1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Driver/ToolChain.h"
11 #include "Tools.h"
12 #include "clang/Basic/ObjCRuntime.h"
13 #include "clang/Basic/VirtualFileSystem.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Option/Arg.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/Option/Option.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/TargetParser.h"
28 #include "llvm/Support/TargetRegistry.h"
29 
30 using namespace clang::driver;
31 using namespace clang::driver::tools;
32 using namespace clang;
33 using namespace llvm;
34 using namespace llvm::opt;
35 
36 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
37   return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
38                          options::OPT_fno_rtti, options::OPT_frtti);
39 }
40 
41 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
42                                              const llvm::Triple &Triple,
43                                              const Arg *CachedRTTIArg) {
44   // Explicit rtti/no-rtti args
45   if (CachedRTTIArg) {
46     if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
47       return ToolChain::RM_EnabledExplicitly;
48     else
49       return ToolChain::RM_DisabledExplicitly;
50   }
51 
52   // -frtti is default, except for the PS4 CPU.
53   if (!Triple.isPS4CPU())
54     return ToolChain::RM_EnabledImplicitly;
55 
56   // On the PS4, turning on c++ exceptions turns on rtti.
57   // We're assuming that, if we see -fexceptions, rtti gets turned on.
58   Arg *Exceptions = Args.getLastArgNoClaim(
59       options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
60       options::OPT_fexceptions, options::OPT_fno_exceptions);
61   if (Exceptions &&
62       (Exceptions->getOption().matches(options::OPT_fexceptions) ||
63        Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
64     return ToolChain::RM_EnabledImplicitly;
65 
66   return ToolChain::RM_DisabledImplicitly;
67 }
68 
69 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
70                      const ArgList &Args)
71     : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
72       CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)),
73       EffectiveTriple() {
74   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
75     if (!isThreadModelSupported(A->getValue()))
76       D.Diag(diag::err_drv_invalid_thread_model_for_target)
77           << A->getValue() << A->getAsString(Args);
78 
79   std::string CandidateLibPath = getArchSpecificLibPath();
80   if (getVFS().exists(CandidateLibPath))
81     getFilePaths().push_back(CandidateLibPath);
82 }
83 
84 ToolChain::~ToolChain() {
85 }
86 
87 vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); }
88 
89 bool ToolChain::useIntegratedAs() const {
90   return Args.hasFlag(options::OPT_fintegrated_as,
91                       options::OPT_fno_integrated_as,
92                       IsIntegratedAssemblerDefault());
93 }
94 
95 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
96   if (!SanitizerArguments.get())
97     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
98   return *SanitizerArguments.get();
99 }
100 
101 namespace {
102 struct DriverSuffix {
103   const char *Suffix;
104   const char *ModeFlag;
105 };
106 
107 const DriverSuffix *FindDriverSuffix(StringRef ProgName) {
108   // A list of known driver suffixes. Suffixes are compared against the
109   // program name in order. If there is a match, the frontend type is updated as
110   // necessary by applying the ModeFlag.
111   static const DriverSuffix DriverSuffixes[] = {
112       {"clang", nullptr},
113       {"clang++", "--driver-mode=g++"},
114       {"clang-c++", "--driver-mode=g++"},
115       {"clang-cc", nullptr},
116       {"clang-cpp", "--driver-mode=cpp"},
117       {"clang-g++", "--driver-mode=g++"},
118       {"clang-gcc", nullptr},
119       {"clang-cl", "--driver-mode=cl"},
120       {"cc", nullptr},
121       {"cpp", "--driver-mode=cpp"},
122       {"cl", "--driver-mode=cl"},
123       {"++", "--driver-mode=g++"},
124   };
125 
126   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
127     if (ProgName.endswith(DriverSuffixes[i].Suffix))
128       return &DriverSuffixes[i];
129   return nullptr;
130 }
131 
132 /// Normalize the program name from argv[0] by stripping the file extension if
133 /// present and lower-casing the string on Windows.
134 std::string normalizeProgramName(llvm::StringRef Argv0) {
135   std::string ProgName = llvm::sys::path::stem(Argv0);
136 #ifdef LLVM_ON_WIN32
137   // Transform to lowercase for case insensitive file systems.
138   std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
139 #endif
140   return ProgName;
141 }
142 
143 const DriverSuffix *parseDriverSuffix(StringRef ProgName) {
144   // Try to infer frontend type and default target from the program name by
145   // comparing it against DriverSuffixes in order.
146 
147   // If there is a match, the function tries to identify a target as prefix.
148   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
149   // prefix "x86_64-linux". If such a target prefix is found, it may be
150   // added via -target as implicit first argument.
151   const DriverSuffix *DS = FindDriverSuffix(ProgName);
152 
153   if (!DS) {
154     // Try again after stripping any trailing version number:
155     // clang++3.5 -> clang++
156     ProgName = ProgName.rtrim("0123456789.");
157     DS = FindDriverSuffix(ProgName);
158   }
159 
160   if (!DS) {
161     // Try again after stripping trailing -component.
162     // clang++-tot -> clang++
163     ProgName = ProgName.slice(0, ProgName.rfind('-'));
164     DS = FindDriverSuffix(ProgName);
165   }
166   return DS;
167 }
168 } // anonymous namespace
169 
170 std::pair<std::string, std::string>
171 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
172   std::string ProgName = normalizeProgramName(PN);
173   const DriverSuffix *DS = parseDriverSuffix(ProgName);
174   if (!DS)
175     return std::make_pair("", "");
176   std::string ModeFlag = DS->ModeFlag == nullptr ? "" : DS->ModeFlag;
177 
178   std::string::size_type LastComponent =
179       ProgName.rfind('-', ProgName.size() - strlen(DS->Suffix));
180   if (LastComponent == std::string::npos)
181     return std::make_pair("", ModeFlag);
182 
183   // Infer target from the prefix.
184   StringRef Prefix(ProgName);
185   Prefix = Prefix.slice(0, LastComponent);
186   std::string IgnoredError;
187   std::string Target;
188   if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
189     Target = Prefix;
190   }
191   return std::make_pair(Target, ModeFlag);
192 }
193 
194 StringRef ToolChain::getDefaultUniversalArchName() const {
195   // In universal driver terms, the arch name accepted by -arch isn't exactly
196   // the same as the ones that appear in the triple. Roughly speaking, this is
197   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
198   // only interesting special case is powerpc.
199   switch (Triple.getArch()) {
200   case llvm::Triple::ppc:
201     return "ppc";
202   case llvm::Triple::ppc64:
203     return "ppc64";
204   case llvm::Triple::ppc64le:
205     return "ppc64le";
206   default:
207     return Triple.getArchName();
208   }
209 }
210 
211 bool ToolChain::IsUnwindTablesDefault() const {
212   return false;
213 }
214 
215 Tool *ToolChain::getClang() const {
216   if (!Clang)
217     Clang.reset(new tools::Clang(*this));
218   return Clang.get();
219 }
220 
221 Tool *ToolChain::buildAssembler() const {
222   return new tools::ClangAs(*this);
223 }
224 
225 Tool *ToolChain::buildLinker() const {
226   llvm_unreachable("Linking is not supported by this toolchain");
227 }
228 
229 Tool *ToolChain::getAssemble() const {
230   if (!Assemble)
231     Assemble.reset(buildAssembler());
232   return Assemble.get();
233 }
234 
235 Tool *ToolChain::getClangAs() const {
236   if (!Assemble)
237     Assemble.reset(new tools::ClangAs(*this));
238   return Assemble.get();
239 }
240 
241 Tool *ToolChain::getLink() const {
242   if (!Link)
243     Link.reset(buildLinker());
244   return Link.get();
245 }
246 
247 Tool *ToolChain::getOffloadBundler() const {
248   if (!OffloadBundler)
249     OffloadBundler.reset(new tools::OffloadBundler(*this));
250   return OffloadBundler.get();
251 }
252 
253 Tool *ToolChain::getTool(Action::ActionClass AC) const {
254   switch (AC) {
255   case Action::AssembleJobClass:
256     return getAssemble();
257 
258   case Action::LinkJobClass:
259     return getLink();
260 
261   case Action::InputClass:
262   case Action::BindArchClass:
263   case Action::OffloadClass:
264   case Action::LipoJobClass:
265   case Action::DsymutilJobClass:
266   case Action::VerifyDebugInfoJobClass:
267     llvm_unreachable("Invalid tool kind.");
268 
269   case Action::CompileJobClass:
270   case Action::PrecompileJobClass:
271   case Action::PreprocessJobClass:
272   case Action::AnalyzeJobClass:
273   case Action::MigrateJobClass:
274   case Action::VerifyPCHJobClass:
275   case Action::BackendJobClass:
276     return getClang();
277 
278   case Action::OffloadBundlingJobClass:
279   case Action::OffloadUnbundlingJobClass:
280     return getOffloadBundler();
281   }
282 
283   llvm_unreachable("Invalid tool kind.");
284 }
285 
286 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
287                                              const ArgList &Args) {
288   const llvm::Triple &Triple = TC.getTriple();
289   bool IsWindows = Triple.isOSWindows();
290 
291   if (Triple.isWindowsMSVCEnvironment() && TC.getArch() == llvm::Triple::x86)
292     return "i386";
293 
294   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
295     return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
296                ? "armhf"
297                : "arm";
298 
299   return TC.getArchName();
300 }
301 
302 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
303                                      bool Shared) const {
304   const llvm::Triple &TT = getTriple();
305   const char *Env = TT.isAndroid() ? "-android" : "";
306   bool IsITANMSVCWindows =
307       TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
308 
309   StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
310   const char *Prefix = IsITANMSVCWindows ? "" : "lib";
311   const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
312                               : (IsITANMSVCWindows ? ".lib" : ".a");
313 
314   SmallString<128> Path(getDriver().ResourceDir);
315   StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS();
316   llvm::sys::path::append(Path, "lib", OSLibName);
317   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
318                                     Arch + Env + Suffix);
319   return Path.str();
320 }
321 
322 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
323                                               StringRef Component,
324                                               bool Shared) const {
325   return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
326 }
327 
328 std::string ToolChain::getArchSpecificLibPath() const {
329   SmallString<128> Path(getDriver().ResourceDir);
330   StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS();
331   llvm::sys::path::append(Path, "lib", OSLibName,
332                           llvm::Triple::getArchTypeName(getArch()));
333   return Path.str();
334 }
335 
336 bool ToolChain::needsProfileRT(const ArgList &Args) {
337   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
338                    false) ||
339       Args.hasArg(options::OPT_fprofile_generate) ||
340       Args.hasArg(options::OPT_fprofile_generate_EQ) ||
341       Args.hasArg(options::OPT_fprofile_instr_generate) ||
342       Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
343       Args.hasArg(options::OPT_fcreate_profile) ||
344       Args.hasArg(options::OPT_coverage))
345     return true;
346 
347   return false;
348 }
349 
350 Tool *ToolChain::SelectTool(const JobAction &JA) const {
351   if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
352   Action::ActionClass AC = JA.getKind();
353   if (AC == Action::AssembleJobClass && useIntegratedAs())
354     return getClangAs();
355   return getTool(AC);
356 }
357 
358 std::string ToolChain::GetFilePath(const char *Name) const {
359   return D.GetFilePath(Name, *this);
360 }
361 
362 std::string ToolChain::GetProgramPath(const char *Name) const {
363   return D.GetProgramPath(Name, *this);
364 }
365 
366 std::string ToolChain::GetLinkerPath() const {
367   const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
368   StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
369 
370   if (llvm::sys::path::is_absolute(UseLinker)) {
371     // If we're passed what looks like an absolute path, don't attempt to
372     // second-guess that.
373     if (llvm::sys::fs::exists(UseLinker))
374       return UseLinker;
375   } else if (UseLinker.empty() || UseLinker == "ld") {
376     // If we're passed -fuse-ld= with no argument, or with the argument ld,
377     // then use whatever the default system linker is.
378     return GetProgramPath(getDefaultLinker());
379   } else {
380     llvm::SmallString<8> LinkerName("ld.");
381     LinkerName.append(UseLinker);
382 
383     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
384     if (llvm::sys::fs::exists(LinkerPath))
385       return LinkerPath;
386   }
387 
388   if (A)
389     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
390 
391   return GetProgramPath(getDefaultLinker());
392 }
393 
394 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
395   return types::lookupTypeForExtension(Ext);
396 }
397 
398 bool ToolChain::HasNativeLLVMSupport() const {
399   return false;
400 }
401 
402 bool ToolChain::isCrossCompiling() const {
403   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
404   switch (HostTriple.getArch()) {
405   // The A32/T32/T16 instruction sets are not separate architectures in this
406   // context.
407   case llvm::Triple::arm:
408   case llvm::Triple::armeb:
409   case llvm::Triple::thumb:
410   case llvm::Triple::thumbeb:
411     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
412            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
413   default:
414     return HostTriple.getArch() != getArch();
415   }
416 }
417 
418 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
419   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
420                      VersionTuple());
421 }
422 
423 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
424   if (Model == "single") {
425     // FIXME: 'single' is only supported on ARM and WebAssembly so far.
426     return Triple.getArch() == llvm::Triple::arm ||
427            Triple.getArch() == llvm::Triple::armeb ||
428            Triple.getArch() == llvm::Triple::thumb ||
429            Triple.getArch() == llvm::Triple::thumbeb ||
430            Triple.getArch() == llvm::Triple::wasm32 ||
431            Triple.getArch() == llvm::Triple::wasm64;
432   } else if (Model == "posix")
433     return true;
434 
435   return false;
436 }
437 
438 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
439                                          types::ID InputType) const {
440   switch (getTriple().getArch()) {
441   default:
442     return getTripleString();
443 
444   case llvm::Triple::x86_64: {
445     llvm::Triple Triple = getTriple();
446     if (!Triple.isOSBinFormatMachO())
447       return getTripleString();
448 
449     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
450       // x86_64h goes in the triple. Other -march options just use the
451       // vanilla triple we already have.
452       StringRef MArch = A->getValue();
453       if (MArch == "x86_64h")
454         Triple.setArchName(MArch);
455     }
456     return Triple.getTriple();
457   }
458   case llvm::Triple::aarch64: {
459     llvm::Triple Triple = getTriple();
460     if (!Triple.isOSBinFormatMachO())
461       return getTripleString();
462 
463     // FIXME: older versions of ld64 expect the "arm64" component in the actual
464     // triple string and query it to determine whether an LTO file can be
465     // handled. Remove this when we don't care any more.
466     Triple.setArchName("arm64");
467     return Triple.getTriple();
468   }
469   case llvm::Triple::arm:
470   case llvm::Triple::armeb:
471   case llvm::Triple::thumb:
472   case llvm::Triple::thumbeb: {
473     // FIXME: Factor into subclasses.
474     llvm::Triple Triple = getTriple();
475     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
476                        getTriple().getArch() == llvm::Triple::thumbeb;
477 
478     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
479     // '-mbig-endian'/'-EB'.
480     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
481                                  options::OPT_mbig_endian)) {
482       IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
483     }
484 
485     // Thumb2 is the default for V7 on Darwin.
486     //
487     // FIXME: Thumb should just be another -target-feaure, not in the triple.
488     StringRef MCPU, MArch;
489     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
490       MCPU = A->getValue();
491     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
492       MArch = A->getValue();
493     std::string CPU =
494         Triple.isOSBinFormatMachO()
495             ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
496             : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
497     StringRef Suffix =
498       tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
499     bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::PK_M;
500     bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
501                                        getTriple().isOSBinFormatMachO());
502     // FIXME: this is invalid for WindowsCE
503     if (getTriple().isOSWindows())
504       ThumbDefault = true;
505     std::string ArchName;
506     if (IsBigEndian)
507       ArchName = "armeb";
508     else
509       ArchName = "arm";
510 
511     // Assembly files should start in ARM mode, unless arch is M-profile.
512     // Windows is always thumb.
513     if ((InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb,
514          options::OPT_mno_thumb, ThumbDefault)) || IsMProfile ||
515          getTriple().isOSWindows()) {
516       if (IsBigEndian)
517         ArchName = "thumbeb";
518       else
519         ArchName = "thumb";
520     }
521     Triple.setArchName(ArchName + Suffix.str());
522 
523     return Triple.getTriple();
524   }
525   }
526 }
527 
528 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
529                                                    types::ID InputType) const {
530   return ComputeLLVMTriple(Args, InputType);
531 }
532 
533 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
534                                           ArgStringList &CC1Args) const {
535   // Each toolchain should provide the appropriate include flags.
536 }
537 
538 void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
539                                       ArgStringList &CC1Args) const {
540 }
541 
542 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
543 
544 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
545                                  llvm::opt::ArgStringList &CmdArgs) const {
546   if (!needsProfileRT(Args)) return;
547 
548   CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
549 }
550 
551 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
552     const ArgList &Args) const {
553   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
554   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
555 
556   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
557   if (LibName == "compiler-rt")
558     return ToolChain::RLT_CompilerRT;
559   else if (LibName == "libgcc")
560     return ToolChain::RLT_Libgcc;
561   else if (LibName == "platform")
562     return GetDefaultRuntimeLibType();
563 
564   if (A)
565     getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
566 
567   return GetDefaultRuntimeLibType();
568 }
569 
570 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
571   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
572   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
573 
574   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
575   if (LibName == "libc++")
576     return ToolChain::CST_Libcxx;
577   else if (LibName == "libstdc++")
578     return ToolChain::CST_Libstdcxx;
579   else if (LibName == "platform")
580     return GetDefaultCXXStdlibType();
581 
582   if (A)
583     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
584 
585   return GetDefaultCXXStdlibType();
586 }
587 
588 /// \brief Utility function to add a system include directory to CC1 arguments.
589 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
590                                             ArgStringList &CC1Args,
591                                             const Twine &Path) {
592   CC1Args.push_back("-internal-isystem");
593   CC1Args.push_back(DriverArgs.MakeArgString(Path));
594 }
595 
596 /// \brief Utility function to add a system include directory with extern "C"
597 /// semantics to CC1 arguments.
598 ///
599 /// Note that this should be used rarely, and only for directories that
600 /// historically and for legacy reasons are treated as having implicit extern
601 /// "C" semantics. These semantics are *ignored* by and large today, but its
602 /// important to preserve the preprocessor changes resulting from the
603 /// classification.
604 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
605                                                    ArgStringList &CC1Args,
606                                                    const Twine &Path) {
607   CC1Args.push_back("-internal-externc-isystem");
608   CC1Args.push_back(DriverArgs.MakeArgString(Path));
609 }
610 
611 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
612                                                 ArgStringList &CC1Args,
613                                                 const Twine &Path) {
614   if (llvm::sys::fs::exists(Path))
615     addExternCSystemInclude(DriverArgs, CC1Args, Path);
616 }
617 
618 /// \brief Utility function to add a list of system include directories to CC1.
619 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
620                                              ArgStringList &CC1Args,
621                                              ArrayRef<StringRef> Paths) {
622   for (StringRef Path : Paths) {
623     CC1Args.push_back("-internal-isystem");
624     CC1Args.push_back(DriverArgs.MakeArgString(Path));
625   }
626 }
627 
628 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
629                                              ArgStringList &CC1Args) const {
630   // Header search paths should be handled by each of the subclasses.
631   // Historically, they have not been, and instead have been handled inside of
632   // the CC1-layer frontend. As the logic is hoisted out, this generic function
633   // will slowly stop being called.
634   //
635   // While it is being called, replicate a bit of a hack to propagate the
636   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
637   // header search paths with it. Once all systems are overriding this
638   // function, the CC1 flag and this line can be removed.
639   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
640 }
641 
642 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
643                                     ArgStringList &CmdArgs) const {
644   CXXStdlibType Type = GetCXXStdlibType(Args);
645 
646   switch (Type) {
647   case ToolChain::CST_Libcxx:
648     CmdArgs.push_back("-lc++");
649     break;
650 
651   case ToolChain::CST_Libstdcxx:
652     CmdArgs.push_back("-lstdc++");
653     break;
654   }
655 }
656 
657 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
658                                    ArgStringList &CmdArgs) const {
659   for (const auto &LibPath : getFilePaths())
660     if(LibPath.length() > 0)
661       CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
662 }
663 
664 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
665                                  ArgStringList &CmdArgs) const {
666   CmdArgs.push_back("-lcc_kext");
667 }
668 
669 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
670                                               ArgStringList &CmdArgs) const {
671   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
672   // (to keep the linker options consistent with gcc and clang itself).
673   if (!isOptimizationLevelFast(Args)) {
674     // Check if -ffast-math or -funsafe-math.
675     Arg *A =
676         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
677                         options::OPT_funsafe_math_optimizations,
678                         options::OPT_fno_unsafe_math_optimizations);
679 
680     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
681         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
682       return false;
683   }
684   // If crtfastmath.o exists add it to the arguments.
685   std::string Path = GetFilePath("crtfastmath.o");
686   if (Path == "crtfastmath.o") // Not found.
687     return false;
688 
689   CmdArgs.push_back(Args.MakeArgString(Path));
690   return true;
691 }
692 
693 SanitizerMask ToolChain::getSupportedSanitizers() const {
694   // Return sanitizers which don't require runtime support and are not
695   // platform dependent.
696   using namespace SanitizerKind;
697   SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
698                       CFICastStrict | UnsignedIntegerOverflow | LocalBounds;
699   if (getTriple().getArch() == llvm::Triple::x86 ||
700       getTriple().getArch() == llvm::Triple::x86_64 ||
701       getTriple().getArch() == llvm::Triple::arm ||
702       getTriple().getArch() == llvm::Triple::aarch64 ||
703       getTriple().getArch() == llvm::Triple::wasm32 ||
704       getTriple().getArch() == llvm::Triple::wasm64)
705     Res |= CFIICall;
706   return Res;
707 }
708 
709 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
710                                    ArgStringList &CC1Args) const {}
711 
712 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
713                                     ArgStringList &CC1Args) const {}
714 
715 static VersionTuple separateMSVCFullVersion(unsigned Version) {
716   if (Version < 100)
717     return VersionTuple(Version);
718 
719   if (Version < 10000)
720     return VersionTuple(Version / 100, Version % 100);
721 
722   unsigned Build = 0, Factor = 1;
723   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
724     Build = Build + (Version % 10) * Factor;
725   return VersionTuple(Version / 100, Version % 100, Build);
726 }
727 
728 VersionTuple
729 ToolChain::computeMSVCVersion(const Driver *D,
730                               const llvm::opt::ArgList &Args) const {
731   const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
732   const Arg *MSCompatibilityVersion =
733       Args.getLastArg(options::OPT_fms_compatibility_version);
734 
735   if (MSCVersion && MSCompatibilityVersion) {
736     if (D)
737       D->Diag(diag::err_drv_argument_not_allowed_with)
738           << MSCVersion->getAsString(Args)
739           << MSCompatibilityVersion->getAsString(Args);
740     return VersionTuple();
741   }
742 
743   if (MSCompatibilityVersion) {
744     VersionTuple MSVT;
745     if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
746       if (D)
747         D->Diag(diag::err_drv_invalid_value)
748             << MSCompatibilityVersion->getAsString(Args)
749             << MSCompatibilityVersion->getValue();
750     } else {
751       return MSVT;
752     }
753   }
754 
755   if (MSCVersion) {
756     unsigned Version = 0;
757     if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
758       if (D)
759         D->Diag(diag::err_drv_invalid_value)
760             << MSCVersion->getAsString(Args) << MSCVersion->getValue();
761     } else {
762       return separateMSVCFullVersion(Version);
763     }
764   }
765 
766   return VersionTuple();
767 }
768