1//===--- Hexagon.cpp - Hexagon ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Hexagon.h"
10#include "clang/Driver/CommonArgs.h"
11#include "clang/Driver/Compilation.h"
12#include "clang/Driver/Driver.h"
13#include "clang/Driver/InputInfo.h"
14#include "clang/Options/Options.h"
15#include "llvm/Option/ArgList.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18#include "llvm/Support/VirtualFileSystem.h"
19
20using namespace clang::driver;
21using namespace clang::driver::tools;
22using namespace clang::driver::toolchains;
23using namespace clang;
24using namespace llvm::opt;
25
26// Default hvx-length for various versions.
27static StringRef getDefaultHvxLength(StringRef HvxVer) {
28 return llvm::StringSwitch<StringRef>(HvxVer)
29 .Case(S: "v60", Value: "64b")
30 .Case(S: "v62", Value: "64b")
31 .Case(S: "v65", Value: "64b")
32 .Default(Value: "128b");
33}
34
35static void handleHVXWarnings(const Driver &D, const ArgList &Args) {
36 // Handle the unsupported values passed to mhvx-length.
37 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_length_EQ)) {
38 StringRef Val = A->getValue();
39 if (!Val.equals_insensitive(RHS: "64b") && !Val.equals_insensitive(RHS: "128b"))
40 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
41 << A->getSpelling() << Val;
42 }
43}
44
45// Handle hvx target features explicitly.
46static void handleHVXTargetFeatures(const Driver &D, const ArgList &Args,
47 std::vector<StringRef> &Features,
48 StringRef Cpu, bool &HasHVX) {
49 // Handle HVX warnings.
50 handleHVXWarnings(D, Args);
51
52 auto makeFeature = [&Args](Twine T, bool Enable) -> StringRef {
53 const std::string &S = T.str();
54 StringRef Opt(S);
55 Opt.consume_back(Suffix: "=");
56 if (Opt.starts_with(Prefix: "mno-"))
57 Opt = Opt.drop_front(N: 4);
58 else if (Opt.starts_with(Prefix: "m"))
59 Opt = Opt.drop_front(N: 1);
60 return Args.MakeArgString(Str: Twine(Enable ? "+" : "-") + Twine(Opt));
61 };
62
63 auto withMinus = [](StringRef S) -> std::string {
64 return "-" + S.str();
65 };
66
67 std::optional<std::string> HvxVer =
68 toolchains::HexagonToolChain::GetHVXVersion(Args);
69 HasHVX = HvxVer.has_value();
70 if (HasHVX)
71 Features.push_back(x: makeFeature(Twine("hvx") + *HvxVer, true));
72 else {
73 if (Arg *A = Args.getLastArg(Ids: options::OPT_mno_hexagon_hvx)) {
74 // If there was an explicit -mno-hvx, add -hvx to target features.
75 Features.push_back(x: makeFeature(A->getOption().getName(), false));
76 }
77 }
78
79 StringRef HvxLen =
80 getDefaultHvxLength(HvxVer: HasHVX ? StringRef(*HvxVer) : StringRef(""));
81
82 // Handle -mhvx-length=.
83 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_length_EQ)) {
84 // These flags are valid only if HVX in enabled.
85 if (!HasHVX)
86 D.Diag(DiagID: diag::err_drv_needs_hvx) << withMinus(A->getOption().getName());
87 else if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_length_EQ))
88 HvxLen = A->getValue();
89 }
90
91 if (HasHVX) {
92 StringRef L = makeFeature(Twine("hvx-length") + HvxLen.lower(), true);
93 Features.push_back(x: L);
94 }
95
96 unsigned HvxVerNum = 0;
97 // getAsInteger returns 'true' on error.
98 if (HasHVX) {
99 StringRef HvxVerRef(*HvxVer);
100 if (HvxVerRef.size() <= 1 ||
101 HvxVerRef.drop_front(N: 1).getAsInteger(Radix: 10, Result&: HvxVerNum))
102 HvxVerNum = 0;
103 }
104
105 // Handle HVX floating point flags.
106 auto checkFlagHvxVersion =
107 [&](auto FlagOn, auto FlagOff,
108 unsigned MinVerNum) -> std::optional<StringRef> {
109 // Return an std::optional<StringRef>:
110 // - std::nullopt indicates a verification failure, or that the flag was not
111 // present in Args.
112 // - Otherwise the returned value is that name of the feature to add
113 // to Features.
114 Arg *A = Args.getLastArg(FlagOn, FlagOff);
115 if (!A)
116 return std::nullopt;
117
118 StringRef OptName = A->getOption().getName();
119 if (A->getOption().matches(ID: FlagOff))
120 return makeFeature(OptName, false);
121
122 if (!HasHVX) {
123 D.Diag(DiagID: diag::err_drv_needs_hvx) << withMinus(OptName);
124 return std::nullopt;
125 }
126 if (HvxVerNum < MinVerNum) {
127 D.Diag(DiagID: diag::err_drv_needs_hvx_version)
128 << withMinus(OptName) << ("v" + std::to_string(val: HvxVerNum));
129 return std::nullopt;
130 }
131 return makeFeature(OptName, true);
132 };
133
134 if (auto F = checkFlagHvxVersion(options::OPT_mhexagon_hvx_qfloat,
135 options::OPT_mno_hexagon_hvx_qfloat, 68)) {
136 Features.push_back(x: *F);
137 }
138 if (auto F = checkFlagHvxVersion(options::OPT_mhexagon_hvx_ieee_fp,
139 options::OPT_mno_hexagon_hvx_ieee_fp, 68)) {
140 Features.push_back(x: *F);
141 }
142}
143
144// Hexagon target features.
145void hexagon::getHexagonTargetFeatures(const Driver &D,
146 const llvm::Triple &Triple,
147 const ArgList &Args,
148 std::vector<StringRef> &Features) {
149 handleTargetFeaturesGroup(D, Triple, Args, Features,
150 Group: options::OPT_m_hexagon_Features_Group);
151
152 bool UseLongCalls = false;
153 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_calls,
154 Ids: options::OPT_mno_long_calls)) {
155 if (A->getOption().matches(ID: options::OPT_mlong_calls))
156 UseLongCalls = true;
157 }
158
159 Features.push_back(x: UseLongCalls ? "+long-calls" : "-long-calls");
160
161 bool HasHVX = false;
162 StringRef Cpu(toolchains::HexagonToolChain::GetTargetCPUVersion(Args));
163 // 't' in Cpu denotes tiny-core micro-architecture. For now, the co-processors
164 // have no dependency on micro-architecture.
165 const bool TinyCore = Cpu.contains(C: 't');
166
167 if (TinyCore)
168 Cpu = Cpu.take_front(N: Cpu.size() - 1);
169
170 handleHVXTargetFeatures(D, Args, Features, Cpu, HasHVX);
171
172 if (HexagonToolChain::isAutoHVXEnabled(Args) && !HasHVX)
173 D.Diag(DiagID: diag::warn_drv_needs_hvx) << "auto-vectorization";
174}
175
176// Hexagon tools start.
177void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
178 ArgStringList &CmdArgs) const {
179}
180
181void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
182 const InputInfo &Output,
183 const InputInfoList &Inputs,
184 const ArgList &Args,
185 const char *LinkingOutput) const {
186 claimNoWarnArgs(Args);
187
188 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
189 const Driver &D = HTC.getDriver();
190 ArgStringList CmdArgs;
191
192 CmdArgs.push_back(Elt: "--arch=hexagon");
193
194 RenderExtraToolArgs(JA, CmdArgs);
195
196 const char *AsName = "llvm-mc";
197 CmdArgs.push_back(Elt: "-filetype=obj");
198 CmdArgs.push_back(Elt: Args.MakeArgString(
199 Str: "-mcpu=hexagon" +
200 toolchains::HexagonToolChain::GetTargetCPUVersion(Args)));
201
202 addSanitizerRuntimes(TC: HTC, Args, CmdArgs);
203
204 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
205 if (Output.isFilename()) {
206 CmdArgs.push_back(Elt: "-o");
207 CmdArgs.push_back(Elt: Output.getFilename());
208 } else {
209 CmdArgs.push_back(Elt: "-fsyntax-only");
210 }
211
212 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_ieee_fp,
213 Ids: options::OPT_mno_hexagon_hvx_ieee_fp)) {
214 if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_ieee_fp))
215 CmdArgs.push_back(Elt: "-mhvx-ieee-fp");
216 }
217
218 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
219 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gpsize=" + Twine(*G)));
220 }
221
222 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wa_COMMA, Id1: options::OPT_Xassembler);
223
224 // Only pass -x if gcc will understand it; otherwise hope gcc
225 // understands the suffix correctly. The main use case this would go
226 // wrong in is for linker inputs if they happened to have an odd
227 // suffix; really the only way to get this to happen is a command
228 // like '-x foobar a.c' which will treat a.c like a linker input.
229 //
230 // FIXME: For the linker case specifically, can we safely convert
231 // inputs into '-Wl,' options?
232 for (const auto &II : Inputs) {
233 // Don't try to pass LLVM or AST inputs to a generic gcc.
234 if (types::isLLVMIR(Id: II.getType()))
235 D.Diag(DiagID: clang::diag::err_drv_no_linker_llvm_support)
236 << HTC.getTripleString();
237 else if (II.getType() == types::TY_AST)
238 D.Diag(DiagID: clang::diag::err_drv_no_ast_support)
239 << HTC.getTripleString();
240 else if (II.getType() == types::TY_ModuleFile)
241 D.Diag(DiagID: diag::err_drv_no_module_support)
242 << HTC.getTripleString();
243
244 if (II.isFilename())
245 CmdArgs.push_back(Elt: II.getFilename());
246 else
247 // Don't render as input, we need gcc to do the translations.
248 // FIXME: What is this?
249 II.getInputArg().render(Args, Output&: CmdArgs);
250 }
251
252 auto *Exec = Args.MakeArgString(Str: HTC.GetProgramPath(Name: AsName));
253 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this,
254 args: ResponseFileSupport::AtFileCurCP(),
255 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
256}
257
258void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
259 ArgStringList &CmdArgs) const {
260}
261
262static void
263constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
264 const toolchains::HexagonToolChain &HTC,
265 const InputInfo &Output, const InputInfoList &Inputs,
266 const ArgList &Args, ArgStringList &CmdArgs,
267 const char *LinkingOutput) {
268
269 const Driver &D = HTC.getDriver();
270
271 //----------------------------------------------------------------------------
272 //
273 //----------------------------------------------------------------------------
274 bool IsStatic = Args.hasArg(Ids: options::OPT_static);
275 bool IsShared = Args.hasArg(Ids: options::OPT_shared);
276 bool IsPIE = Args.hasArg(Ids: options::OPT_pie);
277 bool IncStdLib = !Args.hasArg(Ids: options::OPT_nostdlib);
278 bool IncStartFiles = !Args.hasArg(Ids: options::OPT_nostartfiles);
279 bool IncDefLibs = !Args.hasArg(Ids: options::OPT_nodefaultlibs);
280 bool UseG0 = false;
281 bool UseLLD = false;
282 const char *Exec = Args.MakeArgString(Str: HTC.GetLinkerPath(LinkerIsLLD: &UseLLD));
283 UseLLD = UseLLD || llvm::sys::path::filename(path: Exec).ends_with(Suffix: "ld.lld") ||
284 llvm::sys::path::stem(path: Exec).ends_with(Suffix: "ld.lld");
285 bool UseShared = IsShared && !IsStatic;
286 StringRef CpuVer = toolchains::HexagonToolChain::GetTargetCPUVersion(Args);
287
288 bool NeedsSanitizerDeps = addSanitizerRuntimes(TC: HTC, Args, CmdArgs);
289 bool NeedsXRayDeps = addXRayRuntime(TC: HTC, Args, CmdArgs);
290
291 //----------------------------------------------------------------------------
292 // Silence warnings for various options
293 //----------------------------------------------------------------------------
294 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
295 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
296 Args.ClaimAllArgs(Id0: options::OPT_w); // Other warning options are already
297 // handled somewhere else.
298 Args.ClaimAllArgs(Id0: options::OPT_static_libgcc);
299
300 CmdArgs.push_back(Elt: "--eh-frame-hdr");
301 //----------------------------------------------------------------------------
302 //
303 //----------------------------------------------------------------------------
304 if (Args.hasArg(Ids: options::OPT_s))
305 CmdArgs.push_back(Elt: "-s");
306
307 if (Args.hasArg(Ids: options::OPT_r))
308 CmdArgs.push_back(Elt: "-r");
309
310 for (const auto &Opt : HTC.ExtraOpts)
311 CmdArgs.push_back(Elt: Opt.c_str());
312
313 if (!UseLLD) {
314 CmdArgs.push_back(Elt: "-march=hexagon");
315 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mcpu=hexagon" + CpuVer));
316 }
317
318 if (IsShared) {
319 CmdArgs.push_back(Elt: "-shared");
320 // The following should be the default, but doing as hexagon-gcc does.
321 CmdArgs.push_back(Elt: "-call_shared");
322 }
323
324 if (IsStatic)
325 CmdArgs.push_back(Elt: "-static");
326
327 if (IsPIE && !IsShared)
328 CmdArgs.push_back(Elt: "-pie");
329
330 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
331 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-G" + Twine(*G)));
332 UseG0 = *G == 0;
333 }
334
335 CmdArgs.push_back(Elt: "-o");
336 CmdArgs.push_back(Elt: Output.getFilename());
337
338 if (HTC.getTriple().isMusl()) {
339 if (!Args.hasArg(Ids: options::OPT_shared, Ids: options::OPT_static))
340 CmdArgs.push_back(Elt: "-dynamic-linker=/lib/ld-musl-hexagon.so.1");
341
342 if (!Args.hasArg(Ids: options::OPT_shared, Ids: options::OPT_nostartfiles,
343 Ids: options::OPT_nostdlib))
344 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.SysRoot + "/usr/lib/crt1.o"));
345 else if (Args.hasArg(Ids: options::OPT_shared) &&
346 !Args.hasArg(Ids: options::OPT_nostartfiles, Ids: options::OPT_nostdlib))
347 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.SysRoot + "/usr/lib/crti.o"));
348
349 CmdArgs.push_back(
350 Elt: Args.MakeArgString(Str: StringRef("-L") + D.SysRoot + "/usr/lib"));
351 Args.addAllArgs(Output&: CmdArgs, Ids: {options::OPT_T_Group, options::OPT_s,
352 options::OPT_t, options::OPT_u_Group});
353 AddLinkerInputs(TC: HTC, Inputs, Args, CmdArgs, JA);
354
355 ToolChain::UnwindLibType UNW = HTC.GetUnwindLibType(Args);
356
357 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
358 if (NeedsSanitizerDeps) {
359 linkSanitizerRuntimeDeps(TC: HTC, Args, CmdArgs);
360
361 if (UNW != ToolChain::UNW_None)
362 CmdArgs.push_back(Elt: "-lunwind");
363 }
364 if (NeedsXRayDeps)
365 linkXRayRuntimeDeps(TC: HTC, Args, CmdArgs);
366
367 if (!Args.hasArg(Ids: options::OPT_nolibc))
368 CmdArgs.push_back(Elt: "-lc");
369 CmdArgs.push_back(Elt: "-lclang_rt.builtins-hexagon");
370 }
371 if (D.CCCIsCXX()) {
372 if (HTC.ShouldLinkCXXStdlib(Args))
373 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
374 }
375 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
376 for (const auto &LibPath : LibPaths)
377 CmdArgs.push_back(Elt: Args.MakeArgString(Str: StringRef("-L") + LibPath));
378 Args.ClaimAllArgs(Id0: options::OPT_L);
379 return;
380 }
381
382 //----------------------------------------------------------------------------
383 // moslib
384 //----------------------------------------------------------------------------
385 std::vector<std::string> OsLibs;
386 bool HasStandalone = false;
387 for (const Arg *A : Args.filtered(Ids: options::OPT_moslib_EQ)) {
388 A->claim();
389 OsLibs.emplace_back(args: A->getValue());
390 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
391 }
392 if (OsLibs.empty()) {
393 OsLibs.push_back(x: "standalone");
394 HasStandalone = true;
395 }
396
397 //----------------------------------------------------------------------------
398 // Start Files
399 //----------------------------------------------------------------------------
400 const std::string MCpuSuffix = "/" + CpuVer.str();
401 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
402 const std::string RootDir =
403 HTC.getHexagonTargetDir(InstalledDir: D.Dir, PrefixDirs: D.PrefixDirs) + "/";
404 const std::string StartSubDir =
405 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
406
407 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
408 const char *Name) -> std::string {
409 std::string RelName = SubDir + Name;
410 std::string P = HTC.GetFilePath(Name: RelName.c_str());
411 if (llvm::sys::fs::exists(Path: P))
412 return P;
413 return RootDir + RelName;
414 };
415
416 if (IncStdLib && IncStartFiles) {
417 if (!IsShared) {
418 if (HasStandalone) {
419 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
420 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Crt0SA));
421 }
422 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
423 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Crt0));
424 }
425 std::string Init = UseShared
426 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
427 : Find(RootDir, StartSubDir, "/init.o");
428 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Init));
429 }
430
431 //----------------------------------------------------------------------------
432 // Library Search Paths
433 //----------------------------------------------------------------------------
434 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
435 for (const auto &LibPath : LibPaths)
436 CmdArgs.push_back(Elt: Args.MakeArgString(Str: StringRef("-L") + LibPath));
437 Args.ClaimAllArgs(Id0: options::OPT_L);
438
439 //----------------------------------------------------------------------------
440 //
441 //----------------------------------------------------------------------------
442 Args.addAllArgs(Output&: CmdArgs, Ids: {options::OPT_T_Group, options::OPT_s,
443 options::OPT_t, options::OPT_u_Group});
444
445 AddLinkerInputs(TC: HTC, Inputs, Args, CmdArgs, JA);
446
447 //----------------------------------------------------------------------------
448 // Libraries
449 //----------------------------------------------------------------------------
450 if (IncStdLib && IncDefLibs) {
451 if (D.CCCIsCXX()) {
452 if (HTC.ShouldLinkCXXStdlib(Args))
453 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
454 CmdArgs.push_back(Elt: "-lm");
455 }
456
457 CmdArgs.push_back(Elt: "--start-group");
458
459 if (!IsShared) {
460 for (StringRef Lib : OsLibs)
461 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-l" + Lib));
462 if (!Args.hasArg(Ids: options::OPT_nolibc))
463 CmdArgs.push_back(Elt: "-lc");
464 }
465 CmdArgs.push_back(Elt: "-lgcc");
466
467 CmdArgs.push_back(Elt: "--end-group");
468 }
469
470 //----------------------------------------------------------------------------
471 // End files
472 //----------------------------------------------------------------------------
473 if (IncStdLib && IncStartFiles) {
474 std::string Fini = UseShared
475 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
476 : Find(RootDir, StartSubDir, "/fini.o");
477 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Fini));
478 }
479}
480
481void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
482 const InputInfo &Output,
483 const InputInfoList &Inputs,
484 const ArgList &Args,
485 const char *LinkingOutput) const {
486 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
487
488 ArgStringList CmdArgs;
489 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
490 LinkingOutput);
491
492 const char *Exec = Args.MakeArgString(Str: HTC.GetLinkerPath());
493 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this,
494 args: ResponseFileSupport::AtFileCurCP(),
495 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
496}
497// Hexagon tools end.
498
499/// Hexagon Toolchain
500
501std::string HexagonToolChain::getHexagonTargetDir(
502 const std::string &InstalledDir,
503 const SmallVectorImpl<std::string> &PrefixDirs) const {
504 std::string InstallRelDir;
505 const Driver &D = getDriver();
506
507 // Locate the rest of the toolchain ...
508 for (auto &I : PrefixDirs)
509 if (D.getVFS().exists(Path: I))
510 return I;
511
512 if (getVFS().exists(Path: InstallRelDir = InstalledDir + "/../target"))
513 return InstallRelDir;
514
515 return InstalledDir;
516}
517
518std::optional<unsigned>
519HexagonToolChain::getSmallDataThreshold(const ArgList &Args) {
520 StringRef Gn = "";
521 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
522 Gn = A->getValue();
523 } else if (Args.getLastArg(Ids: options::OPT_shared, Ids: options::OPT_fpic,
524 Ids: options::OPT_fPIC)) {
525 Gn = "0";
526 }
527
528 unsigned G;
529 if (!Gn.getAsInteger(Radix: 10, Result&: G))
530 return G;
531
532 return std::nullopt;
533}
534
535std::string HexagonToolChain::getCompilerRTPath() const {
536 SmallString<128> Dir(getDriver().SysRoot);
537 llvm::sys::path::append(path&: Dir, a: "usr", b: "lib");
538 if (!SelectedMultilibs.empty()) {
539 Dir += SelectedMultilibs.back().gccSuffix();
540 }
541 return std::string(Dir);
542}
543
544void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args,
545 ToolChain::path_list &LibPaths) const {
546 const Driver &D = getDriver();
547
548 //----------------------------------------------------------------------------
549 // -L Args
550 //----------------------------------------------------------------------------
551 for (Arg *A : Args.filtered(Ids: options::OPT_L))
552 llvm::append_range(C&: LibPaths, R&: A->getValues());
553
554 //----------------------------------------------------------------------------
555 // Other standard paths
556 //----------------------------------------------------------------------------
557 std::vector<std::string> RootDirs;
558 std::copy(first: D.PrefixDirs.begin(), last: D.PrefixDirs.end(),
559 result: std::back_inserter(x&: RootDirs));
560
561 std::string TargetDir = getHexagonTargetDir(InstalledDir: D.Dir, PrefixDirs: D.PrefixDirs);
562 if (!llvm::is_contained(Range&: RootDirs, Element: TargetDir))
563 RootDirs.push_back(x: TargetDir);
564
565 bool HasPIC = Args.hasArg(Ids: options::OPT_fpic, Ids: options::OPT_fPIC);
566 // Assume G0 with -shared.
567 bool HasG0 = Args.hasArg(Ids: options::OPT_shared);
568 if (auto G = getSmallDataThreshold(Args))
569 HasG0 = *G == 0;
570
571 const std::string CpuVer = GetTargetCPUVersion(Args).str();
572 for (auto &Dir : RootDirs) {
573 std::string LibDir = Dir + "/hexagon/lib";
574 std::string LibDirCpu = LibDir + '/' + CpuVer;
575 if (HasG0) {
576 if (HasPIC)
577 LibPaths.push_back(Elt: LibDirCpu + "/G0/pic");
578 LibPaths.push_back(Elt: LibDirCpu + "/G0");
579 }
580 LibPaths.push_back(Elt: LibDirCpu);
581 LibPaths.push_back(Elt: LibDir);
582 }
583}
584
585HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
586 const llvm::opt::ArgList &Args)
587 : Linux(D, Triple, Args) {
588 const std::string TargetDir = getHexagonTargetDir(InstalledDir: D.Dir, PrefixDirs: D.PrefixDirs);
589
590 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
591 // program paths
592 const std::string BinDir(TargetDir + "/bin");
593 if (D.getVFS().exists(Path: BinDir))
594 getProgramPaths().push_back(Elt: BinDir);
595
596 ToolChain::path_list &LibPaths = getFilePaths();
597
598 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
599 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
600 // support 'linux' we'll need to fix this up
601 LibPaths.clear();
602 getHexagonLibraryPaths(Args, LibPaths);
603}
604
605HexagonToolChain::~HexagonToolChain() {}
606
607void HexagonToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
608 ArgStringList &CmdArgs) const {
609 CXXStdlibType Type = GetCXXStdlibType(Args);
610 ToolChain::UnwindLibType UNW = GetUnwindLibType(Args);
611 if (UNW != ToolChain::UNW_None && UNW != ToolChain::UNW_CompilerRT) {
612 const Arg *A = Args.getLastArg(Ids: options::OPT_unwindlib_EQ);
613 if (A) {
614 getDriver().Diag(DiagID: diag::err_drv_unsupported_unwind_for_platform)
615 << A->getValue() << getTriple().normalize();
616 return;
617 }
618 }
619
620 switch (Type) {
621 case ToolChain::CST_Libcxx:
622 CmdArgs.push_back(Elt: "-lc++");
623 if (Args.hasArg(Ids: options::OPT_fexperimental_library))
624 CmdArgs.push_back(Elt: "-lc++experimental");
625 CmdArgs.push_back(Elt: "-lc++abi");
626 if (UNW != ToolChain::UNW_None)
627 CmdArgs.push_back(Elt: "-lunwind");
628 break;
629
630 case ToolChain::CST_Libstdcxx:
631 CmdArgs.push_back(Elt: "-lstdc++");
632 break;
633 }
634}
635
636Tool *HexagonToolChain::buildAssembler() const {
637 return new tools::hexagon::Assembler(*this);
638}
639
640Tool *HexagonToolChain::buildLinker() const {
641 return new tools::hexagon::Linker(*this);
642}
643
644unsigned HexagonToolChain::getOptimizationLevel(
645 const llvm::opt::ArgList &DriverArgs) const {
646 // Copied in large part from lib/Frontend/CompilerInvocation.cpp.
647 Arg *A = DriverArgs.getLastArg(Ids: options::OPT_O_Group);
648 if (!A)
649 return 0;
650
651 if (A->getOption().matches(ID: options::OPT_O0))
652 return 0;
653 if (A->getOption().matches(ID: options::OPT_Ofast) ||
654 A->getOption().matches(ID: options::OPT_O4))
655 return 3;
656 assert(A->getNumValues() != 0);
657 StringRef S(A->getValue());
658 if (S == "s" || S == "z" || S.empty())
659 return 2;
660 if (S == "g")
661 return 1;
662
663 unsigned OptLevel;
664 if (S.getAsInteger(Radix: 10, Result&: OptLevel))
665 return 0;
666 return OptLevel;
667}
668
669void HexagonToolChain::addClangTargetOptions(const ArgList &DriverArgs,
670 ArgStringList &CC1Args,
671 Action::OffloadKind) const {
672
673 bool UseInitArrayDefault = getTriple().isMusl();
674
675 if (!DriverArgs.hasFlag(Pos: options::OPT_fuse_init_array,
676 Neg: options::OPT_fno_use_init_array,
677 Default: UseInitArrayDefault))
678 CC1Args.push_back(Elt: "-fno-use-init-array");
679
680 if (DriverArgs.hasArg(Ids: options::OPT_ffixed_r19)) {
681 CC1Args.push_back(Elt: "-target-feature");
682 CC1Args.push_back(Elt: "+reserved-r19");
683 }
684 if (isAutoHVXEnabled(Args: DriverArgs)) {
685 CC1Args.push_back(Elt: "-mllvm");
686 CC1Args.push_back(Elt: "-hexagon-autohvx");
687 }
688}
689
690void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
691 ArgStringList &CC1Args) const {
692 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc))
693 return;
694
695 const bool IsELF = !getTriple().isMusl() && !getTriple().isOSLinux();
696 const bool IsLinuxMusl = getTriple().isMusl() && getTriple().isOSLinux();
697
698 const Driver &D = getDriver();
699 SmallString<128> ResourceDirInclude(D.ResourceDir);
700 if (!IsELF) {
701 llvm::sys::path::append(path&: ResourceDirInclude, a: "include");
702 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc) &&
703 (!IsLinuxMusl || DriverArgs.hasArg(Ids: options::OPT_nostdlibinc)))
704 addSystemInclude(DriverArgs, CC1Args, Path: ResourceDirInclude);
705 }
706 if (DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
707 return;
708
709 const bool HasSysRoot = !D.SysRoot.empty();
710 if (HasSysRoot) {
711 SmallString<128> P(D.SysRoot);
712 if (IsLinuxMusl)
713 llvm::sys::path::append(path&: P, a: "usr/include");
714 else
715 llvm::sys::path::append(path&: P, a: "include");
716
717 addExternCSystemInclude(DriverArgs, CC1Args, Path: P.str());
718 // LOCAL_INCLUDE_DIR
719 addSystemInclude(DriverArgs, CC1Args, Path: P + "/usr/local/include");
720 // TOOL_INCLUDE_DIR
721 AddMultilibIncludeArgs(DriverArgs, CC1Args);
722 }
723
724 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc) && IsLinuxMusl)
725 addSystemInclude(DriverArgs, CC1Args, Path: ResourceDirInclude);
726
727 if (HasSysRoot)
728 return;
729 std::string TargetDir = getHexagonTargetDir(InstalledDir: D.Dir, PrefixDirs: D.PrefixDirs);
730 addExternCSystemInclude(DriverArgs, CC1Args, Path: TargetDir + "/hexagon/include");
731}
732
733void HexagonToolChain::addLibCxxIncludePaths(
734 const llvm::opt::ArgList &DriverArgs,
735 llvm::opt::ArgStringList &CC1Args) const {
736 const Driver &D = getDriver();
737 if (!D.SysRoot.empty() && getTriple().isMusl())
738 addLibStdCXXIncludePaths(IncludeDir: D.SysRoot + "/usr/include/c++/v1", Triple: "", IncludeSuffix: "",
739 DriverArgs, CC1Args);
740 else if (getTriple().isMusl())
741 addLibStdCXXIncludePaths(IncludeDir: "/usr/include/c++/v1", Triple: "", IncludeSuffix: "", DriverArgs,
742 CC1Args);
743 else {
744 std::string TargetDir = getHexagonTargetDir(InstalledDir: D.Dir, PrefixDirs: D.PrefixDirs);
745 addLibStdCXXIncludePaths(IncludeDir: TargetDir + "/hexagon/include/c++/v1", Triple: "", IncludeSuffix: "",
746 DriverArgs, CC1Args);
747 }
748}
749void HexagonToolChain::addLibStdCxxIncludePaths(
750 const llvm::opt::ArgList &DriverArgs,
751 llvm::opt::ArgStringList &CC1Args) const {
752 const Driver &D = getDriver();
753 std::string TargetDir = getHexagonTargetDir(InstalledDir: D.Dir, PrefixDirs: D.PrefixDirs);
754 addLibStdCXXIncludePaths(IncludeDir: TargetDir + "/hexagon/include/c++", Triple: "", IncludeSuffix: "",
755 DriverArgs, CC1Args);
756}
757
758ToolChain::CXXStdlibType
759HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
760 Arg *A = Args.getLastArg(Ids: options::OPT_stdlib_EQ);
761 if (!A) {
762 if (getTriple().isMusl())
763 return ToolChain::CST_Libcxx;
764 else
765 return ToolChain::CST_Libstdcxx;
766 }
767 StringRef Value = A->getValue();
768 if (Value != "libstdc++" && Value != "libc++")
769 getDriver().Diag(DiagID: diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
770
771 if (Value == "libstdc++")
772 return ToolChain::CST_Libstdcxx;
773 else if (Value == "libc++")
774 return ToolChain::CST_Libcxx;
775 else
776 return ToolChain::CST_Libstdcxx;
777}
778
779bool HexagonToolChain::isAutoHVXEnabled(const llvm::opt::ArgList &Args) {
780 if (Arg *A = Args.getLastArg(Ids: options::OPT_fvectorize,
781 Ids: options::OPT_fno_vectorize))
782 return A->getOption().matches(ID: options::OPT_fvectorize);
783 return false;
784}
785
786//
787// Returns the default CPU for Hexagon. This is the default compilation target
788// if no Hexagon processor is selected at the command-line.
789//
790StringRef HexagonToolChain::GetDefaultCPU() { return "hexagonv68"; }
791
792StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
793 Arg *CpuArg = nullptr;
794 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
795 CpuArg = A;
796
797 StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
798 CPU.consume_front(Prefix: "hexagon");
799 return CPU;
800}
801
802std::optional<std::string>
803HexagonToolChain::GetHVXVersion(const ArgList &Args) {
804 // Handle -mh[v]x= and -mno-hvx. If versioned and versionless flags
805 // are both present, the last one wins.
806 Arg *HvxEnablingArg =
807 Args.getLastArg(Ids: options::OPT_mhexagon_hvx, Ids: options::OPT_mhexagon_hvx_EQ,
808 Ids: options::OPT_mno_hexagon_hvx);
809 if (!HvxEnablingArg ||
810 HvxEnablingArg->getOption().matches(ID: options::OPT_mno_hexagon_hvx))
811 return std::nullopt;
812
813 StringRef Cpu(toolchains::HexagonToolChain::GetTargetCPUVersion(Args));
814 std::string HvxVer;
815 if (!Cpu.empty() && (Cpu.back() == 'T' || Cpu.back() == 't'))
816 HvxVer = Cpu.drop_back(N: 1).str();
817 else
818 HvxVer = Cpu.str();
819
820 if (HvxEnablingArg->getOption().matches(ID: options::OPT_mhexagon_hvx_EQ))
821 HvxVer = StringRef(HvxEnablingArg->getValue()).lower();
822
823 return HvxVer;
824}
825
826// End Hexagon
827