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