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/Clang.h"
13 #include "clang/Basic/ObjCRuntime.h"
14 #include "clang/Basic/Sanitizers.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/XRayArgs.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Config/llvm-config.h"
29 #include "llvm/MC/MCTargetOptions.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptTable.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/TargetParser.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/VersionTuple.h"
40 #include "llvm/Support/VirtualFileSystem.h"
41 #include <cassert>
42 #include <cstddef>
43 #include <cstring>
44 #include <string>
45 
46 using namespace clang;
47 using namespace driver;
48 using namespace tools;
49 using namespace llvm;
50 using namespace llvm::opt;
51 
52 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
53   return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
54                          options::OPT_fno_rtti, options::OPT_frtti);
55 }
56 
57 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
58                                              const llvm::Triple &Triple,
59                                              const Arg *CachedRTTIArg) {
60   // Explicit rtti/no-rtti args
61   if (CachedRTTIArg) {
62     if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
63       return ToolChain::RM_Enabled;
64     else
65       return ToolChain::RM_Disabled;
66   }
67 
68   // -frtti is default, except for the PS4 CPU.
69   return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
70 }
71 
72 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
73                      const ArgList &Args)
74     : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
75       CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
76   SmallString<128> P;
77 
78   P.assign(D.ResourceDir);
79   llvm::sys::path::append(P, D.getTargetTriple(), "lib");
80   if (getVFS().exists(P))
81     getLibraryPaths().push_back(P.str());
82 
83   P.assign(D.ResourceDir);
84   llvm::sys::path::append(P, Triple.str(), "lib");
85   if (getVFS().exists(P))
86     getLibraryPaths().push_back(P.str());
87 
88   std::string CandidateLibPath = getArchSpecificLibPath();
89   if (getVFS().exists(CandidateLibPath))
90     getFilePaths().push_back(CandidateLibPath);
91 }
92 
93 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
94   Triple.setEnvironment(Env);
95   if (EffectiveTriple != llvm::Triple())
96     EffectiveTriple.setEnvironment(Env);
97 }
98 
99 ToolChain::~ToolChain() = default;
100 
101 llvm::vfs::FileSystem &ToolChain::getVFS() const {
102   return getDriver().getVFS();
103 }
104 
105 bool ToolChain::useIntegratedAs() const {
106   return Args.hasFlag(options::OPT_fintegrated_as,
107                       options::OPT_fno_integrated_as,
108                       IsIntegratedAssemblerDefault());
109 }
110 
111 bool ToolChain::useRelaxRelocations() const {
112   return ENABLE_X86_RELAX_RELOCATIONS;
113 }
114 
115 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
116   if (!SanitizerArguments.get())
117     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
118   return *SanitizerArguments.get();
119 }
120 
121 const XRayArgs& ToolChain::getXRayArgs() const {
122   if (!XRayArguments.get())
123     XRayArguments.reset(new XRayArgs(*this, Args));
124   return *XRayArguments.get();
125 }
126 
127 namespace {
128 
129 struct DriverSuffix {
130   const char *Suffix;
131   const char *ModeFlag;
132 };
133 
134 } // namespace
135 
136 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
137   // A list of known driver suffixes. Suffixes are compared against the
138   // program name in order. If there is a match, the frontend type is updated as
139   // necessary by applying the ModeFlag.
140   static const DriverSuffix DriverSuffixes[] = {
141       {"clang", nullptr},
142       {"clang++", "--driver-mode=g++"},
143       {"clang-c++", "--driver-mode=g++"},
144       {"clang-cc", nullptr},
145       {"clang-cpp", "--driver-mode=cpp"},
146       {"clang-g++", "--driver-mode=g++"},
147       {"clang-gcc", nullptr},
148       {"clang-cl", "--driver-mode=cl"},
149       {"cc", nullptr},
150       {"cpp", "--driver-mode=cpp"},
151       {"cl", "--driver-mode=cl"},
152       {"++", "--driver-mode=g++"},
153   };
154 
155   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
156     StringRef Suffix(DriverSuffixes[i].Suffix);
157     if (ProgName.endswith(Suffix)) {
158       Pos = ProgName.size() - Suffix.size();
159       return &DriverSuffixes[i];
160     }
161   }
162   return nullptr;
163 }
164 
165 /// Normalize the program name from argv[0] by stripping the file extension if
166 /// present and lower-casing the string on Windows.
167 static std::string normalizeProgramName(llvm::StringRef Argv0) {
168   std::string ProgName = llvm::sys::path::stem(Argv0);
169 #ifdef _WIN32
170   // Transform to lowercase for case insensitive file systems.
171   std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
172 #endif
173   return ProgName;
174 }
175 
176 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
177   // Try to infer frontend type and default target from the program name by
178   // comparing it against DriverSuffixes in order.
179 
180   // If there is a match, the function tries to identify a target as prefix.
181   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
182   // prefix "x86_64-linux". If such a target prefix is found, it may be
183   // added via -target as implicit first argument.
184   const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
185 
186   if (!DS) {
187     // Try again after stripping any trailing version number:
188     // clang++3.5 -> clang++
189     ProgName = ProgName.rtrim("0123456789.");
190     DS = FindDriverSuffix(ProgName, Pos);
191   }
192 
193   if (!DS) {
194     // Try again after stripping trailing -component.
195     // clang++-tot -> clang++
196     ProgName = ProgName.slice(0, ProgName.rfind('-'));
197     DS = FindDriverSuffix(ProgName, Pos);
198   }
199   return DS;
200 }
201 
202 ParsedClangName
203 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
204   std::string ProgName = normalizeProgramName(PN);
205   size_t SuffixPos;
206   const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
207   if (!DS)
208     return {};
209   size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
210 
211   size_t LastComponent = ProgName.rfind('-', SuffixPos);
212   if (LastComponent == std::string::npos)
213     return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
214   std::string ModeSuffix = ProgName.substr(LastComponent + 1,
215                                            SuffixEnd - LastComponent - 1);
216 
217   // Infer target from the prefix.
218   StringRef Prefix(ProgName);
219   Prefix = Prefix.slice(0, LastComponent);
220   std::string IgnoredError;
221   bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
222   return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
223 }
224 
225 StringRef ToolChain::getDefaultUniversalArchName() const {
226   // In universal driver terms, the arch name accepted by -arch isn't exactly
227   // the same as the ones that appear in the triple. Roughly speaking, this is
228   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
229   // only interesting special case is powerpc.
230   switch (Triple.getArch()) {
231   case llvm::Triple::ppc:
232     return "ppc";
233   case llvm::Triple::ppc64:
234     return "ppc64";
235   case llvm::Triple::ppc64le:
236     return "ppc64le";
237   default:
238     return Triple.getArchName();
239   }
240 }
241 
242 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
243   return Input.getFilename();
244 }
245 
246 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
247   return false;
248 }
249 
250 Tool *ToolChain::getClang() const {
251   if (!Clang)
252     Clang.reset(new tools::Clang(*this));
253   return Clang.get();
254 }
255 
256 Tool *ToolChain::buildAssembler() const {
257   return new tools::ClangAs(*this);
258 }
259 
260 Tool *ToolChain::buildLinker() const {
261   llvm_unreachable("Linking is not supported by this toolchain");
262 }
263 
264 Tool *ToolChain::getAssemble() const {
265   if (!Assemble)
266     Assemble.reset(buildAssembler());
267   return Assemble.get();
268 }
269 
270 Tool *ToolChain::getClangAs() const {
271   if (!Assemble)
272     Assemble.reset(new tools::ClangAs(*this));
273   return Assemble.get();
274 }
275 
276 Tool *ToolChain::getLink() const {
277   if (!Link)
278     Link.reset(buildLinker());
279   return Link.get();
280 }
281 
282 Tool *ToolChain::getOffloadBundler() const {
283   if (!OffloadBundler)
284     OffloadBundler.reset(new tools::OffloadBundler(*this));
285   return OffloadBundler.get();
286 }
287 
288 Tool *ToolChain::getTool(Action::ActionClass AC) const {
289   switch (AC) {
290   case Action::AssembleJobClass:
291     return getAssemble();
292 
293   case Action::LinkJobClass:
294     return getLink();
295 
296   case Action::InputClass:
297   case Action::BindArchClass:
298   case Action::OffloadClass:
299   case Action::LipoJobClass:
300   case Action::DsymutilJobClass:
301   case Action::VerifyDebugInfoJobClass:
302     llvm_unreachable("Invalid tool kind.");
303 
304   case Action::CompileJobClass:
305   case Action::PrecompileJobClass:
306   case Action::HeaderModulePrecompileJobClass:
307   case Action::PreprocessJobClass:
308   case Action::AnalyzeJobClass:
309   case Action::MigrateJobClass:
310   case Action::VerifyPCHJobClass:
311   case Action::BackendJobClass:
312     return getClang();
313 
314   case Action::OffloadBundlingJobClass:
315   case Action::OffloadUnbundlingJobClass:
316     return getOffloadBundler();
317   }
318 
319   llvm_unreachable("Invalid tool kind.");
320 }
321 
322 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
323                                              const ArgList &Args) {
324   const llvm::Triple &Triple = TC.getTriple();
325   bool IsWindows = Triple.isOSWindows();
326 
327   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
328     return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
329                ? "armhf"
330                : "arm";
331 
332   // For historic reasons, Android library is using i686 instead of i386.
333   if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
334     return "i686";
335 
336   return llvm::Triple::getArchTypeName(TC.getArch());
337 }
338 
339 StringRef ToolChain::getOSLibName() const {
340   switch (Triple.getOS()) {
341   case llvm::Triple::FreeBSD:
342     return "freebsd";
343   case llvm::Triple::NetBSD:
344     return "netbsd";
345   case llvm::Triple::OpenBSD:
346     return "openbsd";
347   case llvm::Triple::Solaris:
348     return "sunos";
349   default:
350     return getOS();
351   }
352 }
353 
354 std::string ToolChain::getCompilerRTPath() const {
355   SmallString<128> Path(getDriver().ResourceDir);
356   if (Triple.isOSUnknown()) {
357     llvm::sys::path::append(Path, "lib");
358   } else {
359     llvm::sys::path::append(Path, "lib", getOSLibName());
360   }
361   return Path.str();
362 }
363 
364 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
365                                      FileType Type) const {
366   const llvm::Triple &TT = getTriple();
367   bool IsITANMSVCWindows =
368       TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
369 
370   const char *Prefix =
371       IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
372   const char *Suffix;
373   switch (Type) {
374   case ToolChain::FT_Object:
375     Suffix = IsITANMSVCWindows ? ".obj" : ".o";
376     break;
377   case ToolChain::FT_Static:
378     Suffix = IsITANMSVCWindows ? ".lib" : ".a";
379     break;
380   case ToolChain::FT_Shared:
381     Suffix = Triple.isOSWindows()
382                  ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
383                  : ".so";
384     break;
385   }
386 
387   for (const auto &LibPath : getLibraryPaths()) {
388     SmallString<128> P(LibPath);
389     llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
390     if (getVFS().exists(P))
391       return P.str();
392   }
393 
394   StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
395   const char *Env = TT.isAndroid() ? "-android" : "";
396   SmallString<128> Path(getCompilerRTPath());
397   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
398                                     Arch + Env + Suffix);
399   return Path.str();
400 }
401 
402 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
403                                               StringRef Component,
404                                               FileType Type) const {
405   return Args.MakeArgString(getCompilerRT(Args, Component, Type));
406 }
407 
408 std::string ToolChain::getArchSpecificLibPath() const {
409   SmallString<128> Path(getDriver().ResourceDir);
410   llvm::sys::path::append(Path, "lib", getOSLibName(),
411                           llvm::Triple::getArchTypeName(getArch()));
412   return Path.str();
413 }
414 
415 bool ToolChain::needsProfileRT(const ArgList &Args) {
416   if (needsGCovInstrumentation(Args) ||
417       Args.hasArg(options::OPT_fprofile_generate) ||
418       Args.hasArg(options::OPT_fprofile_generate_EQ) ||
419       Args.hasArg(options::OPT_fcs_profile_generate) ||
420       Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
421       Args.hasArg(options::OPT_fprofile_instr_generate) ||
422       Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
423       Args.hasArg(options::OPT_fcreate_profile) ||
424       Args.hasArg(options::OPT_forder_file_instrumentation))
425     return true;
426 
427   return false;
428 }
429 
430 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
431   return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
432                       false) ||
433          Args.hasArg(options::OPT_coverage);
434 }
435 
436 Tool *ToolChain::SelectTool(const JobAction &JA) const {
437   if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
438   Action::ActionClass AC = JA.getKind();
439   if (AC == Action::AssembleJobClass && useIntegratedAs())
440     return getClangAs();
441   return getTool(AC);
442 }
443 
444 std::string ToolChain::GetFilePath(const char *Name) const {
445   return D.GetFilePath(Name, *this);
446 }
447 
448 std::string ToolChain::GetProgramPath(const char *Name) const {
449   return D.GetProgramPath(Name, *this);
450 }
451 
452 std::string ToolChain::GetLinkerPath() const {
453   const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
454   StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
455 
456   if (llvm::sys::path::is_absolute(UseLinker)) {
457     // If we're passed what looks like an absolute path, don't attempt to
458     // second-guess that.
459     if (llvm::sys::fs::can_execute(UseLinker))
460       return UseLinker;
461   } else if (UseLinker.empty() || UseLinker == "ld") {
462     // If we're passed -fuse-ld= with no argument, or with the argument ld,
463     // then use whatever the default system linker is.
464     return GetProgramPath(getDefaultLinker());
465   } else {
466     llvm::SmallString<8> LinkerName;
467     if (Triple.isOSDarwin())
468       LinkerName.append("ld64.");
469     else
470       LinkerName.append("ld.");
471     LinkerName.append(UseLinker);
472 
473     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
474     if (llvm::sys::fs::can_execute(LinkerPath))
475       return LinkerPath;
476   }
477 
478   if (A)
479     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
480 
481   return GetProgramPath(getDefaultLinker());
482 }
483 
484 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
485   return types::lookupTypeForExtension(Ext);
486 }
487 
488 bool ToolChain::HasNativeLLVMSupport() const {
489   return false;
490 }
491 
492 bool ToolChain::isCrossCompiling() const {
493   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
494   switch (HostTriple.getArch()) {
495   // The A32/T32/T16 instruction sets are not separate architectures in this
496   // context.
497   case llvm::Triple::arm:
498   case llvm::Triple::armeb:
499   case llvm::Triple::thumb:
500   case llvm::Triple::thumbeb:
501     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
502            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
503   default:
504     return HostTriple.getArch() != getArch();
505   }
506 }
507 
508 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
509   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
510                      VersionTuple());
511 }
512 
513 llvm::ExceptionHandling
514 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
515   return llvm::ExceptionHandling::None;
516 }
517 
518 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
519   if (Model == "single") {
520     // FIXME: 'single' is only supported on ARM and WebAssembly so far.
521     return Triple.getArch() == llvm::Triple::arm ||
522            Triple.getArch() == llvm::Triple::armeb ||
523            Triple.getArch() == llvm::Triple::thumb ||
524            Triple.getArch() == llvm::Triple::thumbeb ||
525            Triple.getArch() == llvm::Triple::wasm32 ||
526            Triple.getArch() == llvm::Triple::wasm64;
527   } else if (Model == "posix")
528     return true;
529 
530   return false;
531 }
532 
533 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
534                                          types::ID InputType) const {
535   switch (getTriple().getArch()) {
536   default:
537     return getTripleString();
538 
539   case llvm::Triple::x86_64: {
540     llvm::Triple Triple = getTriple();
541     if (!Triple.isOSBinFormatMachO())
542       return getTripleString();
543 
544     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
545       // x86_64h goes in the triple. Other -march options just use the
546       // vanilla triple we already have.
547       StringRef MArch = A->getValue();
548       if (MArch == "x86_64h")
549         Triple.setArchName(MArch);
550     }
551     return Triple.getTriple();
552   }
553   case llvm::Triple::aarch64: {
554     llvm::Triple Triple = getTriple();
555     if (!Triple.isOSBinFormatMachO())
556       return getTripleString();
557 
558     // FIXME: older versions of ld64 expect the "arm64" component in the actual
559     // triple string and query it to determine whether an LTO file can be
560     // handled. Remove this when we don't care any more.
561     Triple.setArchName("arm64");
562     return Triple.getTriple();
563   }
564   case llvm::Triple::arm:
565   case llvm::Triple::armeb:
566   case llvm::Triple::thumb:
567   case llvm::Triple::thumbeb: {
568     // FIXME: Factor into subclasses.
569     llvm::Triple Triple = getTriple();
570     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
571                        getTriple().getArch() == llvm::Triple::thumbeb;
572 
573     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
574     // '-mbig-endian'/'-EB'.
575     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
576                                  options::OPT_mbig_endian)) {
577       IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
578     }
579 
580     // Thumb2 is the default for V7 on Darwin.
581     //
582     // FIXME: Thumb should just be another -target-feaure, not in the triple.
583     StringRef MCPU, MArch;
584     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
585       MCPU = A->getValue();
586     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
587       MArch = A->getValue();
588     std::string CPU =
589         Triple.isOSBinFormatMachO()
590             ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
591             : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
592     StringRef Suffix =
593       tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
594     bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
595     bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
596                                        getTriple().isOSBinFormatMachO());
597     // FIXME: this is invalid for WindowsCE
598     if (getTriple().isOSWindows())
599       ThumbDefault = true;
600     std::string ArchName;
601     if (IsBigEndian)
602       ArchName = "armeb";
603     else
604       ArchName = "arm";
605 
606     // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
607     // M-Class CPUs/architecture variants, which is not supported.
608     bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
609                                           options::OPT_mno_thumb, ThumbDefault);
610     if (IsMProfile && ARMModeRequested) {
611       if (!MCPU.empty())
612         getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
613        else
614         getDriver().Diag(diag::err_arch_unsupported_isa)
615           << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
616     }
617 
618     // Check to see if an explicit choice to use thumb has been made via
619     // -mthumb. For assembler files we must check for -mthumb in the options
620     // passed to the assembler via -Wa or -Xassembler.
621     bool IsThumb = false;
622     if (InputType != types::TY_PP_Asm)
623       IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
624                               ThumbDefault);
625     else {
626       // Ideally we would check for these flags in
627       // CollectArgsForIntegratedAssembler but we can't change the ArchName at
628       // that point. There is no assembler equivalent of -mno-thumb, -marm, or
629       // -mno-arm.
630       for (const auto *A :
631            Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
632         for (StringRef Value : A->getValues()) {
633           if (Value == "-mthumb")
634             IsThumb = true;
635         }
636       }
637     }
638     // Assembly files should start in ARM mode, unless arch is M-profile, or
639     // -mthumb has been passed explicitly to the assembler. Windows is always
640     // thumb.
641     if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
642       if (IsBigEndian)
643         ArchName = "thumbeb";
644       else
645         ArchName = "thumb";
646     }
647     Triple.setArchName(ArchName + Suffix.str());
648 
649     return Triple.getTriple();
650   }
651   }
652 }
653 
654 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
655                                                    types::ID InputType) const {
656   return ComputeLLVMTriple(Args, InputType);
657 }
658 
659 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
660                                           ArgStringList &CC1Args) const {
661   // Each toolchain should provide the appropriate include flags.
662 }
663 
664 void ToolChain::addClangTargetOptions(
665     const ArgList &DriverArgs, ArgStringList &CC1Args,
666     Action::OffloadKind DeviceOffloadKind) const {}
667 
668 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
669 
670 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
671                                  llvm::opt::ArgStringList &CmdArgs) const {
672   if (!needsProfileRT(Args)) return;
673 
674   CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
675 }
676 
677 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
678     const ArgList &Args) const {
679   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
680   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
681 
682   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
683   if (LibName == "compiler-rt")
684     return ToolChain::RLT_CompilerRT;
685   else if (LibName == "libgcc")
686     return ToolChain::RLT_Libgcc;
687   else if (LibName == "platform")
688     return GetDefaultRuntimeLibType();
689 
690   if (A)
691     getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
692 
693   return GetDefaultRuntimeLibType();
694 }
695 
696 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
697   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
698   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
699 
700   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
701   if (LibName == "libc++")
702     return ToolChain::CST_Libcxx;
703   else if (LibName == "libstdc++")
704     return ToolChain::CST_Libstdcxx;
705   else if (LibName == "platform")
706     return GetDefaultCXXStdlibType();
707 
708   if (A)
709     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
710 
711   return GetDefaultCXXStdlibType();
712 }
713 
714 /// Utility function to add a system include directory to CC1 arguments.
715 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
716                                             ArgStringList &CC1Args,
717                                             const Twine &Path) {
718   CC1Args.push_back("-internal-isystem");
719   CC1Args.push_back(DriverArgs.MakeArgString(Path));
720 }
721 
722 /// Utility function to add a system include directory with extern "C"
723 /// semantics to CC1 arguments.
724 ///
725 /// Note that this should be used rarely, and only for directories that
726 /// historically and for legacy reasons are treated as having implicit extern
727 /// "C" semantics. These semantics are *ignored* by and large today, but its
728 /// important to preserve the preprocessor changes resulting from the
729 /// classification.
730 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
731                                                    ArgStringList &CC1Args,
732                                                    const Twine &Path) {
733   CC1Args.push_back("-internal-externc-isystem");
734   CC1Args.push_back(DriverArgs.MakeArgString(Path));
735 }
736 
737 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
738                                                 ArgStringList &CC1Args,
739                                                 const Twine &Path) {
740   if (llvm::sys::fs::exists(Path))
741     addExternCSystemInclude(DriverArgs, CC1Args, Path);
742 }
743 
744 /// Utility function to add a list of system include directories to CC1.
745 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
746                                              ArgStringList &CC1Args,
747                                              ArrayRef<StringRef> Paths) {
748   for (const auto Path : Paths) {
749     CC1Args.push_back("-internal-isystem");
750     CC1Args.push_back(DriverArgs.MakeArgString(Path));
751   }
752 }
753 
754 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
755                                              ArgStringList &CC1Args) const {
756   // Header search paths should be handled by each of the subclasses.
757   // Historically, they have not been, and instead have been handled inside of
758   // the CC1-layer frontend. As the logic is hoisted out, this generic function
759   // will slowly stop being called.
760   //
761   // While it is being called, replicate a bit of a hack to propagate the
762   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
763   // header search paths with it. Once all systems are overriding this
764   // function, the CC1 flag and this line can be removed.
765   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
766 }
767 
768 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
769   return getDriver().CCCIsCXX() &&
770          !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
771                       options::OPT_nostdlibxx);
772 }
773 
774 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
775                                     ArgStringList &CmdArgs) const {
776   assert(!Args.hasArg(options::OPT_nostdlibxx) &&
777          "should not have called this");
778   CXXStdlibType Type = GetCXXStdlibType(Args);
779 
780   switch (Type) {
781   case ToolChain::CST_Libcxx:
782     CmdArgs.push_back("-lc++");
783     break;
784 
785   case ToolChain::CST_Libstdcxx:
786     CmdArgs.push_back("-lstdc++");
787     break;
788   }
789 }
790 
791 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
792                                    ArgStringList &CmdArgs) const {
793   for (const auto &LibPath : getLibraryPaths())
794     if(LibPath.length() > 0)
795       CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
796 
797   for (const auto &LibPath : getFilePaths())
798     if(LibPath.length() > 0)
799       CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
800 }
801 
802 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
803                                  ArgStringList &CmdArgs) const {
804   CmdArgs.push_back("-lcc_kext");
805 }
806 
807 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
808                                               ArgStringList &CmdArgs) const {
809   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
810   // (to keep the linker options consistent with gcc and clang itself).
811   if (!isOptimizationLevelFast(Args)) {
812     // Check if -ffast-math or -funsafe-math.
813     Arg *A =
814         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
815                         options::OPT_funsafe_math_optimizations,
816                         options::OPT_fno_unsafe_math_optimizations);
817 
818     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
819         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
820       return false;
821   }
822   // If crtfastmath.o exists add it to the arguments.
823   std::string Path = GetFilePath("crtfastmath.o");
824   if (Path == "crtfastmath.o") // Not found.
825     return false;
826 
827   CmdArgs.push_back(Args.MakeArgString(Path));
828   return true;
829 }
830 
831 SanitizerMask ToolChain::getSupportedSanitizers() const {
832   // Return sanitizers which don't require runtime support and are not
833   // platform dependent.
834 
835   SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
836                        ~SanitizerKind::Function) |
837                       (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
838                       SanitizerKind::CFICastStrict |
839                       SanitizerKind::UnsignedIntegerOverflow |
840                       SanitizerKind::ImplicitConversion |
841                       SanitizerKind::Nullability | SanitizerKind::LocalBounds;
842   if (getTriple().getArch() == llvm::Triple::x86 ||
843       getTriple().getArch() == llvm::Triple::x86_64 ||
844       getTriple().getArch() == llvm::Triple::arm ||
845       getTriple().getArch() == llvm::Triple::aarch64 ||
846       getTriple().getArch() == llvm::Triple::wasm32 ||
847       getTriple().getArch() == llvm::Triple::wasm64)
848     Res |= SanitizerKind::CFIICall;
849   if (getTriple().getArch() == llvm::Triple::x86_64 ||
850       getTriple().getArch() == llvm::Triple::aarch64)
851     Res |= SanitizerKind::ShadowCallStack;
852   return Res;
853 }
854 
855 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
856                                    ArgStringList &CC1Args) const {}
857 
858 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
859                                     ArgStringList &CC1Args) const {}
860 
861 static VersionTuple separateMSVCFullVersion(unsigned Version) {
862   if (Version < 100)
863     return VersionTuple(Version);
864 
865   if (Version < 10000)
866     return VersionTuple(Version / 100, Version % 100);
867 
868   unsigned Build = 0, Factor = 1;
869   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
870     Build = Build + (Version % 10) * Factor;
871   return VersionTuple(Version / 100, Version % 100, Build);
872 }
873 
874 VersionTuple
875 ToolChain::computeMSVCVersion(const Driver *D,
876                               const llvm::opt::ArgList &Args) const {
877   const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
878   const Arg *MSCompatibilityVersion =
879       Args.getLastArg(options::OPT_fms_compatibility_version);
880 
881   if (MSCVersion && MSCompatibilityVersion) {
882     if (D)
883       D->Diag(diag::err_drv_argument_not_allowed_with)
884           << MSCVersion->getAsString(Args)
885           << MSCompatibilityVersion->getAsString(Args);
886     return VersionTuple();
887   }
888 
889   if (MSCompatibilityVersion) {
890     VersionTuple MSVT;
891     if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
892       if (D)
893         D->Diag(diag::err_drv_invalid_value)
894             << MSCompatibilityVersion->getAsString(Args)
895             << MSCompatibilityVersion->getValue();
896     } else {
897       return MSVT;
898     }
899   }
900 
901   if (MSCVersion) {
902     unsigned Version = 0;
903     if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
904       if (D)
905         D->Diag(diag::err_drv_invalid_value)
906             << MSCVersion->getAsString(Args) << MSCVersion->getValue();
907     } else {
908       return separateMSVCFullVersion(Version);
909     }
910   }
911 
912   return VersionTuple();
913 }
914 
915 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
916     const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
917     SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
918   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
919   const OptTable &Opts = getDriver().getOpts();
920   bool Modified = false;
921 
922   // Handle -Xopenmp-target flags
923   for (auto *A : Args) {
924     // Exclude flags which may only apply to the host toolchain.
925     // Do not exclude flags when the host triple (AuxTriple)
926     // matches the current toolchain triple. If it is not present
927     // at all, target and host share a toolchain.
928     if (A->getOption().matches(options::OPT_m_Group)) {
929       if (SameTripleAsHost)
930         DAL->append(A);
931       else
932         Modified = true;
933       continue;
934     }
935 
936     unsigned Index;
937     unsigned Prev;
938     bool XOpenMPTargetNoTriple =
939         A->getOption().matches(options::OPT_Xopenmp_target);
940 
941     if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
942       // Passing device args: -Xopenmp-target=<triple> -opt=val.
943       if (A->getValue(0) == getTripleString())
944         Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
945       else
946         continue;
947     } else if (XOpenMPTargetNoTriple) {
948       // Passing device args: -Xopenmp-target -opt=val.
949       Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
950     } else {
951       DAL->append(A);
952       continue;
953     }
954 
955     // Parse the argument to -Xopenmp-target.
956     Prev = Index;
957     std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
958     if (!XOpenMPTargetArg || Index > Prev + 1) {
959       getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
960           << A->getAsString(Args);
961       continue;
962     }
963     if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
964         Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
965       getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
966       continue;
967     }
968     XOpenMPTargetArg->setBaseArg(A);
969     A = XOpenMPTargetArg.release();
970     AllocatedArgs.push_back(A);
971     DAL->append(A);
972     Modified = true;
973   }
974 
975   if (Modified)
976     return DAL;
977 
978   delete DAL;
979   return nullptr;
980 }
981