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