1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
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 "clang/Driver/ToolChain.h"
10 #include "InputInfo.h"
11 #include "ToolChains/Arch/ARM.h"
12 #include "ToolChains/Arch/Mips.h"
13 #include "ToolChains/Arch/RISCV.h"
14 #include "ToolChains/Clang.h"
15 #include "ToolChains/InterfaceStubs.h"
16 #include "ToolChains/Flang.h"
17 #include "clang/Basic/ObjCRuntime.h"
18 #include "clang/Basic/Sanitizers.h"
19 #include "clang/Config/config.h"
20 #include "clang/Driver/Action.h"
21 #include "clang/Driver/Driver.h"
22 #include "clang/Driver/DriverDiagnostic.h"
23 #include "clang/Driver/Job.h"
24 #include "clang/Driver/Options.h"
25 #include "clang/Driver/SanitizerArgs.h"
26 #include "clang/Driver/XRayArgs.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/MC/MCTargetOptions.h"
34 #include "llvm/Option/Arg.h"
35 #include "llvm/Option/ArgList.h"
36 #include "llvm/Option/OptTable.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/VersionTuple.h"
44 #include "llvm/Support/VirtualFileSystem.h"
45 #include <cassert>
46 #include <cstddef>
47 #include <cstring>
48 #include <string>
49
50 using namespace clang;
51 using namespace driver;
52 using namespace tools;
53 using namespace llvm;
54 using namespace llvm::opt;
55
GetRTTIArgument(const ArgList & Args)56 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
57 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
58 options::OPT_fno_rtti, options::OPT_frtti);
59 }
60
CalculateRTTIMode(const ArgList & Args,const llvm::Triple & Triple,const Arg * CachedRTTIArg)61 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
62 const llvm::Triple &Triple,
63 const Arg *CachedRTTIArg) {
64 // Explicit rtti/no-rtti args
65 if (CachedRTTIArg) {
66 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
67 return ToolChain::RM_Enabled;
68 else
69 return ToolChain::RM_Disabled;
70 }
71
72 // -frtti is default, except for the PS4 CPU.
73 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
74 }
75
ToolChain(const Driver & D,const llvm::Triple & T,const ArgList & Args)76 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
77 const ArgList &Args)
78 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
79 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
80 if (D.CCCIsCXX()) {
81 if (auto CXXStdlibPath = getCXXStdlibPath())
82 getFilePaths().push_back(*CXXStdlibPath);
83 }
84
85 if (auto RuntimePath = getRuntimePath())
86 getLibraryPaths().push_back(*RuntimePath);
87
88 std::string CandidateLibPath = getArchSpecificLibPath();
89 if (getVFS().exists(CandidateLibPath))
90 getFilePaths().push_back(CandidateLibPath);
91
92 IsCheriPurecap = Triple.getEnvironment() == llvm::Triple::CheriPurecap;
93 if (Triple.isMIPS() && tools::mips::hasMipsAbiArg(Args, "purecap"))
94 IsCheriPurecap = true;
95 if (Triple.isRISCV() && tools::riscv::isCheriPurecap(Args, Triple))
96 IsCheriPurecap = true;
97
98 // FIXME: Should we update triple enviroment to purecap? Or will that break RISCV?
99 }
100
setTripleEnvironment(llvm::Triple::EnvironmentType Env)101 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
102 Triple.setEnvironment(Env);
103 if (EffectiveTriple != llvm::Triple())
104 EffectiveTriple.setEnvironment(Env);
105 }
106
107 ToolChain::~ToolChain() = default;
108
getVFS() const109 llvm::vfs::FileSystem &ToolChain::getVFS() const {
110 return getDriver().getVFS();
111 }
112
useIntegratedAs() const113 bool ToolChain::useIntegratedAs() const {
114 return Args.hasFlag(options::OPT_fintegrated_as,
115 options::OPT_fno_integrated_as,
116 IsIntegratedAssemblerDefault());
117 }
118
useRelaxRelocations() const119 bool ToolChain::useRelaxRelocations() const {
120 return ENABLE_X86_RELAX_RELOCATIONS;
121 }
122
isNoExecStackDefault() const123 bool ToolChain::isNoExecStackDefault() const {
124 return false;
125 }
126
isCheriPurecap() const127 bool ToolChain::isCheriPurecap() const {
128 return IsCheriPurecap ||
129 EffectiveTriple.getEnvironment() == llvm::Triple::CheriPurecap;
130 }
131
getSanitizerArgs() const132 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
133 if (!SanitizerArguments.get())
134 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
135 return *SanitizerArguments.get();
136 }
137
getXRayArgs() const138 const XRayArgs& ToolChain::getXRayArgs() const {
139 if (!XRayArguments.get())
140 XRayArguments.reset(new XRayArgs(*this, Args));
141 return *XRayArguments.get();
142 }
143
144 namespace {
145
146 struct DriverSuffix {
147 const char *Suffix;
148 const char *ModeFlag;
149 };
150
151 } // namespace
152
FindDriverSuffix(StringRef ProgName,size_t & Pos)153 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
154 // A list of known driver suffixes. Suffixes are compared against the
155 // program name in order. If there is a match, the frontend type is updated as
156 // necessary by applying the ModeFlag.
157 static const DriverSuffix DriverSuffixes[] = {
158 {"clang", nullptr},
159 {"clang++", "--driver-mode=g++"},
160 {"clang-c++", "--driver-mode=g++"},
161 {"clang-cc", nullptr},
162 {"clang-cpp", "--driver-mode=cpp"},
163 {"clang-g++", "--driver-mode=g++"},
164 {"clang-gcc", nullptr},
165 {"clang-cl", "--driver-mode=cl"},
166 {"cc", nullptr},
167 {"cpp", "--driver-mode=cpp"},
168 {"cl", "--driver-mode=cl"},
169 {"++", "--driver-mode=g++"},
170 {"flang", "--driver-mode=flang"},
171 };
172
173 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
174 StringRef Suffix(DriverSuffixes[i].Suffix);
175 if (ProgName.endswith(Suffix)) {
176 Pos = ProgName.size() - Suffix.size();
177 return &DriverSuffixes[i];
178 }
179 }
180 return nullptr;
181 }
182
183 /// Normalize the program name from argv[0] by stripping the file extension if
184 /// present and lower-casing the string on Windows.
normalizeProgramName(llvm::StringRef Argv0)185 static std::string normalizeProgramName(llvm::StringRef Argv0) {
186 std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
187 #ifdef _WIN32
188 // Transform to lowercase for case insensitive file systems.
189 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
190 #endif
191 return ProgName;
192 }
193
parseDriverSuffix(StringRef ProgName,size_t & Pos)194 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
195 // Try to infer frontend type and default target from the program name by
196 // comparing it against DriverSuffixes in order.
197
198 // If there is a match, the function tries to identify a target as prefix.
199 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
200 // prefix "x86_64-linux". If such a target prefix is found, it may be
201 // added via -target as implicit first argument.
202 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
203
204 if (!DS) {
205 // Try again after stripping any trailing version number:
206 // clang++3.5 -> clang++
207 ProgName = ProgName.rtrim("0123456789.");
208 DS = FindDriverSuffix(ProgName, Pos);
209 }
210
211 if (!DS) {
212 // Try again after stripping trailing -component.
213 // clang++-tot -> clang++
214 ProgName = ProgName.slice(0, ProgName.rfind('-'));
215 DS = FindDriverSuffix(ProgName, Pos);
216 }
217 return DS;
218 }
219
220 ParsedClangName
getTargetAndModeFromProgramName(StringRef PN)221 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
222 std::string ProgName = normalizeProgramName(PN);
223 size_t SuffixPos;
224 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
225 if (!DS)
226 return {};
227 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
228
229 size_t LastComponent = ProgName.rfind('-', SuffixPos);
230 if (LastComponent == std::string::npos)
231 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
232 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
233 SuffixEnd - LastComponent - 1);
234
235 // Infer target from the prefix.
236 StringRef Prefix(ProgName);
237 Prefix = Prefix.slice(0, LastComponent);
238 std::string IgnoredError;
239 bool IsRegistered =
240 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
241 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
242 IsRegistered};
243 }
244
getDefaultUniversalArchName() const245 StringRef ToolChain::getDefaultUniversalArchName() const {
246 // In universal driver terms, the arch name accepted by -arch isn't exactly
247 // the same as the ones that appear in the triple. Roughly speaking, this is
248 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
249 switch (Triple.getArch()) {
250 case llvm::Triple::aarch64:
251 return "arm64";
252 case llvm::Triple::aarch64_32:
253 return "arm64_32";
254 case llvm::Triple::ppc:
255 return "ppc";
256 case llvm::Triple::ppc64:
257 return "ppc64";
258 case llvm::Triple::ppc64le:
259 return "ppc64le";
260 default:
261 return Triple.getArchName();
262 }
263 }
264
getInputFilename(const InputInfo & Input) const265 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
266 return Input.getFilename();
267 }
268
IsUnwindTablesDefault(const ArgList & Args) const269 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
270 return false;
271 }
272
getClang() const273 Tool *ToolChain::getClang() const {
274 if (!Clang)
275 Clang.reset(new tools::Clang(*this));
276 return Clang.get();
277 }
278
getFlang() const279 Tool *ToolChain::getFlang() const {
280 if (!Flang)
281 Flang.reset(new tools::Flang(*this));
282 return Flang.get();
283 }
284
buildAssembler() const285 Tool *ToolChain::buildAssembler() const {
286 return new tools::ClangAs(*this);
287 }
288
buildLinker() const289 Tool *ToolChain::buildLinker() const {
290 llvm_unreachable("Linking is not supported by this toolchain");
291 }
292
buildStaticLibTool() const293 Tool *ToolChain::buildStaticLibTool() const {
294 llvm_unreachable("Creating static lib is not supported by this toolchain");
295 }
296
getAssemble() const297 Tool *ToolChain::getAssemble() const {
298 if (!Assemble)
299 Assemble.reset(buildAssembler());
300 return Assemble.get();
301 }
302
getClangAs() const303 Tool *ToolChain::getClangAs() const {
304 if (!Assemble)
305 Assemble.reset(new tools::ClangAs(*this));
306 return Assemble.get();
307 }
308
getLink() const309 Tool *ToolChain::getLink() const {
310 if (!Link)
311 Link.reset(buildLinker());
312 return Link.get();
313 }
314
getStaticLibTool() const315 Tool *ToolChain::getStaticLibTool() const {
316 if (!StaticLibTool)
317 StaticLibTool.reset(buildStaticLibTool());
318 return StaticLibTool.get();
319 }
320
getIfsMerge() const321 Tool *ToolChain::getIfsMerge() const {
322 if (!IfsMerge)
323 IfsMerge.reset(new tools::ifstool::Merger(*this));
324 return IfsMerge.get();
325 }
326
getOffloadBundler() const327 Tool *ToolChain::getOffloadBundler() const {
328 if (!OffloadBundler)
329 OffloadBundler.reset(new tools::OffloadBundler(*this));
330 return OffloadBundler.get();
331 }
332
getOffloadWrapper() const333 Tool *ToolChain::getOffloadWrapper() const {
334 if (!OffloadWrapper)
335 OffloadWrapper.reset(new tools::OffloadWrapper(*this));
336 return OffloadWrapper.get();
337 }
338
getTool(Action::ActionClass AC) const339 Tool *ToolChain::getTool(Action::ActionClass AC) const {
340 switch (AC) {
341 case Action::AssembleJobClass:
342 return getAssemble();
343
344 case Action::IfsMergeJobClass:
345 return getIfsMerge();
346
347 case Action::LinkJobClass:
348 return getLink();
349
350 case Action::StaticLibJobClass:
351 return getStaticLibTool();
352
353 case Action::InputClass:
354 case Action::BindArchClass:
355 case Action::OffloadClass:
356 case Action::LipoJobClass:
357 case Action::DsymutilJobClass:
358 case Action::VerifyDebugInfoJobClass:
359 llvm_unreachable("Invalid tool kind.");
360
361 case Action::CompileJobClass:
362 case Action::PrecompileJobClass:
363 case Action::HeaderModulePrecompileJobClass:
364 case Action::PreprocessJobClass:
365 case Action::AnalyzeJobClass:
366 case Action::MigrateJobClass:
367 case Action::VerifyPCHJobClass:
368 case Action::BackendJobClass:
369 return getClang();
370
371 case Action::OffloadBundlingJobClass:
372 case Action::OffloadUnbundlingJobClass:
373 return getOffloadBundler();
374
375 case Action::OffloadWrapperJobClass:
376 return getOffloadWrapper();
377 }
378
379 llvm_unreachable("Invalid tool kind.");
380 }
381
getArchNameForCompilerRTLib(const ToolChain & TC,const ArgList & Args)382 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
383 const ArgList &Args) {
384 const llvm::Triple &Triple = TC.getTriple();
385 bool IsWindows = Triple.isOSWindows();
386
387 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
388 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
389 ? "armhf"
390 : "arm";
391
392 // For historic reasons, Android library is using i686 instead of i386.
393 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
394 return "i686";
395
396 if (Triple.isMIPS() && Triple.getEnvironment() == llvm::Triple::CheriPurecap) {
397 assert(Triple.getSubArch() != llvm::Triple::NoSubArch && "purecap triple should have subarch");
398 return Triple.getArchName();
399 }
400
401 return llvm::Triple::getArchTypeName(TC.getArch());
402 }
403
getOSLibName() const404 StringRef ToolChain::getOSLibName() const {
405 switch (Triple.getOS()) {
406 case llvm::Triple::FreeBSD:
407 return "freebsd";
408 case llvm::Triple::NetBSD:
409 return "netbsd";
410 case llvm::Triple::OpenBSD:
411 return "openbsd";
412 case llvm::Triple::Solaris:
413 return "sunos";
414 default:
415 return getOS();
416 }
417 }
418
getCompilerRTPath() const419 std::string ToolChain::getCompilerRTPath() const {
420 SmallString<128> Path(getDriver().ResourceDir);
421 if (Triple.isOSUnknown()) {
422 llvm::sys::path::append(Path, "lib");
423 } else {
424 llvm::sys::path::append(Path, "lib", getOSLibName());
425 }
426 return std::string(Path.str());
427 }
428
getCompilerRTBasename(const ArgList & Args,StringRef Component,FileType Type,bool AddArch) const429 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
430 StringRef Component, FileType Type,
431 bool AddArch) const {
432 const llvm::Triple &TT = getTriple();
433 bool IsITANMSVCWindows =
434 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
435
436 const char *Prefix =
437 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
438 const char *Suffix;
439 switch (Type) {
440 case ToolChain::FT_Object:
441 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
442 break;
443 case ToolChain::FT_Static:
444 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
445 break;
446 case ToolChain::FT_Shared:
447 Suffix = Triple.isOSWindows()
448 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
449 : ".so";
450 break;
451 }
452
453 std::string ArchAndEnv;
454 if (AddArch) {
455 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
456 const char *Env = TT.isAndroid() ? "-android" : "";
457 ArchAndEnv = ("-" + Arch + Env).str();
458 }
459 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
460 }
461
getCompilerRT(const ArgList & Args,StringRef Component,FileType Type) const462 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
463 FileType Type) const {
464 // Check for runtime files in the new layout without the architecture first.
465 std::string CRTBasename =
466 getCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
467 for (const auto &LibPath : getLibraryPaths()) {
468 SmallString<128> P(LibPath);
469 llvm::sys::path::append(P, CRTBasename);
470 if (getVFS().exists(P))
471 return std::string(P.str());
472 }
473
474 // Fall back to the old expected compiler-rt name if the new one does not
475 // exist.
476 CRTBasename = getCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
477 SmallString<128> Path(getCompilerRTPath());
478 llvm::sys::path::append(Path, CRTBasename);
479 return std::string(Path.str());
480 }
481
getCompilerRTArgString(const llvm::opt::ArgList & Args,StringRef Component,FileType Type) const482 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
483 StringRef Component,
484 FileType Type) const {
485 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
486 }
487
488
getRuntimePath() const489 Optional<std::string> ToolChain::getRuntimePath() const {
490 SmallString<128> P;
491
492 // First try the triple passed to driver as --target=<triple>.
493 P.assign(D.ResourceDir);
494 llvm::sys::path::append(P, "lib", D.getTargetTriple());
495 if (getVFS().exists(P))
496 return llvm::Optional<std::string>(std::string(P.str()));
497
498 // Second try the normalized triple.
499 P.assign(D.ResourceDir);
500 llvm::sys::path::append(P, "lib", Triple.str());
501 if (getVFS().exists(P))
502 return llvm::Optional<std::string>(std::string(P.str()));
503
504 return None;
505 }
506
getCXXStdlibPath() const507 Optional<std::string> ToolChain::getCXXStdlibPath() const {
508 SmallString<128> P;
509
510 // First try the triple passed to driver as --target=<triple>.
511 P.assign(D.Dir);
512 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
513 if (getVFS().exists(P))
514 return llvm::Optional<std::string>(std::string(P.str()));
515
516 // Second try the normalized triple.
517 P.assign(D.Dir);
518 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
519 if (getVFS().exists(P))
520 return llvm::Optional<std::string>(std::string(P.str()));
521
522 return None;
523 }
524
getArchSpecificLibPath() const525 std::string ToolChain::getArchSpecificLibPath() const {
526 SmallString<128> Path(getDriver().ResourceDir);
527 llvm::sys::path::append(Path, "lib", getOSLibName(),
528 llvm::Triple::getArchTypeName(getArch()));
529 return std::string(Path.str());
530 }
531
needsProfileRT(const ArgList & Args)532 bool ToolChain::needsProfileRT(const ArgList &Args) {
533 if (Args.hasArg(options::OPT_noprofilelib))
534 return false;
535
536 return Args.hasArg(options::OPT_fprofile_generate) ||
537 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
538 Args.hasArg(options::OPT_fcs_profile_generate) ||
539 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
540 Args.hasArg(options::OPT_fprofile_instr_generate) ||
541 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
542 Args.hasArg(options::OPT_fcreate_profile) ||
543 Args.hasArg(options::OPT_forder_file_instrumentation);
544 }
545
needsGCovInstrumentation(const llvm::opt::ArgList & Args)546 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
547 return Args.hasArg(options::OPT_coverage) ||
548 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
549 false);
550 }
551
SelectTool(const JobAction & JA) const552 Tool *ToolChain::SelectTool(const JobAction &JA) const {
553 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
554 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
555 Action::ActionClass AC = JA.getKind();
556 if (AC == Action::AssembleJobClass && useIntegratedAs())
557 return getClangAs();
558 return getTool(AC);
559 }
560
GetFilePath(const char * Name) const561 std::string ToolChain::GetFilePath(const char *Name) const {
562 return D.GetFilePath(Name, *this);
563 }
564
GetProgramPath(const char * Name) const565 std::string ToolChain::GetProgramPath(const char *Name) const {
566 return D.GetProgramPath(Name, *this);
567 }
568
GetLinkerPath() const569 std::string ToolChain::GetLinkerPath() const {
570 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
571 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
572
573 if (llvm::sys::path::is_absolute(UseLinker)) {
574 // If we're passed what looks like an absolute path, don't attempt to
575 // second-guess that.
576 if (llvm::sys::fs::can_execute(UseLinker))
577 return std::string(UseLinker);
578 } else if (UseLinker.empty() || UseLinker == "ld") {
579 // If we're passed -fuse-ld= with no argument, or with the argument ld,
580 // then use whatever the default system linker is.
581 return GetProgramPath(getDefaultLinker());
582 } else {
583 llvm::SmallString<8> LinkerName;
584 if (Triple.isOSDarwin())
585 LinkerName.append("ld64.");
586 else
587 LinkerName.append("ld.");
588 LinkerName.append(UseLinker);
589
590 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
591 if (llvm::sys::fs::can_execute(LinkerPath))
592 return LinkerPath;
593 }
594
595 if (A)
596 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
597
598 return GetProgramPath(getDefaultLinker());
599 }
600
GetStaticLibToolPath() const601 std::string ToolChain::GetStaticLibToolPath() const {
602 // TODO: Add support for static lib archiving on Windows
603 return GetProgramPath("llvm-ar");
604 }
605
LookupTypeForExtension(StringRef Ext) const606 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
607 types::ID id = types::lookupTypeForExtension(Ext);
608
609 // Flang always runs the preprocessor and has no notion of "preprocessed
610 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
611 // them differently.
612 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
613 id = types::TY_Fortran;
614
615 return id;
616 }
617
HasNativeLLVMSupport() const618 bool ToolChain::HasNativeLLVMSupport() const {
619 return false;
620 }
621
isCrossCompiling() const622 bool ToolChain::isCrossCompiling() const {
623 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
624 switch (HostTriple.getArch()) {
625 // The A32/T32/T16 instruction sets are not separate architectures in this
626 // context.
627 case llvm::Triple::arm:
628 case llvm::Triple::armeb:
629 case llvm::Triple::thumb:
630 case llvm::Triple::thumbeb:
631 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
632 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
633 default:
634 return HostTriple.getArch() != getArch();
635 }
636 }
637
getDefaultObjCRuntime(bool isNonFragile) const638 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
639 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
640 VersionTuple());
641 }
642
643 llvm::ExceptionHandling
GetExceptionModel(const llvm::opt::ArgList & Args) const644 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
645 return llvm::ExceptionHandling::None;
646 }
647
isThreadModelSupported(const StringRef Model) const648 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
649 if (Model == "single") {
650 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
651 return Triple.getArch() == llvm::Triple::arm ||
652 Triple.getArch() == llvm::Triple::armeb ||
653 Triple.getArch() == llvm::Triple::thumb ||
654 Triple.getArch() == llvm::Triple::thumbeb ||
655 Triple.getArch() == llvm::Triple::wasm32 ||
656 Triple.getArch() == llvm::Triple::wasm64;
657 } else if (Model == "posix")
658 return true;
659
660 return false;
661 }
662
ComputeLLVMTriple(const ArgList & Args,types::ID InputType) const663 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
664 types::ID InputType) const {
665 switch (getTriple().getArch()) {
666 default:
667 return getTripleString();
668
669 case llvm::Triple::x86_64: {
670 llvm::Triple Triple = getTriple();
671 if (!Triple.isOSBinFormatMachO())
672 return getTripleString();
673
674 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
675 // x86_64h goes in the triple. Other -march options just use the
676 // vanilla triple we already have.
677 StringRef MArch = A->getValue();
678 if (MArch == "x86_64h")
679 Triple.setArchName(MArch);
680 }
681 return Triple.getTriple();
682 }
683 case llvm::Triple::aarch64: {
684 llvm::Triple Triple = getTriple();
685 if (!Triple.isOSBinFormatMachO())
686 return getTripleString();
687
688 // FIXME: older versions of ld64 expect the "arm64" component in the actual
689 // triple string and query it to determine whether an LTO file can be
690 // handled. Remove this when we don't care any more.
691 Triple.setArchName("arm64");
692 return Triple.getTriple();
693 }
694 case llvm::Triple::aarch64_32:
695 return getTripleString();
696 case llvm::Triple::arm:
697 case llvm::Triple::armeb:
698 case llvm::Triple::thumb:
699 case llvm::Triple::thumbeb: {
700 // FIXME: Factor into subclasses.
701 llvm::Triple Triple = getTriple();
702 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
703 getTriple().getArch() == llvm::Triple::thumbeb;
704
705 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
706 // '-mbig-endian'/'-EB'.
707 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
708 options::OPT_mbig_endian)) {
709 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
710 }
711
712 // Thumb2 is the default for V7 on Darwin.
713 //
714 // FIXME: Thumb should just be another -target-feaure, not in the triple.
715 StringRef MCPU, MArch;
716 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
717 MCPU = A->getValue();
718 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
719 MArch = A->getValue();
720 std::string CPU =
721 Triple.isOSBinFormatMachO()
722 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
723 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
724 StringRef Suffix =
725 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
726 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
727 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
728 getTriple().isOSBinFormatMachO());
729 // FIXME: this is invalid for WindowsCE
730 if (getTriple().isOSWindows())
731 ThumbDefault = true;
732 std::string ArchName;
733 if (IsBigEndian)
734 ArchName = "armeb";
735 else
736 ArchName = "arm";
737
738 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
739 // M-Class CPUs/architecture variants, which is not supported.
740 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
741 options::OPT_mno_thumb, ThumbDefault);
742 if (IsMProfile && ARMModeRequested) {
743 if (!MCPU.empty())
744 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
745 else
746 getDriver().Diag(diag::err_arch_unsupported_isa)
747 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
748 }
749
750 // Check to see if an explicit choice to use thumb has been made via
751 // -mthumb. For assembler files we must check for -mthumb in the options
752 // passed to the assembler via -Wa or -Xassembler.
753 bool IsThumb = false;
754 if (InputType != types::TY_PP_Asm)
755 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
756 ThumbDefault);
757 else {
758 // Ideally we would check for these flags in
759 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
760 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
761 // -mno-arm.
762 for (const auto *A :
763 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
764 for (StringRef Value : A->getValues()) {
765 if (Value == "-mthumb")
766 IsThumb = true;
767 }
768 }
769 }
770 // Assembly files should start in ARM mode, unless arch is M-profile, or
771 // -mthumb has been passed explicitly to the assembler. Windows is always
772 // thumb.
773 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
774 if (IsBigEndian)
775 ArchName = "thumbeb";
776 else
777 ArchName = "thumb";
778 }
779 Triple.setArchName(ArchName + Suffix.str());
780
781 return Triple.getTriple();
782 }
783 }
784 }
785
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const786 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
787 types::ID InputType) const {
788 return ComputeLLVMTriple(Args, InputType);
789 }
790
computeSysRoot() const791 std::string ToolChain::computeSysRoot() const {
792 return D.SysRoot;
793 }
794
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const795 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
796 ArgStringList &CC1Args) const {
797 // Each toolchain should provide the appropriate include flags.
798 }
799
addClangTargetOptions(const ArgList & DriverArgs,ArgStringList & CC1Args,Action::OffloadKind DeviceOffloadKind) const800 void ToolChain::addClangTargetOptions(
801 const ArgList &DriverArgs, ArgStringList &CC1Args,
802 Action::OffloadKind DeviceOffloadKind) const {}
803
addClangWarningOptions(ArgStringList & CC1Args) const804 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
805
addProfileRTLibs(const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs) const806 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
807 llvm::opt::ArgStringList &CmdArgs) const {
808 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
809 return;
810
811 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
812 }
813
GetRuntimeLibType(const ArgList & Args) const814 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
815 const ArgList &Args) const {
816 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
817 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
818
819 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
820 if (LibName == "compiler-rt")
821 return ToolChain::RLT_CompilerRT;
822 else if (LibName == "libgcc")
823 return ToolChain::RLT_Libgcc;
824 else if (LibName == "platform")
825 return GetDefaultRuntimeLibType();
826
827 if (A)
828 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
829
830 return GetDefaultRuntimeLibType();
831 }
832
GetUnwindLibType(const ArgList & Args) const833 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
834 const ArgList &Args) const {
835 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
836 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
837
838 if (LibName == "none")
839 return ToolChain::UNW_None;
840 else if (LibName == "platform" || LibName == "") {
841 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
842 if (RtLibType == ToolChain::RLT_CompilerRT)
843 return ToolChain::UNW_None;
844 else if (RtLibType == ToolChain::RLT_Libgcc)
845 return ToolChain::UNW_Libgcc;
846 } else if (LibName == "libunwind") {
847 if (GetRuntimeLibType(Args) == RLT_Libgcc)
848 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
849 return ToolChain::UNW_CompilerRT;
850 } else if (LibName == "libgcc")
851 return ToolChain::UNW_Libgcc;
852
853 if (A)
854 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
855 << A->getAsString(Args);
856
857 return GetDefaultUnwindLibType();
858 }
859
GetCXXStdlibType(const ArgList & Args) const860 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
861 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
862 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
863
864 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
865 if (LibName == "libc++")
866 return ToolChain::CST_Libcxx;
867 else if (LibName == "libstdc++")
868 return ToolChain::CST_Libstdcxx;
869 else if (LibName == "platform")
870 return GetDefaultCXXStdlibType();
871
872 if (A)
873 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
874
875 return GetDefaultCXXStdlibType();
876 }
877
878 /// Utility function to add a system include directory to CC1 arguments.
addSystemInclude(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)879 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
880 ArgStringList &CC1Args,
881 const Twine &Path) {
882 CC1Args.push_back("-internal-isystem");
883 CC1Args.push_back(DriverArgs.MakeArgString(Path));
884 }
885
886 /// Utility function to add a system include directory with extern "C"
887 /// semantics to CC1 arguments.
888 ///
889 /// Note that this should be used rarely, and only for directories that
890 /// historically and for legacy reasons are treated as having implicit extern
891 /// "C" semantics. These semantics are *ignored* by and large today, but its
892 /// important to preserve the preprocessor changes resulting from the
893 /// classification.
addExternCSystemInclude(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)894 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
895 ArgStringList &CC1Args,
896 const Twine &Path) {
897 CC1Args.push_back("-internal-externc-isystem");
898 CC1Args.push_back(DriverArgs.MakeArgString(Path));
899 }
900
addExternCSystemIncludeIfExists(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)901 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
902 ArgStringList &CC1Args,
903 const Twine &Path) {
904 if (llvm::sys::fs::exists(Path))
905 addExternCSystemInclude(DriverArgs, CC1Args, Path);
906 }
907
908 /// Utility function to add a list of system include directories to CC1.
addSystemIncludes(const ArgList & DriverArgs,ArgStringList & CC1Args,ArrayRef<StringRef> Paths)909 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
910 ArgStringList &CC1Args,
911 ArrayRef<StringRef> Paths) {
912 for (const auto &Path : Paths) {
913 CC1Args.push_back("-internal-isystem");
914 CC1Args.push_back(DriverArgs.MakeArgString(Path));
915 }
916 }
917
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const918 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
919 ArgStringList &CC1Args) const {
920 // Header search paths should be handled by each of the subclasses.
921 // Historically, they have not been, and instead have been handled inside of
922 // the CC1-layer frontend. As the logic is hoisted out, this generic function
923 // will slowly stop being called.
924 //
925 // While it is being called, replicate a bit of a hack to propagate the
926 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
927 // header search paths with it. Once all systems are overriding this
928 // function, the CC1 flag and this line can be removed.
929 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
930 }
931
AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args) const932 void ToolChain::AddClangCXXStdlibIsystemArgs(
933 const llvm::opt::ArgList &DriverArgs,
934 llvm::opt::ArgStringList &CC1Args) const {
935 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
936 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
937 for (const auto &P :
938 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
939 addSystemInclude(DriverArgs, CC1Args, P);
940 }
941
ShouldLinkCXXStdlib(const llvm::opt::ArgList & Args) const942 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
943 return getDriver().CCCIsCXX() &&
944 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
945 options::OPT_nostdlibxx);
946 }
947
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const948 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
949 ArgStringList &CmdArgs) const {
950 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
951 "should not have called this");
952 CXXStdlibType Type = GetCXXStdlibType(Args);
953
954 switch (Type) {
955 case ToolChain::CST_Libcxx:
956 CmdArgs.push_back("-lc++");
957 break;
958
959 case ToolChain::CST_Libstdcxx:
960 CmdArgs.push_back("-lstdc++");
961 break;
962 }
963 }
964
AddFilePathLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const965 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
966 ArgStringList &CmdArgs) const {
967 for (const auto &LibPath : getFilePaths())
968 if(LibPath.length() > 0)
969 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
970 }
971
AddCCKextLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const972 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
973 ArgStringList &CmdArgs) const {
974 CmdArgs.push_back("-lcc_kext");
975 }
976
isFastMathRuntimeAvailable(const ArgList & Args,std::string & Path) const977 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
978 std::string &Path) const {
979 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
980 // (to keep the linker options consistent with gcc and clang itself).
981 if (!isOptimizationLevelFast(Args)) {
982 // Check if -ffast-math or -funsafe-math.
983 Arg *A =
984 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
985 options::OPT_funsafe_math_optimizations,
986 options::OPT_fno_unsafe_math_optimizations);
987
988 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
989 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
990 return false;
991 }
992 // If crtfastmath.o exists add it to the arguments.
993 Path = GetFilePath("crtfastmath.o");
994 return (Path != "crtfastmath.o"); // Not found.
995 }
996
addFastMathRuntimeIfAvailable(const ArgList & Args,ArgStringList & CmdArgs) const997 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
998 ArgStringList &CmdArgs) const {
999 std::string Path;
1000 if (isFastMathRuntimeAvailable(Args, Path)) {
1001 CmdArgs.push_back(Args.MakeArgString(Path));
1002 return true;
1003 }
1004
1005 return false;
1006 }
1007
getSupportedSanitizers() const1008 SanitizerMask ToolChain::getSupportedSanitizers() const {
1009 // Return sanitizers which don't require runtime support and are not
1010 // platform dependent.
1011
1012 SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
1013 ~SanitizerKind::Function) |
1014 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1015 SanitizerKind::CFICastStrict |
1016 SanitizerKind::FloatDivideByZero |
1017 SanitizerKind::UnsignedIntegerOverflow |
1018 SanitizerKind::ImplicitConversion |
1019 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1020 if (getTriple().getArch() == llvm::Triple::x86 ||
1021 getTriple().getArch() == llvm::Triple::x86_64 ||
1022 getTriple().getArch() == llvm::Triple::arm ||
1023 getTriple().getArch() == llvm::Triple::wasm32 ||
1024 getTriple().getArch() == llvm::Triple::wasm64 || getTriple().isAArch64())
1025 Res |= SanitizerKind::CFIICall;
1026 if (getTriple().getArch() == llvm::Triple::x86_64 || getTriple().isAArch64())
1027 Res |= SanitizerKind::ShadowCallStack;
1028 if (getTriple().isAArch64())
1029 Res |= SanitizerKind::MemTag;
1030 return Res;
1031 }
1032
AddCudaIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1033 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1034 ArgStringList &CC1Args) const {}
1035
AddHIPIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1036 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1037 ArgStringList &CC1Args) const {}
1038
AddIAMCUIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1039 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1040 ArgStringList &CC1Args) const {}
1041
separateMSVCFullVersion(unsigned Version)1042 static VersionTuple separateMSVCFullVersion(unsigned Version) {
1043 if (Version < 100)
1044 return VersionTuple(Version);
1045
1046 if (Version < 10000)
1047 return VersionTuple(Version / 100, Version % 100);
1048
1049 unsigned Build = 0, Factor = 1;
1050 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1051 Build = Build + (Version % 10) * Factor;
1052 return VersionTuple(Version / 100, Version % 100, Build);
1053 }
1054
1055 VersionTuple
computeMSVCVersion(const Driver * D,const llvm::opt::ArgList & Args) const1056 ToolChain::computeMSVCVersion(const Driver *D,
1057 const llvm::opt::ArgList &Args) const {
1058 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1059 const Arg *MSCompatibilityVersion =
1060 Args.getLastArg(options::OPT_fms_compatibility_version);
1061
1062 if (MSCVersion && MSCompatibilityVersion) {
1063 if (D)
1064 D->Diag(diag::err_drv_argument_not_allowed_with)
1065 << MSCVersion->getAsString(Args)
1066 << MSCompatibilityVersion->getAsString(Args);
1067 return VersionTuple();
1068 }
1069
1070 if (MSCompatibilityVersion) {
1071 VersionTuple MSVT;
1072 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1073 if (D)
1074 D->Diag(diag::err_drv_invalid_value)
1075 << MSCompatibilityVersion->getAsString(Args)
1076 << MSCompatibilityVersion->getValue();
1077 } else {
1078 return MSVT;
1079 }
1080 }
1081
1082 if (MSCVersion) {
1083 unsigned Version = 0;
1084 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1085 if (D)
1086 D->Diag(diag::err_drv_invalid_value)
1087 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1088 } else {
1089 return separateMSVCFullVersion(Version);
1090 }
1091 }
1092
1093 return VersionTuple();
1094 }
1095
TranslateOpenMPTargetArgs(const llvm::opt::DerivedArgList & Args,bool SameTripleAsHost,SmallVectorImpl<llvm::opt::Arg * > & AllocatedArgs) const1096 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1097 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1098 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1099 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1100 const OptTable &Opts = getDriver().getOpts();
1101 bool Modified = false;
1102
1103 // Handle -Xopenmp-target flags
1104 for (auto *A : Args) {
1105 // Exclude flags which may only apply to the host toolchain.
1106 // Do not exclude flags when the host triple (AuxTriple)
1107 // matches the current toolchain triple. If it is not present
1108 // at all, target and host share a toolchain.
1109 if (A->getOption().matches(options::OPT_m_Group)) {
1110 if (SameTripleAsHost)
1111 DAL->append(A);
1112 else
1113 Modified = true;
1114 continue;
1115 }
1116
1117 unsigned Index;
1118 unsigned Prev;
1119 bool XOpenMPTargetNoTriple =
1120 A->getOption().matches(options::OPT_Xopenmp_target);
1121
1122 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1123 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1124 if (A->getValue(0) == getTripleString())
1125 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1126 else
1127 continue;
1128 } else if (XOpenMPTargetNoTriple) {
1129 // Passing device args: -Xopenmp-target -opt=val.
1130 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1131 } else {
1132 DAL->append(A);
1133 continue;
1134 }
1135
1136 // Parse the argument to -Xopenmp-target.
1137 Prev = Index;
1138 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1139 if (!XOpenMPTargetArg || Index > Prev + 1) {
1140 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1141 << A->getAsString(Args);
1142 continue;
1143 }
1144 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1145 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1146 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1147 continue;
1148 }
1149 XOpenMPTargetArg->setBaseArg(A);
1150 A = XOpenMPTargetArg.release();
1151 AllocatedArgs.push_back(A);
1152 DAL->append(A);
1153 Modified = true;
1154 }
1155
1156 if (Modified)
1157 return DAL;
1158
1159 delete DAL;
1160 return nullptr;
1161 }
1162
1163 // TODO: Currently argument values separated by space e.g.
1164 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1165 // fixed.
TranslateXarchArgs(const llvm::opt::DerivedArgList & Args,llvm::opt::Arg * & A,llvm::opt::DerivedArgList * DAL,SmallVectorImpl<llvm::opt::Arg * > * AllocatedArgs) const1166 void ToolChain::TranslateXarchArgs(
1167 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1168 llvm::opt::DerivedArgList *DAL,
1169 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1170 const OptTable &Opts = getDriver().getOpts();
1171 unsigned ValuePos = 1;
1172 if (A->getOption().matches(options::OPT_Xarch_device) ||
1173 A->getOption().matches(options::OPT_Xarch_host))
1174 ValuePos = 0;
1175
1176 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1177 unsigned Prev = Index;
1178 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1179
1180 // If the argument parsing failed or more than one argument was
1181 // consumed, the -Xarch_ argument's parameter tried to consume
1182 // extra arguments. Emit an error and ignore.
1183 //
1184 // We also want to disallow any options which would alter the
1185 // driver behavior; that isn't going to work in our model. We
1186 // use isDriverOption() as an approximation, although things
1187 // like -O4 are going to slip through.
1188 if (!XarchArg || Index > Prev + 1) {
1189 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1190 << A->getAsString(Args);
1191 return;
1192 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
1193 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
1194 << A->getAsString(Args);
1195 return;
1196 }
1197 XarchArg->setBaseArg(A);
1198 A = XarchArg.release();
1199 if (!AllocatedArgs)
1200 DAL->AddSynthesizedArg(A);
1201 else
1202 AllocatedArgs->push_back(A);
1203 }
1204
TranslateXarchArgs(const llvm::opt::DerivedArgList & Args,StringRef BoundArch,Action::OffloadKind OFK,SmallVectorImpl<llvm::opt::Arg * > * AllocatedArgs) const1205 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1206 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1207 Action::OffloadKind OFK,
1208 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1209 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1210 bool Modified = false;
1211
1212 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
1213 for (Arg *A : Args) {
1214 bool NeedTrans = false;
1215 bool Skip = false;
1216 if (A->getOption().matches(options::OPT_Xarch_device)) {
1217 NeedTrans = IsGPU;
1218 Skip = !IsGPU;
1219 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1220 NeedTrans = !IsGPU;
1221 Skip = IsGPU;
1222 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
1223 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1224 // they may need special translation.
1225 // Skip this argument unless the architecture matches BoundArch
1226 if (BoundArch.empty() || A->getValue(0) != BoundArch)
1227 Skip = true;
1228 else
1229 NeedTrans = true;
1230 }
1231 if (NeedTrans || Skip)
1232 Modified = true;
1233 if (NeedTrans)
1234 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1235 if (!Skip)
1236 DAL->append(A);
1237 }
1238
1239 if (Modified)
1240 return DAL;
1241
1242 delete DAL;
1243 return nullptr;
1244 }
1245