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

source code of clang/lib/Driver/ToolChains/Hexagon.cpp