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