]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
Merge llvm, clang, lld and lldb release_40 branch r292009. Also update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains.cpp
1 //===--- ToolChains.cpp - ToolChain Implementations -------------*- C++ -*-===//
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 "ToolChains.h"
11 #include "clang/Basic/Cuda.h"
12 #include "clang/Basic/ObjCRuntime.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Basic/VirtualFileSystem.h"
15 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/Distro.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 "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Option/Arg.h"
27 #include "llvm/Option/ArgList.h"
28 #include "llvm/Option/OptTable.h"
29 #include "llvm/Option/Option.h"
30 #include "llvm/ProfileData/InstrProf.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/Program.h"
36 #include "llvm/Support/TargetParser.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cstdlib> // ::getenv
39 #include <system_error>
40
41 using namespace clang::driver;
42 using namespace clang::driver::toolchains;
43 using namespace clang;
44 using namespace llvm::opt;
45
46 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
47     : ToolChain(D, Triple, Args) {
48   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
49   getProgramPaths().push_back(getDriver().getInstalledDir());
50   if (getDriver().getInstalledDir() != getDriver().Dir)
51     getProgramPaths().push_back(getDriver().Dir);
52 }
53
54 /// Darwin - Darwin tool chain for i386 and x86_64.
55 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
56     : MachO(D, Triple, Args), TargetInitialized(false),
57       CudaInstallation(D, Triple, Args) {}
58
59 types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
60   types::ID Ty = types::lookupTypeForExtension(Ext);
61
62   // Darwin always preprocesses assembly files (unless -x is used explicitly).
63   if (Ty == types::TY_PP_Asm)
64     return types::TY_Asm;
65
66   return Ty;
67 }
68
69 bool MachO::HasNativeLLVMSupport() const { return true; }
70
71 ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
72   // Default to use libc++ on OS X 10.9+ and iOS 7+.
73   if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
74        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
75        isTargetWatchOSBased())
76     return ToolChain::CST_Libcxx;
77
78   return ToolChain::CST_Libstdcxx;
79 }
80
81 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
82 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
83   if (isTargetWatchOSBased())
84     return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
85   if (isTargetIOSBased())
86     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
87   if (isNonFragile)
88     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
89   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
90 }
91
92 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
93 bool Darwin::hasBlocksRuntime() const {
94   if (isTargetWatchOSBased())
95     return true;
96   else if (isTargetIOSBased())
97     return !isIPhoneOSVersionLT(3, 2);
98   else {
99     assert(isTargetMacOS() && "unexpected darwin target");
100     return !isMacosxVersionLT(10, 6);
101   }
102 }
103
104 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
105                                 ArgStringList &CC1Args) const {
106   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
107 }
108
109 // This is just a MachO name translation routine and there's no
110 // way to join this into ARMTargetParser without breaking all
111 // other assumptions. Maybe MachO should consider standardising
112 // their nomenclature.
113 static const char *ArmMachOArchName(StringRef Arch) {
114   return llvm::StringSwitch<const char *>(Arch)
115       .Case("armv6k", "armv6")
116       .Case("armv6m", "armv6m")
117       .Case("armv5tej", "armv5")
118       .Case("xscale", "xscale")
119       .Case("armv4t", "armv4t")
120       .Case("armv7", "armv7")
121       .Cases("armv7a", "armv7-a", "armv7")
122       .Cases("armv7r", "armv7-r", "armv7")
123       .Cases("armv7em", "armv7e-m", "armv7em")
124       .Cases("armv7k", "armv7-k", "armv7k")
125       .Cases("armv7m", "armv7-m", "armv7m")
126       .Cases("armv7s", "armv7-s", "armv7s")
127       .Default(nullptr);
128 }
129
130 static const char *ArmMachOArchNameCPU(StringRef CPU) {
131   unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
132   if (ArchKind == llvm::ARM::AK_INVALID)
133     return nullptr;
134   StringRef Arch = llvm::ARM::getArchName(ArchKind);
135
136   // FIXME: Make sure this MachO triple mangling is really necessary.
137   // ARMv5* normalises to ARMv5.
138   if (Arch.startswith("armv5"))
139     Arch = Arch.substr(0, 5);
140   // ARMv6*, except ARMv6M, normalises to ARMv6.
141   else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
142     Arch = Arch.substr(0, 5);
143   // ARMv7A normalises to ARMv7.
144   else if (Arch.endswith("v7a"))
145     Arch = Arch.substr(0, 5);
146   return Arch.data();
147 }
148
149 static bool isSoftFloatABI(const ArgList &Args) {
150   Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
151                            options::OPT_mfloat_abi_EQ);
152   if (!A)
153     return false;
154
155   return A->getOption().matches(options::OPT_msoft_float) ||
156          (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
157           A->getValue() == StringRef("soft"));
158 }
159
160 StringRef MachO::getMachOArchName(const ArgList &Args) const {
161   switch (getTriple().getArch()) {
162   default:
163     return getDefaultUniversalArchName();
164
165   case llvm::Triple::aarch64:
166     return "arm64";
167
168   case llvm::Triple::thumb:
169   case llvm::Triple::arm:
170     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
171       if (const char *Arch = ArmMachOArchName(A->getValue()))
172         return Arch;
173
174     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
175       if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
176         return Arch;
177
178     return "arm";
179   }
180 }
181
182 Darwin::~Darwin() {}
183
184 MachO::~MachO() {}
185
186 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
187                                                 types::ID InputType) const {
188   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
189
190   // If the target isn't initialized (e.g., an unknown Darwin platform, return
191   // the default triple).
192   if (!isTargetInitialized())
193     return Triple.getTriple();
194
195   SmallString<16> Str;
196   if (isTargetWatchOSBased())
197     Str += "watchos";
198   else if (isTargetTvOSBased())
199     Str += "tvos";
200   else if (isTargetIOSBased())
201     Str += "ios";
202   else
203     Str += "macosx";
204   Str += getTargetVersion().getAsString();
205   Triple.setOSName(Str);
206
207   return Triple.getTriple();
208 }
209
210 void Generic_ELF::anchor() {}
211
212 Tool *MachO::getTool(Action::ActionClass AC) const {
213   switch (AC) {
214   case Action::LipoJobClass:
215     if (!Lipo)
216       Lipo.reset(new tools::darwin::Lipo(*this));
217     return Lipo.get();
218   case Action::DsymutilJobClass:
219     if (!Dsymutil)
220       Dsymutil.reset(new tools::darwin::Dsymutil(*this));
221     return Dsymutil.get();
222   case Action::VerifyDebugInfoJobClass:
223     if (!VerifyDebug)
224       VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
225     return VerifyDebug.get();
226   default:
227     return ToolChain::getTool(AC);
228   }
229 }
230
231 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
232
233 Tool *MachO::buildAssembler() const {
234   return new tools::darwin::Assembler(*this);
235 }
236
237 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
238                          const ArgList &Args)
239     : Darwin(D, Triple, Args) {}
240
241 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
242   // For modern targets, promote certain warnings to errors.
243   if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
244     // Always enable -Wdeprecated-objc-isa-usage and promote it
245     // to an error.
246     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
247     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
248
249     // For iOS and watchOS, also error about implicit function declarations,
250     // as that can impact calling conventions.
251     if (!isTargetMacOS())
252       CC1Args.push_back("-Werror=implicit-function-declaration");
253   }
254 }
255
256 /// \brief Determine whether Objective-C automated reference counting is
257 /// enabled.
258 static bool isObjCAutoRefCount(const ArgList &Args) {
259   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
260 }
261
262 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
263                                  ArgStringList &CmdArgs) const {
264   // Avoid linking compatibility stubs on i386 mac.
265   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
266     return;
267
268   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
269
270   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
271       runtime.hasSubscripting())
272     return;
273
274   CmdArgs.push_back("-force_load");
275   SmallString<128> P(getDriver().ClangExecutable);
276   llvm::sys::path::remove_filename(P); // 'clang'
277   llvm::sys::path::remove_filename(P); // 'bin'
278   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
279   // Mash in the platform.
280   if (isTargetWatchOSSimulator())
281     P += "watchsimulator";
282   else if (isTargetWatchOS())
283     P += "watchos";
284   else if (isTargetTvOSSimulator())
285     P += "appletvsimulator";
286   else if (isTargetTvOS())
287     P += "appletvos";
288   else if (isTargetIOSSimulator())
289     P += "iphonesimulator";
290   else if (isTargetIPhoneOS())
291     P += "iphoneos";
292   else
293     P += "macosx";
294   P += ".a";
295
296   CmdArgs.push_back(Args.MakeArgString(P));
297 }
298
299 unsigned DarwinClang::GetDefaultDwarfVersion() const {
300   // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
301   if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
302       (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
303     return 2;
304   return 4;
305 }
306
307 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
308                               StringRef DarwinLibName, bool AlwaysLink,
309                               bool IsEmbedded, bool AddRPath) const {
310   SmallString<128> Dir(getDriver().ResourceDir);
311   llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
312
313   SmallString<128> P(Dir);
314   llvm::sys::path::append(P, DarwinLibName);
315
316   // For now, allow missing resource libraries to support developers who may
317   // not have compiler-rt checked out or integrated into their build (unless
318   // we explicitly force linking with this library).
319   if (AlwaysLink || getVFS().exists(P))
320     CmdArgs.push_back(Args.MakeArgString(P));
321
322   // Adding the rpaths might negatively interact when other rpaths are involved,
323   // so we should make sure we add the rpaths last, after all user-specified
324   // rpaths. This is currently true from this place, but we need to be
325   // careful if this function is ever called before user's rpaths are emitted.
326   if (AddRPath) {
327     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
328
329     // Add @executable_path to rpath to support having the dylib copied with
330     // the executable.
331     CmdArgs.push_back("-rpath");
332     CmdArgs.push_back("@executable_path");
333
334     // Add the path to the resource dir to rpath to support using the dylib
335     // from the default location without copying.
336     CmdArgs.push_back("-rpath");
337     CmdArgs.push_back(Args.MakeArgString(Dir));
338   }
339 }
340
341 StringRef Darwin::getPlatformFamily() const {
342   switch (TargetPlatform) {
343     case DarwinPlatformKind::MacOS:
344       return "MacOSX";
345     case DarwinPlatformKind::IPhoneOS:
346     case DarwinPlatformKind::IPhoneOSSimulator:
347       return "iPhone";
348     case DarwinPlatformKind::TvOS:
349     case DarwinPlatformKind::TvOSSimulator:
350       return "AppleTV";
351     case DarwinPlatformKind::WatchOS:
352     case DarwinPlatformKind::WatchOSSimulator:
353       return "Watch";
354   }
355   llvm_unreachable("Unsupported platform");
356 }
357
358 StringRef Darwin::getSDKName(StringRef isysroot) {
359   // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
360   llvm::sys::path::const_iterator SDKDir;
361   auto BeginSDK = llvm::sys::path::begin(isysroot);
362   auto EndSDK = llvm::sys::path::end(isysroot);
363   for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
364     StringRef SDK = *IT;
365     if (SDK.endswith(".sdk"))
366       return SDK.slice(0, SDK.size() - 4);
367   }
368   return "";
369 }
370
371 StringRef Darwin::getOSLibraryNameSuffix() const {
372   switch(TargetPlatform) {
373   case DarwinPlatformKind::MacOS:
374     return "osx";
375   case DarwinPlatformKind::IPhoneOS:
376     return "ios";
377   case DarwinPlatformKind::IPhoneOSSimulator:
378     return "iossim";
379   case DarwinPlatformKind::TvOS:
380     return "tvos";
381   case DarwinPlatformKind::TvOSSimulator:
382     return "tvossim";
383   case DarwinPlatformKind::WatchOS:
384     return "watchos";
385   case DarwinPlatformKind::WatchOSSimulator:
386     return "watchossim";
387   }
388   llvm_unreachable("Unsupported platform");
389 }
390
391 void Darwin::addProfileRTLibs(const ArgList &Args,
392                               ArgStringList &CmdArgs) const {
393   if (!needsProfileRT(Args)) return;
394
395   AddLinkRuntimeLib(Args, CmdArgs, (Twine("libclang_rt.profile_") +
396        getOSLibraryNameSuffix() + ".a").str(),
397                     /*AlwaysLink*/ true);
398 }
399
400 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
401                                           ArgStringList &CmdArgs,
402                                           StringRef Sanitizer) const {
403   AddLinkRuntimeLib(
404       Args, CmdArgs,
405       (Twine("libclang_rt.") + Sanitizer + "_" +
406        getOSLibraryNameSuffix() + "_dynamic.dylib").str(),
407       /*AlwaysLink*/ true, /*IsEmbedded*/ false,
408       /*AddRPath*/ true);
409 }
410
411 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
412     const ArgList &Args) const {
413   if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
414     StringRef Value = A->getValue();
415     if (Value != "compiler-rt")
416       getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
417           << Value << "darwin";
418   }
419
420   return ToolChain::RLT_CompilerRT;
421 }
422
423 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
424                                         ArgStringList &CmdArgs) const {
425   // Call once to ensure diagnostic is printed if wrong value was specified
426   GetRuntimeLibType(Args);
427
428   // Darwin doesn't support real static executables, don't link any runtime
429   // libraries with -static.
430   if (Args.hasArg(options::OPT_static) ||
431       Args.hasArg(options::OPT_fapple_kext) ||
432       Args.hasArg(options::OPT_mkernel))
433     return;
434
435   // Reject -static-libgcc for now, we can deal with this when and if someone
436   // cares. This is useful in situations where someone wants to statically link
437   // something like libstdc++, and needs its runtime support routines.
438   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
439     getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
440     return;
441   }
442
443   const SanitizerArgs &Sanitize = getSanitizerArgs();
444   if (Sanitize.needsAsanRt())
445     AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
446   if (Sanitize.needsUbsanRt())
447     AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
448   if (Sanitize.needsTsanRt())
449     AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
450   if (Sanitize.needsStatsRt()) {
451     StringRef OS = isTargetMacOS() ? "osx" : "iossim";
452     AddLinkRuntimeLib(Args, CmdArgs,
453                       (Twine("libclang_rt.stats_client_") + OS + ".a").str(),
454                       /*AlwaysLink=*/true);
455     AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
456   }
457   if (Sanitize.needsEsanRt())
458     AddLinkSanitizerLibArgs(Args, CmdArgs, "esan");
459
460   // Otherwise link libSystem, then the dynamic runtime library, and finally any
461   // target specific static runtime library.
462   CmdArgs.push_back("-lSystem");
463
464   // Select the dynamic runtime library and the target specific static library.
465   if (isTargetWatchOSBased()) {
466     // We currently always need a static runtime library for watchOS.
467     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
468   } else if (isTargetTvOSBased()) {
469     // We currently always need a static runtime library for tvOS.
470     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
471   } else if (isTargetIOSBased()) {
472     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
473     // it never went into the SDK.
474     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
475     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
476         getTriple().getArch() != llvm::Triple::aarch64)
477       CmdArgs.push_back("-lgcc_s.1");
478
479     // We currently always need a static runtime library for iOS.
480     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
481   } else {
482     assert(isTargetMacOS() && "unexpected non MacOS platform");
483     // The dynamic runtime library was merged with libSystem for 10.6 and
484     // beyond; only 10.4 and 10.5 need an additional runtime library.
485     if (isMacosxVersionLT(10, 5))
486       CmdArgs.push_back("-lgcc_s.10.4");
487     else if (isMacosxVersionLT(10, 6))
488       CmdArgs.push_back("-lgcc_s.10.5");
489
490     // Originally for OS X, we thought we would only need a static runtime
491     // library when targeting 10.4, to provide versions of the static functions
492     // which were omitted from 10.4.dylib. This led to the creation of the 10.4
493     // builtins library.
494     //
495     // Unfortunately, that turned out to not be true, because Darwin system
496     // headers can still use eprintf on i386, and it is not exported from
497     // libSystem. Therefore, we still must provide a runtime library just for
498     // the tiny tiny handful of projects that *might* use that symbol.
499     //
500     // Then over time, we figured out it was useful to add more things to the
501     // runtime so we created libclang_rt.osx.a to provide new functions when
502     // deploying to old OS builds, and for a long time we had both eprintf and
503     // osx builtin libraries. Which just seems excessive. So with PR 28855, we
504     // are removing the eprintf library and expecting eprintf to be provided by
505     // the OS X builtins library.
506     if (isMacosxVersionLT(10, 5))
507       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
508     else
509       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
510   }
511 }
512
513 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
514   const OptTable &Opts = getDriver().getOpts();
515
516   // Support allowing the SDKROOT environment variable used by xcrun and other
517   // Xcode tools to define the default sysroot, by making it the default for
518   // isysroot.
519   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
520     // Warn if the path does not exist.
521     if (!getVFS().exists(A->getValue()))
522       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
523   } else {
524     if (char *env = ::getenv("SDKROOT")) {
525       // We only use this value as the default if it is an absolute path,
526       // exists, and it is not the root path.
527       if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
528           StringRef(env) != "/") {
529         Args.append(Args.MakeSeparateArg(
530             nullptr, Opts.getOption(options::OPT_isysroot), env));
531       }
532     }
533   }
534
535   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
536   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
537   Arg *TvOSVersion = Args.getLastArg(options::OPT_mtvos_version_min_EQ);
538   Arg *WatchOSVersion = Args.getLastArg(options::OPT_mwatchos_version_min_EQ);
539
540   if (OSXVersion && (iOSVersion || TvOSVersion || WatchOSVersion)) {
541     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
542         << OSXVersion->getAsString(Args)
543         << (iOSVersion ? iOSVersion :
544             TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
545     iOSVersion = TvOSVersion = WatchOSVersion = nullptr;
546   } else if (iOSVersion && (TvOSVersion || WatchOSVersion)) {
547     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
548         << iOSVersion->getAsString(Args)
549         << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
550     TvOSVersion = WatchOSVersion = nullptr;
551   } else if (TvOSVersion && WatchOSVersion) {
552      getDriver().Diag(diag::err_drv_argument_not_allowed_with)
553         << TvOSVersion->getAsString(Args)
554         << WatchOSVersion->getAsString(Args);
555     WatchOSVersion = nullptr;
556   } else if (!OSXVersion && !iOSVersion && !TvOSVersion && !WatchOSVersion) {
557     // If no deployment target was specified on the command line, check for
558     // environment defines.
559     std::string OSXTarget;
560     std::string iOSTarget;
561     std::string TvOSTarget;
562     std::string WatchOSTarget;
563
564     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
565       OSXTarget = env;
566     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
567       iOSTarget = env;
568     if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET"))
569       TvOSTarget = env;
570     if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET"))
571       WatchOSTarget = env;
572
573     // If there is no command-line argument to specify the Target version and
574     // no environment variable defined, see if we can set the default based
575     // on -isysroot.
576     if (OSXTarget.empty() && iOSTarget.empty() && WatchOSTarget.empty() &&
577         TvOSTarget.empty() && Args.hasArg(options::OPT_isysroot)) {
578       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
579         StringRef isysroot = A->getValue();
580         StringRef SDK = getSDKName(isysroot);
581         if (SDK.size() > 0) {
582           // Slice the version number out.
583           // Version number is between the first and the last number.
584           size_t StartVer = SDK.find_first_of("0123456789");
585           size_t EndVer = SDK.find_last_of("0123456789");
586           if (StartVer != StringRef::npos && EndVer > StartVer) {
587             StringRef Version = SDK.slice(StartVer, EndVer + 1);
588             if (SDK.startswith("iPhoneOS") ||
589                 SDK.startswith("iPhoneSimulator"))
590               iOSTarget = Version;
591             else if (SDK.startswith("MacOSX"))
592               OSXTarget = Version;
593             else if (SDK.startswith("WatchOS") ||
594                      SDK.startswith("WatchSimulator"))
595               WatchOSTarget = Version;
596             else if (SDK.startswith("AppleTVOS") ||
597                      SDK.startswith("AppleTVSimulator"))
598               TvOSTarget = Version;
599           }
600         }
601       }
602     }
603
604     // If no OSX or iOS target has been specified, try to guess platform
605     // from arch name and compute the version from the triple.
606     if (OSXTarget.empty() && iOSTarget.empty() && TvOSTarget.empty() &&
607         WatchOSTarget.empty()) {
608       StringRef MachOArchName = getMachOArchName(Args);
609       unsigned Major, Minor, Micro;
610       if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
611           MachOArchName == "arm64") {
612         getTriple().getiOSVersion(Major, Minor, Micro);
613         llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
614                                             << Micro;
615       } else if (MachOArchName == "armv7k") {
616         getTriple().getWatchOSVersion(Major, Minor, Micro);
617         llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.'
618                                                 << Micro;
619       } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
620                  MachOArchName != "armv7em") {
621         if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
622           getDriver().Diag(diag::err_drv_invalid_darwin_version)
623               << getTriple().getOSName();
624         }
625         llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
626                                             << Micro;
627       }
628     }
629
630     // Do not allow conflicts with the watchOS target.
631     if (!WatchOSTarget.empty() && (!iOSTarget.empty() || !TvOSTarget.empty())) {
632       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
633         << "WATCHOS_DEPLOYMENT_TARGET"
634         << (!iOSTarget.empty() ? "IPHONEOS_DEPLOYMENT_TARGET" :
635             "TVOS_DEPLOYMENT_TARGET");
636     }
637
638     // Do not allow conflicts with the tvOS target.
639     if (!TvOSTarget.empty() && !iOSTarget.empty()) {
640       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
641         << "TVOS_DEPLOYMENT_TARGET"
642         << "IPHONEOS_DEPLOYMENT_TARGET";
643     }
644
645     // Allow conflicts among OSX and iOS for historical reasons, but choose the
646     // default platform.
647     if (!OSXTarget.empty() && (!iOSTarget.empty() ||
648                                !WatchOSTarget.empty() ||
649                                !TvOSTarget.empty())) {
650       if (getTriple().getArch() == llvm::Triple::arm ||
651           getTriple().getArch() == llvm::Triple::aarch64 ||
652           getTriple().getArch() == llvm::Triple::thumb)
653         OSXTarget = "";
654       else
655         iOSTarget = WatchOSTarget = TvOSTarget = "";
656     }
657
658     if (!OSXTarget.empty()) {
659       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
660       OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
661       Args.append(OSXVersion);
662     } else if (!iOSTarget.empty()) {
663       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
664       iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
665       Args.append(iOSVersion);
666     } else if (!TvOSTarget.empty()) {
667       const Option O = Opts.getOption(options::OPT_mtvos_version_min_EQ);
668       TvOSVersion = Args.MakeJoinedArg(nullptr, O, TvOSTarget);
669       Args.append(TvOSVersion);
670     } else if (!WatchOSTarget.empty()) {
671       const Option O = Opts.getOption(options::OPT_mwatchos_version_min_EQ);
672       WatchOSVersion = Args.MakeJoinedArg(nullptr, O, WatchOSTarget);
673       Args.append(WatchOSVersion);
674     }
675   }
676
677   DarwinPlatformKind Platform;
678   if (OSXVersion)
679     Platform = MacOS;
680   else if (iOSVersion)
681     Platform = IPhoneOS;
682   else if (TvOSVersion)
683     Platform = TvOS;
684   else if (WatchOSVersion)
685     Platform = WatchOS;
686   else
687     llvm_unreachable("Unable to infer Darwin variant");
688
689   // Set the tool chain target information.
690   unsigned Major, Minor, Micro;
691   bool HadExtra;
692   if (Platform == MacOS) {
693     assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) &&
694            "Unknown target platform!");
695     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
696                                    HadExtra) ||
697         HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
698       getDriver().Diag(diag::err_drv_invalid_version_number)
699           << OSXVersion->getAsString(Args);
700   } else if (Platform == IPhoneOS) {
701     assert(iOSVersion && "Unknown target platform!");
702     if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
703                                    HadExtra) ||
704         HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
705       getDriver().Diag(diag::err_drv_invalid_version_number)
706           << iOSVersion->getAsString(Args);
707   } else if (Platform == TvOS) {
708     if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor,
709                                    Micro, HadExtra) || HadExtra ||
710         Major >= 100 || Minor >= 100 || Micro >= 100)
711       getDriver().Diag(diag::err_drv_invalid_version_number)
712           << TvOSVersion->getAsString(Args);
713   } else if (Platform == WatchOS) {
714     if (!Driver::GetReleaseVersion(WatchOSVersion->getValue(), Major, Minor,
715                                    Micro, HadExtra) || HadExtra ||
716         Major >= 10 || Minor >= 100 || Micro >= 100)
717       getDriver().Diag(diag::err_drv_invalid_version_number)
718           << WatchOSVersion->getAsString(Args);
719   } else
720     llvm_unreachable("unknown kind of Darwin platform");
721
722   // Recognize iOS targets with an x86 architecture as the iOS simulator.
723   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
724                      getTriple().getArch() == llvm::Triple::x86_64))
725     Platform = IPhoneOSSimulator;
726   if (TvOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
727                       getTriple().getArch() == llvm::Triple::x86_64))
728     Platform = TvOSSimulator;
729   if (WatchOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
730                          getTriple().getArch() == llvm::Triple::x86_64))
731     Platform = WatchOSSimulator;
732
733   setTarget(Platform, Major, Minor, Micro);
734
735   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
736     StringRef SDK = getSDKName(A->getValue());
737     if (SDK.size() > 0) {
738       size_t StartVer = SDK.find_first_of("0123456789");
739       StringRef SDKName = SDK.slice(0, StartVer);
740       if (!SDKName.startswith(getPlatformFamily()))
741         getDriver().Diag(diag::warn_incompatible_sysroot)
742             << SDKName << getPlatformFamily();
743     }
744   }
745 }
746
747 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
748                                       ArgStringList &CmdArgs) const {
749   CXXStdlibType Type = GetCXXStdlibType(Args);
750
751   switch (Type) {
752   case ToolChain::CST_Libcxx:
753     CmdArgs.push_back("-lc++");
754     break;
755
756   case ToolChain::CST_Libstdcxx:
757     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
758     // it was previously found in the gcc lib dir. However, for all the Darwin
759     // platforms we care about it was -lstdc++.6, so we search for that
760     // explicitly if we can't see an obvious -lstdc++ candidate.
761
762     // Check in the sysroot first.
763     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
764       SmallString<128> P(A->getValue());
765       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
766
767       if (!getVFS().exists(P)) {
768         llvm::sys::path::remove_filename(P);
769         llvm::sys::path::append(P, "libstdc++.6.dylib");
770         if (getVFS().exists(P)) {
771           CmdArgs.push_back(Args.MakeArgString(P));
772           return;
773         }
774       }
775     }
776
777     // Otherwise, look in the root.
778     // FIXME: This should be removed someday when we don't have to care about
779     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
780     if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
781         getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
782       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
783       return;
784     }
785
786     // Otherwise, let the linker search.
787     CmdArgs.push_back("-lstdc++");
788     break;
789   }
790 }
791
792 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
793                                    ArgStringList &CmdArgs) const {
794   // For Darwin platforms, use the compiler-rt-based support library
795   // instead of the gcc-provided one (which is also incidentally
796   // only present in the gcc lib dir, which makes it hard to find).
797
798   SmallString<128> P(getDriver().ResourceDir);
799   llvm::sys::path::append(P, "lib", "darwin");
800
801   // Use the newer cc_kext for iOS ARM after 6.0.
802   if (isTargetWatchOS()) {
803     llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
804   } else if (isTargetTvOS()) {
805     llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
806   } else if (isTargetIPhoneOS()) {
807     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
808   } else {
809     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
810   }
811
812   // For now, allow missing resource libraries to support developers who may
813   // not have compiler-rt checked out or integrated into their build.
814   if (getVFS().exists(P))
815     CmdArgs.push_back(Args.MakeArgString(P));
816 }
817
818 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
819                                      StringRef BoundArch,
820                                      Action::OffloadKind) const {
821   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
822   const OptTable &Opts = getDriver().getOpts();
823
824   // FIXME: We really want to get out of the tool chain level argument
825   // translation business, as it makes the driver functionality much
826   // more opaque. For now, we follow gcc closely solely for the
827   // purpose of easily achieving feature parity & testability. Once we
828   // have something that works, we should reevaluate each translation
829   // and try to push it down into tool specific logic.
830
831   for (Arg *A : Args) {
832     if (A->getOption().matches(options::OPT_Xarch__)) {
833       // Skip this argument unless the architecture matches either the toolchain
834       // triple arch, or the arch being bound.
835       llvm::Triple::ArchType XarchArch =
836           tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
837       if (!(XarchArch == getArch() ||
838             (!BoundArch.empty() &&
839              XarchArch ==
840                  tools::darwin::getArchTypeForMachOArchName(BoundArch))))
841         continue;
842
843       Arg *OriginalArg = A;
844       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
845       unsigned Prev = Index;
846       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
847
848       // If the argument parsing failed or more than one argument was
849       // consumed, the -Xarch_ argument's parameter tried to consume
850       // extra arguments. Emit an error and ignore.
851       //
852       // We also want to disallow any options which would alter the
853       // driver behavior; that isn't going to work in our model. We
854       // use isDriverOption() as an approximation, although things
855       // like -O4 are going to slip through.
856       if (!XarchArg || Index > Prev + 1) {
857         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
858             << A->getAsString(Args);
859         continue;
860       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
861         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
862             << A->getAsString(Args);
863         continue;
864       }
865
866       XarchArg->setBaseArg(A);
867
868       A = XarchArg.release();
869       DAL->AddSynthesizedArg(A);
870
871       // Linker input arguments require custom handling. The problem is that we
872       // have already constructed the phase actions, so we can not treat them as
873       // "input arguments".
874       if (A->getOption().hasFlag(options::LinkerInput)) {
875         // Convert the argument into individual Zlinker_input_args.
876         for (const char *Value : A->getValues()) {
877           DAL->AddSeparateArg(
878               OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
879         }
880         continue;
881       }
882     }
883
884     // Sob. These is strictly gcc compatible for the time being. Apple
885     // gcc translates options twice, which means that self-expanding
886     // options add duplicates.
887     switch ((options::ID)A->getOption().getID()) {
888     default:
889       DAL->append(A);
890       break;
891
892     case options::OPT_mkernel:
893     case options::OPT_fapple_kext:
894       DAL->append(A);
895       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
896       break;
897
898     case options::OPT_dependency_file:
899       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
900       break;
901
902     case options::OPT_gfull:
903       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
904       DAL->AddFlagArg(
905           A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
906       break;
907
908     case options::OPT_gused:
909       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
910       DAL->AddFlagArg(
911           A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
912       break;
913
914     case options::OPT_shared:
915       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
916       break;
917
918     case options::OPT_fconstant_cfstrings:
919       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
920       break;
921
922     case options::OPT_fno_constant_cfstrings:
923       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
924       break;
925
926     case options::OPT_Wnonportable_cfstrings:
927       DAL->AddFlagArg(A,
928                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
929       break;
930
931     case options::OPT_Wno_nonportable_cfstrings:
932       DAL->AddFlagArg(
933           A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
934       break;
935
936     case options::OPT_fpascal_strings:
937       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
938       break;
939
940     case options::OPT_fno_pascal_strings:
941       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
942       break;
943     }
944   }
945
946   if (getTriple().getArch() == llvm::Triple::x86 ||
947       getTriple().getArch() == llvm::Triple::x86_64)
948     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
949       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
950                         "core2");
951
952   // Add the arch options based on the particular spelling of -arch, to match
953   // how the driver driver works.
954   if (!BoundArch.empty()) {
955     StringRef Name = BoundArch;
956     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
957     const Option MArch = Opts.getOption(options::OPT_march_EQ);
958
959     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
960     // which defines the list of which architectures we accept.
961     if (Name == "ppc")
962       ;
963     else if (Name == "ppc601")
964       DAL->AddJoinedArg(nullptr, MCpu, "601");
965     else if (Name == "ppc603")
966       DAL->AddJoinedArg(nullptr, MCpu, "603");
967     else if (Name == "ppc604")
968       DAL->AddJoinedArg(nullptr, MCpu, "604");
969     else if (Name == "ppc604e")
970       DAL->AddJoinedArg(nullptr, MCpu, "604e");
971     else if (Name == "ppc750")
972       DAL->AddJoinedArg(nullptr, MCpu, "750");
973     else if (Name == "ppc7400")
974       DAL->AddJoinedArg(nullptr, MCpu, "7400");
975     else if (Name == "ppc7450")
976       DAL->AddJoinedArg(nullptr, MCpu, "7450");
977     else if (Name == "ppc970")
978       DAL->AddJoinedArg(nullptr, MCpu, "970");
979
980     else if (Name == "ppc64" || Name == "ppc64le")
981       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
982
983     else if (Name == "i386")
984       ;
985     else if (Name == "i486")
986       DAL->AddJoinedArg(nullptr, MArch, "i486");
987     else if (Name == "i586")
988       DAL->AddJoinedArg(nullptr, MArch, "i586");
989     else if (Name == "i686")
990       DAL->AddJoinedArg(nullptr, MArch, "i686");
991     else if (Name == "pentium")
992       DAL->AddJoinedArg(nullptr, MArch, "pentium");
993     else if (Name == "pentium2")
994       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
995     else if (Name == "pentpro")
996       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
997     else if (Name == "pentIIm3")
998       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
999
1000     else if (Name == "x86_64")
1001       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1002     else if (Name == "x86_64h") {
1003       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1004       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
1005     }
1006
1007     else if (Name == "arm")
1008       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1009     else if (Name == "armv4t")
1010       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1011     else if (Name == "armv5")
1012       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
1013     else if (Name == "xscale")
1014       DAL->AddJoinedArg(nullptr, MArch, "xscale");
1015     else if (Name == "armv6")
1016       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
1017     else if (Name == "armv6m")
1018       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
1019     else if (Name == "armv7")
1020       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
1021     else if (Name == "armv7em")
1022       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
1023     else if (Name == "armv7k")
1024       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
1025     else if (Name == "armv7m")
1026       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
1027     else if (Name == "armv7s")
1028       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
1029   }
1030
1031   return DAL;
1032 }
1033
1034 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
1035                                   ArgStringList &CmdArgs) const {
1036   // Embedded targets are simple at the moment, not supporting sanitizers and
1037   // with different libraries for each member of the product { static, PIC } x
1038   // { hard-float, soft-float }
1039   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
1040   CompilerRT +=
1041       (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
1042           ? "hard"
1043           : "soft";
1044   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
1045
1046   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
1047 }
1048
1049 DerivedArgList *
1050 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
1051                       Action::OffloadKind DeviceOffloadKind) const {
1052   // First get the generic Apple args, before moving onto Darwin-specific ones.
1053   DerivedArgList *DAL =
1054       MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
1055   const OptTable &Opts = getDriver().getOpts();
1056
1057   // If no architecture is bound, none of the translations here are relevant.
1058   if (BoundArch.empty())
1059     return DAL;
1060
1061   // Add an explicit version min argument for the deployment target. We do this
1062   // after argument translation because -Xarch_ arguments may add a version min
1063   // argument.
1064   AddDeploymentTarget(*DAL);
1065
1066   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
1067   // FIXME: It would be far better to avoid inserting those -static arguments,
1068   // but we can't check the deployment target in the translation code until
1069   // it is set here.
1070   if (isTargetWatchOSBased() ||
1071       (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
1072     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
1073       Arg *A = *it;
1074       ++it;
1075       if (A->getOption().getID() != options::OPT_mkernel &&
1076           A->getOption().getID() != options::OPT_fapple_kext)
1077         continue;
1078       assert(it != ie && "unexpected argument translation");
1079       A = *it;
1080       assert(A->getOption().getID() == options::OPT_static &&
1081              "missing expected -static argument");
1082       it = DAL->getArgs().erase(it);
1083     }
1084   }
1085
1086   if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
1087       GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
1088     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
1089                       "libc++");
1090
1091   // Validate the C++ standard library choice.
1092   CXXStdlibType Type = GetCXXStdlibType(*DAL);
1093   if (Type == ToolChain::CST_Libcxx) {
1094     // Check whether the target provides libc++.
1095     StringRef where;
1096
1097     // Complain about targeting iOS < 5.0 in any way.
1098     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
1099       where = "iOS 5.0";
1100
1101     if (where != StringRef()) {
1102       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
1103     }
1104   }
1105
1106   auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
1107   if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
1108     if (Args.hasFlag(options::OPT_fomit_frame_pointer,
1109                      options::OPT_fno_omit_frame_pointer, false))
1110       getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
1111           << "-fomit-frame-pointer" << BoundArch;
1112     if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
1113                      options::OPT_mno_omit_leaf_frame_pointer, false))
1114       getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
1115           << "-momit-leaf-frame-pointer" << BoundArch;
1116   }
1117
1118   return DAL;
1119 }
1120
1121 bool MachO::IsUnwindTablesDefault() const {
1122   return getArch() == llvm::Triple::x86_64;
1123 }
1124
1125 bool MachO::UseDwarfDebugFlags() const {
1126   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
1127     return S[0] != '\0';
1128   return false;
1129 }
1130
1131 bool Darwin::UseSjLjExceptions(const ArgList &Args) const {
1132   // Darwin uses SjLj exceptions on ARM.
1133   if (getTriple().getArch() != llvm::Triple::arm &&
1134       getTriple().getArch() != llvm::Triple::thumb)
1135     return false;
1136
1137   // Only watchOS uses the new DWARF/Compact unwinding method.
1138   llvm::Triple Triple(ComputeLLVMTriple(Args));
1139   return !Triple.isWatchABI();
1140 }
1141
1142 bool Darwin::SupportsEmbeddedBitcode() const {
1143   assert(TargetInitialized && "Target not initialized!");
1144   if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
1145     return false;
1146   return true;
1147 }
1148
1149 bool MachO::isPICDefault() const { return true; }
1150
1151 bool MachO::isPIEDefault() const { return false; }
1152
1153 bool MachO::isPICDefaultForced() const {
1154   return (getArch() == llvm::Triple::x86_64 ||
1155           getArch() == llvm::Triple::aarch64);
1156 }
1157
1158 bool MachO::SupportsProfiling() const {
1159   // Profiling instrumentation is only supported on x86.
1160   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
1161 }
1162
1163 void Darwin::addMinVersionArgs(const ArgList &Args,
1164                                ArgStringList &CmdArgs) const {
1165   VersionTuple TargetVersion = getTargetVersion();
1166
1167   if (isTargetWatchOS())
1168     CmdArgs.push_back("-watchos_version_min");
1169   else if (isTargetWatchOSSimulator())
1170     CmdArgs.push_back("-watchos_simulator_version_min");
1171   else if (isTargetTvOS())
1172     CmdArgs.push_back("-tvos_version_min");
1173   else if (isTargetTvOSSimulator())
1174     CmdArgs.push_back("-tvos_simulator_version_min");
1175   else if (isTargetIOSSimulator())
1176     CmdArgs.push_back("-ios_simulator_version_min");
1177   else if (isTargetIOSBased())
1178     CmdArgs.push_back("-iphoneos_version_min");
1179   else {
1180     assert(isTargetMacOS() && "unexpected target");
1181     CmdArgs.push_back("-macosx_version_min");
1182   }
1183
1184   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
1185 }
1186
1187 void Darwin::addStartObjectFileArgs(const ArgList &Args,
1188                                     ArgStringList &CmdArgs) const {
1189   // Derived from startfile spec.
1190   if (Args.hasArg(options::OPT_dynamiclib)) {
1191     // Derived from darwin_dylib1 spec.
1192     if (isTargetWatchOSBased()) {
1193       ; // watchOS does not need dylib1.o.
1194     } else if (isTargetIOSSimulator()) {
1195       ; // iOS simulator does not need dylib1.o.
1196     } else if (isTargetIPhoneOS()) {
1197       if (isIPhoneOSVersionLT(3, 1))
1198         CmdArgs.push_back("-ldylib1.o");
1199     } else {
1200       if (isMacosxVersionLT(10, 5))
1201         CmdArgs.push_back("-ldylib1.o");
1202       else if (isMacosxVersionLT(10, 6))
1203         CmdArgs.push_back("-ldylib1.10.5.o");
1204     }
1205   } else {
1206     if (Args.hasArg(options::OPT_bundle)) {
1207       if (!Args.hasArg(options::OPT_static)) {
1208         // Derived from darwin_bundle1 spec.
1209         if (isTargetWatchOSBased()) {
1210           ; // watchOS does not need bundle1.o.
1211         } else if (isTargetIOSSimulator()) {
1212           ; // iOS simulator does not need bundle1.o.
1213         } else if (isTargetIPhoneOS()) {
1214           if (isIPhoneOSVersionLT(3, 1))
1215             CmdArgs.push_back("-lbundle1.o");
1216         } else {
1217           if (isMacosxVersionLT(10, 6))
1218             CmdArgs.push_back("-lbundle1.o");
1219         }
1220       }
1221     } else {
1222       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1223         if (Args.hasArg(options::OPT_static) ||
1224             Args.hasArg(options::OPT_object) ||
1225             Args.hasArg(options::OPT_preload)) {
1226           CmdArgs.push_back("-lgcrt0.o");
1227         } else {
1228           CmdArgs.push_back("-lgcrt1.o");
1229
1230           // darwin_crt2 spec is empty.
1231         }
1232         // By default on OS X 10.8 and later, we don't link with a crt1.o
1233         // file and the linker knows to use _main as the entry point.  But,
1234         // when compiling with -pg, we need to link with the gcrt1.o file,
1235         // so pass the -no_new_main option to tell the linker to use the
1236         // "start" symbol as the entry point.
1237         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1238           CmdArgs.push_back("-no_new_main");
1239       } else {
1240         if (Args.hasArg(options::OPT_static) ||
1241             Args.hasArg(options::OPT_object) ||
1242             Args.hasArg(options::OPT_preload)) {
1243           CmdArgs.push_back("-lcrt0.o");
1244         } else {
1245           // Derived from darwin_crt1 spec.
1246           if (isTargetWatchOSBased()) {
1247             ; // watchOS does not need crt1.o.
1248           } else if (isTargetIOSSimulator()) {
1249             ; // iOS simulator does not need crt1.o.
1250           } else if (isTargetIPhoneOS()) {
1251             if (getArch() == llvm::Triple::aarch64)
1252               ; // iOS does not need any crt1 files for arm64
1253             else if (isIPhoneOSVersionLT(3, 1))
1254               CmdArgs.push_back("-lcrt1.o");
1255             else if (isIPhoneOSVersionLT(6, 0))
1256               CmdArgs.push_back("-lcrt1.3.1.o");
1257           } else {
1258             if (isMacosxVersionLT(10, 5))
1259               CmdArgs.push_back("-lcrt1.o");
1260             else if (isMacosxVersionLT(10, 6))
1261               CmdArgs.push_back("-lcrt1.10.5.o");
1262             else if (isMacosxVersionLT(10, 8))
1263               CmdArgs.push_back("-lcrt1.10.6.o");
1264
1265             // darwin_crt2 spec is empty.
1266           }
1267         }
1268       }
1269     }
1270   }
1271
1272   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1273       !isTargetWatchOS() &&
1274       isMacosxVersionLT(10, 5)) {
1275     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1276     CmdArgs.push_back(Str);
1277   }
1278 }
1279
1280 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1281
1282 void Darwin::CheckObjCARC() const {
1283   if (isTargetIOSBased() || isTargetWatchOSBased() ||
1284       (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1285     return;
1286   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1287 }
1288
1289 SanitizerMask Darwin::getSupportedSanitizers() const {
1290   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
1291   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1292   Res |= SanitizerKind::Address;
1293   if (isTargetMacOS()) {
1294     if (!isMacosxVersionLT(10, 9))
1295       Res |= SanitizerKind::Vptr;
1296     Res |= SanitizerKind::SafeStack;
1297     if (IsX86_64)
1298       Res |= SanitizerKind::Thread;
1299   } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
1300     if (IsX86_64)
1301       Res |= SanitizerKind::Thread;
1302   }
1303   return Res;
1304 }
1305
1306 void Darwin::printVerboseInfo(raw_ostream &OS) const {
1307   CudaInstallation.print(OS);
1308 }
1309
1310 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1311 /// all subcommands; this relies on gcc translating the majority of
1312 /// command line options.
1313
1314 /// \brief Parse a GCCVersion object out of a string of text.
1315 ///
1316 /// This is the primary means of forming GCCVersion objects.
1317 /*static*/
1318 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1319   const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1320   std::pair<StringRef, StringRef> First = VersionText.split('.');
1321   std::pair<StringRef, StringRef> Second = First.second.split('.');
1322
1323   GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1324   if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1325     return BadVersion;
1326   GoodVersion.MajorStr = First.first.str();
1327   if (First.second.empty())
1328     return GoodVersion;
1329   if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1330     return BadVersion;
1331   GoodVersion.MinorStr = Second.first.str();
1332
1333   // First look for a number prefix and parse that if present. Otherwise just
1334   // stash the entire patch string in the suffix, and leave the number
1335   // unspecified. This covers versions strings such as:
1336   //   5        (handled above)
1337   //   4.4
1338   //   4.4.0
1339   //   4.4.x
1340   //   4.4.2-rc4
1341   //   4.4.x-patched
1342   // And retains any patch number it finds.
1343   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1344   if (!PatchText.empty()) {
1345     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1346       // Try to parse the number and any suffix.
1347       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1348           GoodVersion.Patch < 0)
1349         return BadVersion;
1350       GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1351     }
1352   }
1353
1354   return GoodVersion;
1355 }
1356
1357 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1358 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1359                                           int RHSPatch,
1360                                           StringRef RHSPatchSuffix) const {
1361   if (Major != RHSMajor)
1362     return Major < RHSMajor;
1363   if (Minor != RHSMinor)
1364     return Minor < RHSMinor;
1365   if (Patch != RHSPatch) {
1366     // Note that versions without a specified patch sort higher than those with
1367     // a patch.
1368     if (RHSPatch == -1)
1369       return true;
1370     if (Patch == -1)
1371       return false;
1372
1373     // Otherwise just sort on the patch itself.
1374     return Patch < RHSPatch;
1375   }
1376   if (PatchSuffix != RHSPatchSuffix) {
1377     // Sort empty suffixes higher.
1378     if (RHSPatchSuffix.empty())
1379       return true;
1380     if (PatchSuffix.empty())
1381       return false;
1382
1383     // Provide a lexicographic sort to make this a total ordering.
1384     return PatchSuffix < RHSPatchSuffix;
1385   }
1386
1387   // The versions are equal.
1388   return false;
1389 }
1390
1391 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1392   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1393   if (A)
1394     return A->getValue();
1395   return GCC_INSTALL_PREFIX;
1396 }
1397
1398 /// \brief Initialize a GCCInstallationDetector from the driver.
1399 ///
1400 /// This performs all of the autodetection and sets up the various paths.
1401 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1402 ///
1403 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1404 /// should instead pull the target out of the driver. This is currently
1405 /// necessary because the driver doesn't store the final version of the target
1406 /// triple.
1407 void Generic_GCC::GCCInstallationDetector::init(
1408     const llvm::Triple &TargetTriple, const ArgList &Args,
1409     ArrayRef<std::string> ExtraTripleAliases) {
1410   llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1411                                          ? TargetTriple.get64BitArchVariant()
1412                                          : TargetTriple.get32BitArchVariant();
1413   // The library directories which may contain GCC installations.
1414   SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1415   // The compatible GCC triples for this particular architecture.
1416   SmallVector<StringRef, 16> CandidateTripleAliases;
1417   SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1418   CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1419                            CandidateTripleAliases, CandidateBiarchLibDirs,
1420                            CandidateBiarchTripleAliases);
1421
1422   // Compute the set of prefixes for our search.
1423   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1424                                        D.PrefixDirs.end());
1425
1426   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1427   if (GCCToolchainDir != "") {
1428     if (GCCToolchainDir.back() == '/')
1429       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1430
1431     Prefixes.push_back(GCCToolchainDir);
1432   } else {
1433     // If we have a SysRoot, try that first.
1434     if (!D.SysRoot.empty()) {
1435       Prefixes.push_back(D.SysRoot);
1436       Prefixes.push_back(D.SysRoot + "/usr");
1437     }
1438
1439     // Then look for gcc installed alongside clang.
1440     Prefixes.push_back(D.InstalledDir + "/..");
1441
1442     // Then look for distribution supplied gcc installations.
1443     if (D.SysRoot.empty()) {
1444       // Look for RHEL devtoolsets.
1445       Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
1446       Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
1447       Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
1448       Prefixes.push_back("/opt/rh/devtoolset-1.1/root/usr");
1449       Prefixes.push_back("/opt/rh/devtoolset-1.0/root/usr");
1450       // And finally in /usr.
1451       Prefixes.push_back("/usr");
1452     }
1453   }
1454
1455   // Try to respect gcc-config on Gentoo. However, do that only
1456   // if --gcc-toolchain is not provided or equal to the Gentoo install
1457   // in /usr. This avoids accidentally enforcing the system GCC version
1458   // when using a custom toolchain.
1459   if (GCCToolchainDir == "" || GCCToolchainDir == D.SysRoot + "/usr") {
1460     for (StringRef CandidateTriple : ExtraTripleAliases) {
1461       if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
1462         return;
1463     }
1464     for (StringRef CandidateTriple : CandidateTripleAliases) {
1465       if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
1466         return;
1467     }
1468     for (StringRef CandidateTriple : CandidateBiarchTripleAliases) {
1469       if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
1470         return;
1471     }
1472   }
1473
1474   // Loop over the various components which exist and select the best GCC
1475   // installation available. GCC installs are ranked by version number.
1476   Version = GCCVersion::Parse("0.0.0");
1477   for (const std::string &Prefix : Prefixes) {
1478     if (!D.getVFS().exists(Prefix))
1479       continue;
1480     for (StringRef Suffix : CandidateLibDirs) {
1481       const std::string LibDir = Prefix + Suffix.str();
1482       if (!D.getVFS().exists(LibDir))
1483         continue;
1484       for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1485         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1486       for (StringRef Candidate : CandidateTripleAliases)
1487         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1488     }
1489     for (StringRef Suffix : CandidateBiarchLibDirs) {
1490       const std::string LibDir = Prefix + Suffix.str();
1491       if (!D.getVFS().exists(LibDir))
1492         continue;
1493       for (StringRef Candidate : CandidateBiarchTripleAliases)
1494         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1495                                /*NeedsBiarchSuffix=*/ true);
1496     }
1497   }
1498 }
1499
1500 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1501   for (const auto &InstallPath : CandidateGCCInstallPaths)
1502     OS << "Found candidate GCC installation: " << InstallPath << "\n";
1503
1504   if (!GCCInstallPath.empty())
1505     OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1506
1507   for (const auto &Multilib : Multilibs)
1508     OS << "Candidate multilib: " << Multilib << "\n";
1509
1510   if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1511     OS << "Selected multilib: " << SelectedMultilib << "\n";
1512 }
1513
1514 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1515   if (BiarchSibling.hasValue()) {
1516     M = BiarchSibling.getValue();
1517     return true;
1518   }
1519   return false;
1520 }
1521
1522 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1523     const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1524     SmallVectorImpl<StringRef> &LibDirs,
1525     SmallVectorImpl<StringRef> &TripleAliases,
1526     SmallVectorImpl<StringRef> &BiarchLibDirs,
1527     SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1528   // Declare a bunch of static data sets that we'll select between below. These
1529   // are specifically designed to always refer to string literals to avoid any
1530   // lifetime or initialization issues.
1531   static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1532   static const char *const AArch64Triples[] = {
1533       "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1534       "aarch64-redhat-linux", "aarch64-suse-linux"};
1535   static const char *const AArch64beLibDirs[] = {"/lib"};
1536   static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1537                                                  "aarch64_be-linux-gnu"};
1538
1539   static const char *const ARMLibDirs[] = {"/lib"};
1540   static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1541                                            "arm-linux-androideabi"};
1542   static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1543                                              "armv7hl-redhat-linux-gnueabi"};
1544   static const char *const ARMebLibDirs[] = {"/lib"};
1545   static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1546                                              "armeb-linux-androideabi"};
1547   static const char *const ARMebHFTriples[] = {
1548       "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1549
1550   static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1551   static const char *const X86_64Triples[] = {
1552       "x86_64-linux-gnu",       "x86_64-unknown-linux-gnu",
1553       "x86_64-pc-linux-gnu",    "x86_64-redhat-linux6E",
1554       "x86_64-redhat-linux",    "x86_64-suse-linux",
1555       "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1556       "x86_64-slackware-linux", "x86_64-linux-android",
1557       "x86_64-unknown-linux"};
1558   static const char *const X32LibDirs[] = {"/libx32"};
1559   static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1560   static const char *const X86Triples[] = {
1561       "i686-linux-gnu",       "i686-pc-linux-gnu",     "i486-linux-gnu",
1562       "i386-linux-gnu",       "i386-redhat-linux6E",   "i686-redhat-linux",
1563       "i586-redhat-linux",    "i386-redhat-linux",     "i586-suse-linux",
1564       "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1565       "i586-linux-gnu"};
1566
1567   static const char *const MIPSLibDirs[] = {"/lib"};
1568   static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
1569                                             "mips-mti-linux-gnu",
1570                                             "mips-img-linux-gnu"};
1571   static const char *const MIPSELLibDirs[] = {"/lib"};
1572   static const char *const MIPSELTriples[] = {"mipsel-linux-gnu",
1573                                               "mips-img-linux-gnu"};
1574
1575   static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1576   static const char *const MIPS64Triples[] = {
1577       "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1578       "mips64-linux-gnuabi64"};
1579   static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1580   static const char *const MIPS64ELTriples[] = {
1581       "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1582       "mips64el-linux-gnuabi64"};
1583
1584   static const char *const MIPSELAndroidLibDirs[] = {"/lib", "/libr2",
1585                                                      "/libr6"};
1586   static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
1587   static const char *const MIPS64ELAndroidLibDirs[] = {"/lib64", "/lib",
1588                                                        "/libr2", "/libr6"};
1589   static const char *const MIPS64ELAndroidTriples[] = {
1590       "mips64el-linux-android"};
1591
1592   static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1593   static const char *const PPCTriples[] = {
1594       "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1595       "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1596   static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1597   static const char *const PPC64Triples[] = {
1598       "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1599       "powerpc64-suse-linux", "ppc64-redhat-linux"};
1600   static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1601   static const char *const PPC64LETriples[] = {
1602       "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1603       "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1604
1605   static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1606   static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1607                                                "sparcv8-linux-gnu"};
1608   static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1609   static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1610                                                "sparcv9-linux-gnu"};
1611
1612   static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1613   static const char *const SystemZTriples[] = {
1614       "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1615       "s390x-suse-linux", "s390x-redhat-linux"};
1616
1617   // Solaris.
1618   static const char *const SolarisSPARCLibDirs[] = {"/gcc"};
1619   static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11",
1620                                                     "i386-pc-solaris2.11"};
1621
1622   using std::begin;
1623   using std::end;
1624
1625   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1626     LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs));
1627     TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples));
1628     return;
1629   }
1630
1631   switch (TargetTriple.getArch()) {
1632   case llvm::Triple::aarch64:
1633     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1634     TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1635     BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1636     BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1637     break;
1638   case llvm::Triple::aarch64_be:
1639     LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1640     TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1641     BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1642     BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1643     break;
1644   case llvm::Triple::arm:
1645   case llvm::Triple::thumb:
1646     LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1647     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1648       TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1649     } else {
1650       TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1651     }
1652     break;
1653   case llvm::Triple::armeb:
1654   case llvm::Triple::thumbeb:
1655     LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1656     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1657       TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1658     } else {
1659       TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1660     }
1661     break;
1662   case llvm::Triple::x86_64:
1663     LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1664     TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1665     // x32 is always available when x86_64 is available, so adding it as
1666     // secondary arch with x86_64 triples
1667     if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1668       BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1669       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1670     } else {
1671       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1672       BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1673     }
1674     break;
1675   case llvm::Triple::x86:
1676     LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1677     // MCU toolchain is 32 bit only and its triple alias is TargetTriple
1678     // itself, which will be appended below.
1679     if (!TargetTriple.isOSIAMCU()) {
1680       TripleAliases.append(begin(X86Triples), end(X86Triples));
1681       BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1682       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1683     }
1684     break;
1685   case llvm::Triple::mips:
1686     LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1687     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1688     BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1689     BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1690     break;
1691   case llvm::Triple::mipsel:
1692     if (TargetTriple.isAndroid()) {
1693       LibDirs.append(begin(MIPSELAndroidLibDirs), end(MIPSELAndroidLibDirs));
1694       TripleAliases.append(begin(MIPSELAndroidTriples),
1695                            end(MIPSELAndroidTriples));
1696       BiarchLibDirs.append(begin(MIPS64ELAndroidLibDirs),
1697                            end(MIPS64ELAndroidLibDirs));
1698       BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
1699                                  end(MIPS64ELAndroidTriples));
1700
1701     } else {
1702       LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1703       TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1704       TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1705       BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1706       BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1707     }
1708     break;
1709   case llvm::Triple::mips64:
1710     LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1711     TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1712     BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1713     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1714     break;
1715   case llvm::Triple::mips64el:
1716     if (TargetTriple.isAndroid()) {
1717       LibDirs.append(begin(MIPS64ELAndroidLibDirs),
1718                      end(MIPS64ELAndroidLibDirs));
1719       TripleAliases.append(begin(MIPS64ELAndroidTriples),
1720                            end(MIPS64ELAndroidTriples));
1721       BiarchLibDirs.append(begin(MIPSELAndroidLibDirs),
1722                            end(MIPSELAndroidLibDirs));
1723       BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
1724                                  end(MIPSELAndroidTriples));
1725
1726     } else {
1727       LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1728       TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1729       BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1730       BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1731       BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1732     }
1733     break;
1734   case llvm::Triple::ppc:
1735     LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1736     TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1737     BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1738     BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1739     break;
1740   case llvm::Triple::ppc64:
1741     LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1742     TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1743     BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1744     BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1745     break;
1746   case llvm::Triple::ppc64le:
1747     LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1748     TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1749     break;
1750   case llvm::Triple::sparc:
1751   case llvm::Triple::sparcel:
1752     LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1753     TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1754     BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1755     BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1756     break;
1757   case llvm::Triple::sparcv9:
1758     LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1759     TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1760     BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1761     BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1762     break;
1763   case llvm::Triple::systemz:
1764     LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1765     TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1766     break;
1767   default:
1768     // By default, just rely on the standard lib directories and the original
1769     // triple.
1770     break;
1771   }
1772
1773   // Always append the drivers target triple to the end, in case it doesn't
1774   // match any of our aliases.
1775   TripleAliases.push_back(TargetTriple.str());
1776
1777   // Also include the multiarch variant if it's different.
1778   if (TargetTriple.str() != BiarchTriple.str())
1779     BiarchTripleAliases.push_back(BiarchTriple.str());
1780 }
1781
1782 // Parses the contents of version.txt in an CUDA installation.  It should
1783 // contain one line of the from e.g. "CUDA Version 7.5.2".
1784 static CudaVersion ParseCudaVersionFile(llvm::StringRef V) {
1785   if (!V.startswith("CUDA Version "))
1786     return CudaVersion::UNKNOWN;
1787   V = V.substr(strlen("CUDA Version "));
1788   int Major = -1, Minor = -1;
1789   auto First = V.split('.');
1790   auto Second = First.second.split('.');
1791   if (First.first.getAsInteger(10, Major) ||
1792       Second.first.getAsInteger(10, Minor))
1793     return CudaVersion::UNKNOWN;
1794
1795   if (Major == 7 && Minor == 0) {
1796     // This doesn't appear to ever happen -- version.txt doesn't exist in the
1797     // CUDA 7 installs I've seen.  But no harm in checking.
1798     return CudaVersion::CUDA_70;
1799   }
1800   if (Major == 7 && Minor == 5)
1801     return CudaVersion::CUDA_75;
1802   if (Major == 8 && Minor == 0)
1803     return CudaVersion::CUDA_80;
1804   return CudaVersion::UNKNOWN;
1805 }
1806
1807 CudaInstallationDetector::CudaInstallationDetector(
1808     const Driver &D, const llvm::Triple &HostTriple,
1809     const llvm::opt::ArgList &Args)
1810     : D(D) {
1811   SmallVector<std::string, 4> CudaPathCandidates;
1812
1813   // In decreasing order so we prefer newer versions to older versions.
1814   std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
1815
1816   if (Args.hasArg(options::OPT_cuda_path_EQ)) {
1817     CudaPathCandidates.push_back(
1818         Args.getLastArgValue(options::OPT_cuda_path_EQ));
1819   } else if (HostTriple.isOSWindows()) {
1820     for (const char *Ver : Versions)
1821       CudaPathCandidates.push_back(
1822           D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
1823           Ver);
1824   } else {
1825     CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda");
1826     for (const char *Ver : Versions)
1827       CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-" + Ver);
1828   }
1829
1830   for (const auto &CudaPath : CudaPathCandidates) {
1831     if (CudaPath.empty() || !D.getVFS().exists(CudaPath))
1832       continue;
1833
1834     InstallPath = CudaPath;
1835     BinPath = CudaPath + "/bin";
1836     IncludePath = InstallPath + "/include";
1837     LibDevicePath = InstallPath + "/nvvm/libdevice";
1838
1839     auto &FS = D.getVFS();
1840     if (!(FS.exists(IncludePath) && FS.exists(BinPath) &&
1841           FS.exists(LibDevicePath)))
1842       continue;
1843
1844     // On Linux, we have both lib and lib64 directories, and we need to choose
1845     // based on our triple.  On MacOS, we have only a lib directory.
1846     //
1847     // It's sufficient for our purposes to be flexible: If both lib and lib64
1848     // exist, we choose whichever one matches our triple.  Otherwise, if only
1849     // lib exists, we use it.
1850     if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
1851       LibPath = InstallPath + "/lib64";
1852     else if (FS.exists(InstallPath + "/lib"))
1853       LibPath = InstallPath + "/lib";
1854     else
1855       continue;
1856
1857     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
1858         FS.getBufferForFile(InstallPath + "/version.txt");
1859     if (!VersionFile) {
1860       // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
1861       // version.txt isn't present.
1862       Version = CudaVersion::CUDA_70;
1863     } else {
1864       Version = ParseCudaVersionFile((*VersionFile)->getBuffer());
1865     }
1866
1867     std::error_code EC;
1868     for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
1869          !EC && LI != LE; LI = LI.increment(EC)) {
1870       StringRef FilePath = LI->path();
1871       StringRef FileName = llvm::sys::path::filename(FilePath);
1872       // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc
1873       const StringRef LibDeviceName = "libdevice.";
1874       if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
1875         continue;
1876       StringRef GpuArch = FileName.slice(
1877           LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
1878       LibDeviceMap[GpuArch] = FilePath.str();
1879       // Insert map entries for specifc devices with this compute
1880       // capability. NVCC's choice of the libdevice library version is
1881       // rather peculiar and depends on the CUDA version.
1882       if (GpuArch == "compute_20") {
1883         LibDeviceMap["sm_20"] = FilePath;
1884         LibDeviceMap["sm_21"] = FilePath;
1885         LibDeviceMap["sm_32"] = FilePath;
1886       } else if (GpuArch == "compute_30") {
1887         LibDeviceMap["sm_30"] = FilePath;
1888         if (Version < CudaVersion::CUDA_80) {
1889           LibDeviceMap["sm_50"] = FilePath;
1890           LibDeviceMap["sm_52"] = FilePath;
1891           LibDeviceMap["sm_53"] = FilePath;
1892         }
1893         LibDeviceMap["sm_60"] = FilePath;
1894         LibDeviceMap["sm_61"] = FilePath;
1895         LibDeviceMap["sm_62"] = FilePath;
1896       } else if (GpuArch == "compute_35") {
1897         LibDeviceMap["sm_35"] = FilePath;
1898         LibDeviceMap["sm_37"] = FilePath;
1899       } else if (GpuArch == "compute_50") {
1900         if (Version >= CudaVersion::CUDA_80) {
1901           LibDeviceMap["sm_50"] = FilePath;
1902           LibDeviceMap["sm_52"] = FilePath;
1903           LibDeviceMap["sm_53"] = FilePath;
1904         }
1905       }
1906     }
1907
1908     IsValid = true;
1909     break;
1910   }
1911 }
1912
1913 void CudaInstallationDetector::AddCudaIncludeArgs(
1914     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
1915   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
1916     // Add cuda_wrappers/* to our system include path.  This lets us wrap
1917     // standard library headers.
1918     SmallString<128> P(D.ResourceDir);
1919     llvm::sys::path::append(P, "include");
1920     llvm::sys::path::append(P, "cuda_wrappers");
1921     CC1Args.push_back("-internal-isystem");
1922     CC1Args.push_back(DriverArgs.MakeArgString(P));
1923   }
1924
1925   if (DriverArgs.hasArg(options::OPT_nocudainc))
1926     return;
1927
1928   if (!isValid()) {
1929     D.Diag(diag::err_drv_no_cuda_installation);
1930     return;
1931   }
1932
1933   CC1Args.push_back("-internal-isystem");
1934   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
1935   CC1Args.push_back("-include");
1936   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
1937 }
1938
1939 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
1940     CudaArch Arch) const {
1941   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
1942       ArchsWithVersionTooLowErrors.count(Arch) > 0)
1943     return;
1944
1945   auto RequiredVersion = MinVersionForCudaArch(Arch);
1946   if (Version < RequiredVersion) {
1947     ArchsWithVersionTooLowErrors.insert(Arch);
1948     D.Diag(diag::err_drv_cuda_version_too_low)
1949         << InstallPath << CudaArchToString(Arch) << CudaVersionToString(Version)
1950         << CudaVersionToString(RequiredVersion);
1951   }
1952 }
1953
1954 void CudaInstallationDetector::print(raw_ostream &OS) const {
1955   if (isValid())
1956     OS << "Found CUDA installation: " << InstallPath << ", version "
1957        << CudaVersionToString(Version) << "\n";
1958 }
1959
1960 namespace {
1961 // Filter to remove Multilibs that don't exist as a suffix to Path
1962 class FilterNonExistent {
1963   StringRef Base, File;
1964   vfs::FileSystem &VFS;
1965
1966 public:
1967   FilterNonExistent(StringRef Base, StringRef File, vfs::FileSystem &VFS)
1968       : Base(Base), File(File), VFS(VFS) {}
1969   bool operator()(const Multilib &M) {
1970     return !VFS.exists(Base + M.gccSuffix() + File);
1971   }
1972 };
1973 } // end anonymous namespace
1974
1975 static void addMultilibFlag(bool Enabled, const char *const Flag,
1976                             std::vector<std::string> &Flags) {
1977   if (Enabled)
1978     Flags.push_back(std::string("+") + Flag);
1979   else
1980     Flags.push_back(std::string("-") + Flag);
1981 }
1982
1983 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1984   return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1985 }
1986
1987 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1988   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1989          Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1990 }
1991
1992 static bool isMips32(llvm::Triple::ArchType Arch) {
1993   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1994 }
1995
1996 static bool isMips64(llvm::Triple::ArchType Arch) {
1997   return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1998 }
1999
2000 static bool isMipsEL(llvm::Triple::ArchType Arch) {
2001   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
2002 }
2003
2004 static bool isMips16(const ArgList &Args) {
2005   Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
2006   return A && A->getOption().matches(options::OPT_mips16);
2007 }
2008
2009 static bool isMicroMips(const ArgList &Args) {
2010   Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
2011   return A && A->getOption().matches(options::OPT_mmicromips);
2012 }
2013
2014 namespace {
2015 struct DetectedMultilibs {
2016   /// The set of multilibs that the detected installation supports.
2017   MultilibSet Multilibs;
2018
2019   /// The primary multilib appropriate for the given flags.
2020   Multilib SelectedMultilib;
2021
2022   /// On Biarch systems, this corresponds to the default multilib when
2023   /// targeting the non-default multilib. Otherwise, it is empty.
2024   llvm::Optional<Multilib> BiarchSibling;
2025 };
2026 } // end anonymous namespace
2027
2028 static Multilib makeMultilib(StringRef commonSuffix) {
2029   return Multilib(commonSuffix, commonSuffix, commonSuffix);
2030 }
2031
2032 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
2033                                 FilterNonExistent &NonExistent,
2034                                 DetectedMultilibs &Result) {
2035   // Check for Code Sourcery toolchain multilibs
2036   MultilibSet CSMipsMultilibs;
2037   {
2038     auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
2039
2040     auto MArchMicroMips =
2041         makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
2042
2043     auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
2044
2045     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
2046
2047     auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
2048
2049     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
2050
2051     auto DefaultFloat =
2052         makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
2053
2054     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
2055
2056     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2057
2058     // Note that this one's osSuffix is ""
2059     auto MAbi64 = makeMultilib("")
2060                       .gccSuffix("/64")
2061                       .includeSuffix("/64")
2062                       .flag("+mabi=n64")
2063                       .flag("-mabi=n32")
2064                       .flag("-m32");
2065
2066     CSMipsMultilibs =
2067         MultilibSet()
2068             .Either(MArchMips16, MArchMicroMips, MArchDefault)
2069             .Maybe(UCLibc)
2070             .Either(SoftFloat, Nan2008, DefaultFloat)
2071             .FilterOut("/micromips/nan2008")
2072             .FilterOut("/mips16/nan2008")
2073             .Either(BigEndian, LittleEndian)
2074             .Maybe(MAbi64)
2075             .FilterOut("/mips16.*/64")
2076             .FilterOut("/micromips.*/64")
2077             .FilterOut(NonExistent)
2078             .setIncludeDirsCallback([](const Multilib &M) {
2079               std::vector<std::string> Dirs({"/include"});
2080               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
2081                 Dirs.push_back(
2082                     "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
2083               else
2084                 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
2085               return Dirs;
2086             });
2087   }
2088
2089   MultilibSet DebianMipsMultilibs;
2090   {
2091     Multilib MAbiN32 =
2092         Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
2093
2094     Multilib M64 = Multilib()
2095                        .gccSuffix("/64")
2096                        .includeSuffix("/64")
2097                        .flag("+m64")
2098                        .flag("-m32")
2099                        .flag("-mabi=n32");
2100
2101     Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
2102
2103     DebianMipsMultilibs =
2104         MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
2105   }
2106
2107   // Sort candidates. Toolchain that best meets the directories tree goes first.
2108   // Then select the first toolchains matches command line flags.
2109   MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
2110   if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
2111     std::iter_swap(Candidates, Candidates + 1);
2112   for (const MultilibSet *Candidate : Candidates) {
2113     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2114       if (Candidate == &DebianMipsMultilibs)
2115         Result.BiarchSibling = Multilib();
2116       Result.Multilibs = *Candidate;
2117       return true;
2118     }
2119   }
2120   return false;
2121 }
2122
2123 static bool findMipsAndroidMultilibs(vfs::FileSystem &VFS, StringRef Path,
2124                                      const Multilib::flags_list &Flags,
2125                                      FilterNonExistent &NonExistent,
2126                                      DetectedMultilibs &Result) {
2127
2128   MultilibSet AndroidMipsMultilibs =
2129       MultilibSet()
2130           .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
2131           .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
2132           .FilterOut(NonExistent);
2133
2134   MultilibSet AndroidMipselMultilibs =
2135       MultilibSet()
2136           .Either(Multilib().flag("+march=mips32"),
2137                   Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
2138                   Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
2139           .FilterOut(NonExistent);
2140
2141   MultilibSet AndroidMips64elMultilibs =
2142       MultilibSet()
2143           .Either(
2144               Multilib().flag("+march=mips64r6"),
2145               Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
2146               Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
2147               Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
2148           .FilterOut(NonExistent);
2149
2150   MultilibSet *MS = &AndroidMipsMultilibs;
2151   if (VFS.exists(Path + "/mips-r6"))
2152     MS = &AndroidMipselMultilibs;
2153   else if (VFS.exists(Path + "/32"))
2154     MS = &AndroidMips64elMultilibs;
2155   if (MS->select(Flags, Result.SelectedMultilib)) {
2156     Result.Multilibs = *MS;
2157     return true;
2158   }
2159   return false;
2160 }
2161
2162 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
2163                                   FilterNonExistent &NonExistent,
2164                                   DetectedMultilibs &Result) {
2165   // Musl toolchain multilibs
2166   MultilibSet MuslMipsMultilibs;
2167   {
2168     auto MArchMipsR2 = makeMultilib("")
2169                            .osSuffix("/mips-r2-hard-musl")
2170                            .flag("+EB")
2171                            .flag("-EL")
2172                            .flag("+march=mips32r2");
2173
2174     auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
2175                              .flag("-EB")
2176                              .flag("+EL")
2177                              .flag("+march=mips32r2");
2178
2179     MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
2180
2181     // Specify the callback that computes the include directories.
2182     MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
2183       return std::vector<std::string>(
2184           {"/../sysroot" + M.osSuffix() + "/usr/include"});
2185     });
2186   }
2187   if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2188     Result.Multilibs = MuslMipsMultilibs;
2189     return true;
2190   }
2191   return false;
2192 }
2193
2194 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
2195                                  FilterNonExistent &NonExistent,
2196                                  DetectedMultilibs &Result) {
2197   // CodeScape MTI toolchain v1.2 and early.
2198   MultilibSet MtiMipsMultilibsV1;
2199   {
2200     auto MArchMips32 = makeMultilib("/mips32")
2201                            .flag("+m32")
2202                            .flag("-m64")
2203                            .flag("-mmicromips")
2204                            .flag("+march=mips32");
2205
2206     auto MArchMicroMips = makeMultilib("/micromips")
2207                               .flag("+m32")
2208                               .flag("-m64")
2209                               .flag("+mmicromips");
2210
2211     auto MArchMips64r2 = makeMultilib("/mips64r2")
2212                              .flag("-m32")
2213                              .flag("+m64")
2214                              .flag("+march=mips64r2");
2215
2216     auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
2217         "-march=mips64r2");
2218
2219     auto MArchDefault = makeMultilib("")
2220                             .flag("+m32")
2221                             .flag("-m64")
2222                             .flag("-mmicromips")
2223                             .flag("+march=mips32r2");
2224
2225     auto Mips16 = makeMultilib("/mips16").flag("+mips16");
2226
2227     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
2228
2229     auto MAbi64 =
2230         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
2231
2232     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
2233
2234     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2235
2236     auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
2237
2238     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
2239
2240     MtiMipsMultilibsV1 =
2241         MultilibSet()
2242             .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
2243                     MArchDefault)
2244             .Maybe(UCLibc)
2245             .Maybe(Mips16)
2246             .FilterOut("/mips64/mips16")
2247             .FilterOut("/mips64r2/mips16")
2248             .FilterOut("/micromips/mips16")
2249             .Maybe(MAbi64)
2250             .FilterOut("/micromips/64")
2251             .FilterOut("/mips32/64")
2252             .FilterOut("^/64")
2253             .FilterOut("/mips16/64")
2254             .Either(BigEndian, LittleEndian)
2255             .Maybe(SoftFloat)
2256             .Maybe(Nan2008)
2257             .FilterOut(".*sof/nan2008")
2258             .FilterOut(NonExistent)
2259             .setIncludeDirsCallback([](const Multilib &M) {
2260               std::vector<std::string> Dirs({"/include"});
2261               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
2262                 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
2263               else
2264                 Dirs.push_back("/../../../../sysroot/usr/include");
2265               return Dirs;
2266             });
2267   }
2268
2269   // CodeScape IMG toolchain starting from v1.3.
2270   MultilibSet MtiMipsMultilibsV2;
2271   {
2272     auto BeHard = makeMultilib("/mips-r2-hard")
2273                       .flag("+EB")
2274                       .flag("-msoft-float")
2275                       .flag("-mnan=2008")
2276                       .flag("-muclibc");
2277     auto BeSoft = makeMultilib("/mips-r2-soft")
2278                       .flag("+EB")
2279                       .flag("+msoft-float")
2280                       .flag("-mnan=2008");
2281     auto ElHard = makeMultilib("/mipsel-r2-hard")
2282                       .flag("+EL")
2283                       .flag("-msoft-float")
2284                       .flag("-mnan=2008")
2285                       .flag("-muclibc");
2286     auto ElSoft = makeMultilib("/mipsel-r2-soft")
2287                       .flag("+EL")
2288                       .flag("+msoft-float")
2289                       .flag("-mnan=2008")
2290                       .flag("-mmicromips");
2291     auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
2292                          .flag("+EB")
2293                          .flag("-msoft-float")
2294                          .flag("+mnan=2008")
2295                          .flag("-muclibc");
2296     auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
2297                          .flag("+EL")
2298                          .flag("-msoft-float")
2299                          .flag("+mnan=2008")
2300                          .flag("-muclibc")
2301                          .flag("-mmicromips");
2302     auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
2303                                .flag("+EB")
2304                                .flag("-msoft-float")
2305                                .flag("+mnan=2008")
2306                                .flag("+muclibc");
2307     auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
2308                                .flag("+EL")
2309                                .flag("-msoft-float")
2310                                .flag("+mnan=2008")
2311                                .flag("+muclibc");
2312     auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
2313                             .flag("+EB")
2314                             .flag("-msoft-float")
2315                             .flag("-mnan=2008")
2316                             .flag("+muclibc");
2317     auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
2318                             .flag("+EL")
2319                             .flag("-msoft-float")
2320                             .flag("-mnan=2008")
2321                             .flag("+muclibc");
2322     auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
2323                               .flag("+EL")
2324                               .flag("-msoft-float")
2325                               .flag("+mnan=2008")
2326                               .flag("+mmicromips");
2327     auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
2328                            .flag("+EL")
2329                            .flag("+msoft-float")
2330                            .flag("-mnan=2008")
2331                            .flag("+mmicromips");
2332
2333     auto O32 =
2334         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
2335     auto N32 =
2336         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
2337     auto N64 =
2338         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
2339
2340     MtiMipsMultilibsV2 =
2341         MultilibSet()
2342             .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
2343                      BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
2344                      ElHardUclibc, ElMicroHardNan, ElMicroSoft})
2345             .Either(O32, N32, N64)
2346             .FilterOut(NonExistent)
2347             .setIncludeDirsCallback([](const Multilib &M) {
2348               return std::vector<std::string>({"/../../../../sysroot" +
2349                                                M.includeSuffix() +
2350                                                "/../usr/include"});
2351             })
2352             .setFilePathsCallback([](const Multilib &M) {
2353               return std::vector<std::string>(
2354                   {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
2355             });
2356   }
2357   for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
2358     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2359       Result.Multilibs = *Candidate;
2360       return true;
2361     }
2362   }
2363   return false;
2364 }
2365
2366 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
2367                                  FilterNonExistent &NonExistent,
2368                                  DetectedMultilibs &Result) {
2369   // CodeScape IMG toolchain v1.2 and early.
2370   MultilibSet ImgMultilibsV1;
2371   {
2372     auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
2373
2374     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2375
2376     auto MAbi64 =
2377         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
2378
2379     ImgMultilibsV1 =
2380         MultilibSet()
2381             .Maybe(Mips64r6)
2382             .Maybe(MAbi64)
2383             .Maybe(LittleEndian)
2384             .FilterOut(NonExistent)
2385             .setIncludeDirsCallback([](const Multilib &M) {
2386               return std::vector<std::string>(
2387                   {"/include", "/../../../../sysroot/usr/include"});
2388             });
2389   }
2390
2391   // CodeScape IMG toolchain starting from v1.3.
2392   MultilibSet ImgMultilibsV2;
2393   {
2394     auto BeHard = makeMultilib("/mips-r6-hard")
2395                       .flag("+EB")
2396                       .flag("-msoft-float")
2397                       .flag("-mmicromips");
2398     auto BeSoft = makeMultilib("/mips-r6-soft")
2399                       .flag("+EB")
2400                       .flag("+msoft-float")
2401                       .flag("-mmicromips");
2402     auto ElHard = makeMultilib("/mipsel-r6-hard")
2403                       .flag("+EL")
2404                       .flag("-msoft-float")
2405                       .flag("-mmicromips");
2406     auto ElSoft = makeMultilib("/mipsel-r6-soft")
2407                       .flag("+EL")
2408                       .flag("+msoft-float")
2409                       .flag("-mmicromips");
2410     auto BeMicroHard = makeMultilib("/micromips-r6-hard")
2411                            .flag("+EB")
2412                            .flag("-msoft-float")
2413                            .flag("+mmicromips");
2414     auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
2415                            .flag("+EB")
2416                            .flag("+msoft-float")
2417                            .flag("+mmicromips");
2418     auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
2419                            .flag("+EL")
2420                            .flag("-msoft-float")
2421                            .flag("+mmicromips");
2422     auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
2423                            .flag("+EL")
2424                            .flag("+msoft-float")
2425                            .flag("+mmicromips");
2426
2427     auto O32 =
2428         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
2429     auto N32 =
2430         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
2431     auto N64 =
2432         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
2433
2434     ImgMultilibsV2 =
2435         MultilibSet()
2436             .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
2437                      ElMicroHard, ElMicroSoft})
2438             .Either(O32, N32, N64)
2439             .FilterOut(NonExistent)
2440             .setIncludeDirsCallback([](const Multilib &M) {
2441               return std::vector<std::string>({"/../../../../sysroot" +
2442                                                M.includeSuffix() +
2443                                                "/../usr/include"});
2444             })
2445             .setFilePathsCallback([](const Multilib &M) {
2446               return std::vector<std::string>(
2447                   {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
2448             });
2449   }
2450   for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
2451     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2452       Result.Multilibs = *Candidate;
2453       return true;
2454     }
2455   }
2456   return false;
2457 }
2458
2459 static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
2460                               StringRef Path, const ArgList &Args,
2461                               DetectedMultilibs &Result) {
2462   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
2463
2464   StringRef CPUName;
2465   StringRef ABIName;
2466   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
2467
2468   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2469
2470   Multilib::flags_list Flags;
2471   addMultilibFlag(isMips32(TargetArch), "m32", Flags);
2472   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
2473   addMultilibFlag(isMips16(Args), "mips16", Flags);
2474   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
2475   addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
2476                       CPUName == "mips32r5" || CPUName == "p5600",
2477                   "march=mips32r2", Flags);
2478   addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
2479   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
2480   addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
2481                       CPUName == "mips64r5" || CPUName == "octeon",
2482                   "march=mips64r2", Flags);
2483   addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
2484   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
2485   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
2486   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
2487                   Flags);
2488   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
2489   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
2490   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
2491   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
2492   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
2493   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
2494
2495   if (TargetTriple.isAndroid())
2496     return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
2497                                     Result);
2498
2499   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2500       TargetTriple.getOS() == llvm::Triple::Linux &&
2501       TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2502     return findMipsMuslMultilibs(Flags, NonExistent, Result);
2503
2504   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2505       TargetTriple.getOS() == llvm::Triple::Linux &&
2506       TargetTriple.getEnvironment() == llvm::Triple::GNU)
2507     return findMipsMtiMultilibs(Flags, NonExistent, Result);
2508
2509   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
2510       TargetTriple.getOS() == llvm::Triple::Linux &&
2511       TargetTriple.getEnvironment() == llvm::Triple::GNU)
2512     return findMipsImgMultilibs(Flags, NonExistent, Result);
2513
2514   if (findMipsCsMultilibs(Flags, NonExistent, Result))
2515     return true;
2516
2517   // Fallback to the regular toolchain-tree structure.
2518   Multilib Default;
2519   Result.Multilibs.push_back(Default);
2520   Result.Multilibs.FilterOut(NonExistent);
2521
2522   if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
2523     Result.BiarchSibling = Multilib();
2524     return true;
2525   }
2526
2527   return false;
2528 }
2529
2530 static void findAndroidArmMultilibs(const Driver &D,
2531                                     const llvm::Triple &TargetTriple,
2532                                     StringRef Path, const ArgList &Args,
2533                                     DetectedMultilibs &Result) {
2534   // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
2535   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
2536   Multilib ArmV7Multilib = makeMultilib("/armv7-a")
2537                                .flag("+armv7")
2538                                .flag("-thumb");
2539   Multilib ThumbMultilib = makeMultilib("/thumb")
2540                                .flag("-armv7")
2541                                .flag("+thumb");
2542   Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
2543                                .flag("+armv7")
2544                                .flag("+thumb");
2545   Multilib DefaultMultilib = makeMultilib("")
2546                                .flag("-armv7")
2547                                .flag("-thumb");
2548   MultilibSet AndroidArmMultilibs =
2549       MultilibSet()
2550           .Either(ThumbMultilib, ArmV7Multilib,
2551                   ArmV7ThumbMultilib, DefaultMultilib)
2552           .FilterOut(NonExistent);
2553
2554   Multilib::flags_list Flags;
2555   llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
2556   bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
2557   bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
2558   bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
2559   bool IsThumbMode = IsThumbArch ||
2560       Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
2561       (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::IK_THUMB);
2562   bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
2563       (llvm::ARM::parseArchVersion(Arch) == 7 ||
2564        (IsArmArch && Arch == "" && IsV7SubArch));
2565   addMultilibFlag(IsArmV7Mode, "armv7", Flags);
2566   addMultilibFlag(IsThumbMode, "thumb", Flags);
2567
2568   if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
2569     Result.Multilibs = AndroidArmMultilibs;
2570 }
2571
2572 static bool findBiarchMultilibs(const Driver &D,
2573                                 const llvm::Triple &TargetTriple,
2574                                 StringRef Path, const ArgList &Args,
2575                                 bool NeedsBiarchSuffix,
2576                                 DetectedMultilibs &Result) {
2577   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
2578   // in what would normally be GCCInstallPath and put the 64-bit
2579   // libs in a subdirectory named 64. The simple logic we follow is that
2580   // *if* there is a subdirectory of the right name with crtbegin.o in it,
2581   // we use that. If not, and if not a biarch triple alias, we look for
2582   // crtbegin.o without the subdirectory.
2583
2584   Multilib Default;
2585   Multilib Alt64 = Multilib()
2586                        .gccSuffix("/64")
2587                        .includeSuffix("/64")
2588                        .flag("-m32")
2589                        .flag("+m64")
2590                        .flag("-mx32");
2591   Multilib Alt32 = Multilib()
2592                        .gccSuffix("/32")
2593                        .includeSuffix("/32")
2594                        .flag("+m32")
2595                        .flag("-m64")
2596                        .flag("-mx32");
2597   Multilib Altx32 = Multilib()
2598                         .gccSuffix("/x32")
2599                         .includeSuffix("/x32")
2600                         .flag("-m32")
2601                         .flag("-m64")
2602                         .flag("+mx32");
2603
2604   // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
2605   FilterNonExistent NonExistent(
2606       Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
2607
2608   // Determine default multilib from: 32, 64, x32
2609   // Also handle cases such as 64 on 32, 32 on 64, etc.
2610   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2611   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
2612   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2613     Want = WANT64;
2614   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2615     Want = WANT64;
2616   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2617     Want = WANT32;
2618   else {
2619     if (TargetTriple.isArch32Bit())
2620       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2621     else if (IsX32)
2622       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2623     else
2624       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2625   }
2626
2627   if (Want == WANT32)
2628     Default.flag("+m32").flag("-m64").flag("-mx32");
2629   else if (Want == WANT64)
2630     Default.flag("-m32").flag("+m64").flag("-mx32");
2631   else if (Want == WANTX32)
2632     Default.flag("-m32").flag("-m64").flag("+mx32");
2633   else
2634     return false;
2635
2636   Result.Multilibs.push_back(Default);
2637   Result.Multilibs.push_back(Alt64);
2638   Result.Multilibs.push_back(Alt32);
2639   Result.Multilibs.push_back(Altx32);
2640
2641   Result.Multilibs.FilterOut(NonExistent);
2642
2643   Multilib::flags_list Flags;
2644   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
2645   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
2646   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
2647
2648   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
2649     return false;
2650
2651   if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
2652       Result.SelectedMultilib == Altx32)
2653     Result.BiarchSibling = Default;
2654
2655   return true;
2656 }
2657
2658 void Generic_GCC::GCCInstallationDetector::scanLibDirForGCCTripleSolaris(
2659     const llvm::Triple &TargetArch, const llvm::opt::ArgList &Args,
2660     const std::string &LibDir, StringRef CandidateTriple,
2661     bool NeedsBiarchSuffix) {
2662   // Solaris is a special case. The GCC installation is under
2663   // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/, so we
2664   // need to iterate twice.
2665   std::error_code EC;
2666   for (vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir, EC), LE;
2667        !EC && LI != LE; LI = LI.increment(EC)) {
2668     StringRef VersionText = llvm::sys::path::filename(LI->getName());
2669     GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2670
2671     if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2672       if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2673         continue; // Saw this path before; no need to look at it again.
2674     if (CandidateVersion.isOlderThan(4, 1, 1))
2675       continue;
2676     if (CandidateVersion <= Version)
2677       continue;
2678
2679     GCCInstallPath =
2680         LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str();
2681     if (!D.getVFS().exists(GCCInstallPath))
2682       continue;
2683
2684     // If we make it here there has to be at least one GCC version, let's just
2685     // use the latest one.
2686     std::error_code EEC;
2687     for (vfs::directory_iterator
2688              LLI = D.getVFS().dir_begin(GCCInstallPath, EEC),
2689              LLE;
2690          !EEC && LLI != LLE; LLI = LLI.increment(EEC)) {
2691
2692       StringRef SubVersionText = llvm::sys::path::filename(LLI->getName());
2693       GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText);
2694
2695       if (CandidateSubVersion > Version)
2696         Version = CandidateSubVersion;
2697     }
2698
2699     GCCTriple.setTriple(CandidateTriple);
2700
2701     GCCInstallPath += "/" + Version.Text;
2702     GCCParentLibPath = GCCInstallPath + "/../../../../";
2703
2704     IsValid = true;
2705   }
2706 }
2707
2708 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2709     const llvm::Triple &TargetTriple, const ArgList &Args,
2710     StringRef Path, bool NeedsBiarchSuffix) {
2711   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2712   DetectedMultilibs Detected;
2713
2714   // Android standalone toolchain could have multilibs for ARM and Thumb.
2715   // Debian mips multilibs behave more like the rest of the biarch ones,
2716   // so handle them there
2717   if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2718     // It should also work without multilibs in a simplified toolchain.
2719     findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2720   } else if (isMipsArch(TargetArch)) {
2721     if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2722       return false;
2723   } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2724                                   NeedsBiarchSuffix, Detected)) {
2725     return false;
2726   }
2727
2728   Multilibs = Detected.Multilibs;
2729   SelectedMultilib = Detected.SelectedMultilib;
2730   BiarchSibling = Detected.BiarchSibling;
2731
2732   return true;
2733 }
2734
2735 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2736     const llvm::Triple &TargetTriple, const ArgList &Args,
2737     const std::string &LibDir, StringRef CandidateTriple,
2738     bool NeedsBiarchSuffix) {
2739   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2740   // There are various different suffixes involving the triple we
2741   // check for. We also record what is necessary to walk from each back
2742   // up to the lib directory. Specifically, the number of "up" steps
2743   // in the second half of each row is 1 + the number of path separators
2744   // in the first half.
2745   const std::string LibAndInstallSuffixes[][2] = {
2746       {"/gcc/" + CandidateTriple.str(), "/../../.."},
2747
2748       // Debian puts cross-compilers in gcc-cross
2749       {"/gcc-cross/" + CandidateTriple.str(), "/../../.."},
2750
2751       {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
2752        "/../../../.."},
2753
2754       // The Freescale PPC SDK has the gcc libraries in
2755       // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
2756       {"/" + CandidateTriple.str(), "/../.."},
2757
2758       // Ubuntu has a strange mis-matched pair of triples that this happens to
2759       // match.
2760       // FIXME: It may be worthwhile to generalize this and look for a second
2761       // triple.
2762       {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}};
2763
2764   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2765     scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple,
2766                                   NeedsBiarchSuffix);
2767     return;
2768   }
2769
2770   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
2771   const unsigned NumLibSuffixes = (llvm::array_lengthof(LibAndInstallSuffixes) -
2772                                    (TargetArch != llvm::Triple::x86));
2773   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
2774     StringRef LibSuffix = LibAndInstallSuffixes[i][0];
2775     std::error_code EC;
2776     for (vfs::directory_iterator
2777              LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC),
2778              LE;
2779          !EC && LI != LE; LI = LI.increment(EC)) {
2780       StringRef VersionText = llvm::sys::path::filename(LI->getName());
2781       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2782       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2783         if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2784           continue; // Saw this path before; no need to look at it again.
2785       if (CandidateVersion.isOlderThan(4, 1, 1))
2786         continue;
2787       if (CandidateVersion <= Version)
2788         continue;
2789
2790       if (!ScanGCCForMultilibs(TargetTriple, Args, LI->getName(),
2791                                NeedsBiarchSuffix))
2792         continue;
2793
2794       Version = CandidateVersion;
2795       GCCTriple.setTriple(CandidateTriple);
2796       // FIXME: We hack together the directory name here instead of
2797       // using LI to ensure stable path separators across Windows and
2798       // Linux.
2799       GCCInstallPath =
2800           LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str();
2801       GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1];
2802       IsValid = true;
2803     }
2804   }
2805 }
2806
2807 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2808     const llvm::Triple &TargetTriple, const ArgList &Args,
2809     StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2810   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2811       D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
2812                                   CandidateTriple.str());
2813   if (File) {
2814     SmallVector<StringRef, 2> Lines;
2815     File.get()->getBuffer().split(Lines, "\n");
2816     for (StringRef Line : Lines) {
2817       // CURRENT=triple-version
2818       if (Line.consume_front("CURRENT=")) {
2819         const std::pair<StringRef, StringRef> ActiveVersion =
2820           Line.rsplit('-');
2821         // Note: Strictly speaking, we should be reading
2822         // /etc/env.d/gcc/${CURRENT} now. However, the file doesn't
2823         // contain anything new or especially useful to us.
2824         const std::string GentooPath = D.SysRoot + "/usr/lib/gcc/" +
2825                                        ActiveVersion.first.str() + "/" +
2826                                        ActiveVersion.second.str();
2827         if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2828           if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2829                                    NeedsBiarchSuffix))
2830             return false;
2831
2832           Version = GCCVersion::Parse(ActiveVersion.second);
2833           GCCInstallPath = GentooPath;
2834           GCCParentLibPath = GentooPath + "/../../..";
2835           GCCTriple.setTriple(ActiveVersion.first);
2836           IsValid = true;
2837           return true;
2838         }
2839       }
2840     }
2841   }
2842
2843   return false;
2844 }
2845
2846 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2847                          const ArgList &Args)
2848     : ToolChain(D, Triple, Args), GCCInstallation(D),
2849       CudaInstallation(D, Triple, Args) {
2850   getProgramPaths().push_back(getDriver().getInstalledDir());
2851   if (getDriver().getInstalledDir() != getDriver().Dir)
2852     getProgramPaths().push_back(getDriver().Dir);
2853 }
2854
2855 Generic_GCC::~Generic_GCC() {}
2856
2857 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2858   switch (AC) {
2859   case Action::PreprocessJobClass:
2860     if (!Preprocess)
2861       Preprocess.reset(new tools::gcc::Preprocessor(*this));
2862     return Preprocess.get();
2863   case Action::CompileJobClass:
2864     if (!Compile)
2865       Compile.reset(new tools::gcc::Compiler(*this));
2866     return Compile.get();
2867   default:
2868     return ToolChain::getTool(AC);
2869   }
2870 }
2871
2872 Tool *Generic_GCC::buildAssembler() const {
2873   return new tools::gnutools::Assembler(*this);
2874 }
2875
2876 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2877
2878 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2879   // Print the information about how we detected the GCC installation.
2880   GCCInstallation.print(OS);
2881   CudaInstallation.print(OS);
2882 }
2883
2884 bool Generic_GCC::IsUnwindTablesDefault() const {
2885   return getArch() == llvm::Triple::x86_64;
2886 }
2887
2888 bool Generic_GCC::isPICDefault() const {
2889   switch (getArch()) {
2890   case llvm::Triple::x86_64:
2891     return getTriple().isOSWindows();
2892   case llvm::Triple::ppc64:
2893   case llvm::Triple::ppc64le:
2894     return !getTriple().isOSBinFormatMachO() && !getTriple().isMacOSX();
2895   default:
2896     return false;
2897   }
2898 }
2899
2900 bool Generic_GCC::isPIEDefault() const { return false; }
2901
2902 bool Generic_GCC::isPICDefaultForced() const {
2903   return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2904 }
2905
2906 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2907   switch (getTriple().getArch()) {
2908   case llvm::Triple::x86:
2909   case llvm::Triple::x86_64:
2910   case llvm::Triple::aarch64:
2911   case llvm::Triple::aarch64_be:
2912   case llvm::Triple::arm:
2913   case llvm::Triple::armeb:
2914   case llvm::Triple::bpfel:
2915   case llvm::Triple::bpfeb:
2916   case llvm::Triple::thumb:
2917   case llvm::Triple::thumbeb:
2918   case llvm::Triple::ppc:
2919   case llvm::Triple::ppc64:
2920   case llvm::Triple::ppc64le:
2921   case llvm::Triple::systemz:
2922   case llvm::Triple::mips:
2923   case llvm::Triple::mipsel:
2924     return true;
2925   case llvm::Triple::mips64:
2926   case llvm::Triple::mips64el:
2927     // Enabled for Debian mips64/mips64el only. Other targets are unable to
2928     // distinguish N32 from N64.
2929     if (getTriple().getEnvironment() == llvm::Triple::GNUABI64)
2930       return true;
2931     return false;
2932   default:
2933     return false;
2934   }
2935 }
2936
2937 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2938                                                ArgStringList &CC1Args) const {
2939   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2940       DriverArgs.hasArg(options::OPT_nostdincxx))
2941     return;
2942
2943   switch (GetCXXStdlibType(DriverArgs)) {
2944   case ToolChain::CST_Libcxx: {
2945     std::string Path = findLibCxxIncludePath();
2946     if (!Path.empty())
2947       addSystemInclude(DriverArgs, CC1Args, Path);
2948     break;
2949   }
2950
2951   case ToolChain::CST_Libstdcxx:
2952     addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2953     break;
2954   }
2955 }
2956
2957 std::string Generic_GCC::findLibCxxIncludePath() const {
2958   // FIXME: The Linux behavior would probaby be a better approach here.
2959   return getDriver().SysRoot + "/usr/include/c++/v1";
2960 }
2961
2962 void
2963 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2964                                       llvm::opt::ArgStringList &CC1Args) const {
2965   // By default, we don't assume we know where libstdc++ might be installed.
2966   // FIXME: If we have a valid GCCInstallation, use it.
2967 }
2968
2969 /// \brief Helper to add the variant paths of a libstdc++ installation.
2970 bool Generic_GCC::addLibStdCXXIncludePaths(
2971     Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2972     StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2973     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2974   if (!getVFS().exists(Base + Suffix))
2975     return false;
2976
2977   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2978
2979   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2980   // that path exists or we have neither a GCC nor target multiarch triple, use
2981   // this vanilla search path.
2982   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2983       getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2984     addSystemInclude(DriverArgs, CC1Args,
2985                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2986   } else {
2987     // Otherwise try to use multiarch naming schemes which have normalized the
2988     // triples and put the triple before the suffix.
2989     //
2990     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2991     // the target triple, so we support that here.
2992     addSystemInclude(DriverArgs, CC1Args,
2993                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2994     addSystemInclude(DriverArgs, CC1Args,
2995                      Base + "/" + TargetMultiarchTriple + Suffix);
2996   }
2997
2998   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2999   return true;
3000 }
3001
3002 llvm::opt::DerivedArgList *
3003 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3004                            Action::OffloadKind DeviceOffloadKind) const {
3005
3006   // If this tool chain is used for an OpenMP offloading device we have to make
3007   // sure we always generate a shared library regardless of the commands the
3008   // user passed to the host. This is required because the runtime library
3009   // is required to load the device image dynamically at run time.
3010   if (DeviceOffloadKind == Action::OFK_OpenMP) {
3011     DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3012     const OptTable &Opts = getDriver().getOpts();
3013
3014     // Request the shared library. Given that these options are decided
3015     // implicitly, they do not refer to any base argument.
3016     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3017     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3018
3019     // Filter all the arguments we don't care passing to the offloading
3020     // toolchain as they can mess up with the creation of a shared library.
3021     for (auto *A : Args) {
3022       switch ((options::ID)A->getOption().getID()) {
3023       default:
3024         DAL->append(A);
3025         break;
3026       case options::OPT_shared:
3027       case options::OPT_dynamic:
3028       case options::OPT_static:
3029       case options::OPT_fPIC:
3030       case options::OPT_fno_PIC:
3031       case options::OPT_fpic:
3032       case options::OPT_fno_pic:
3033       case options::OPT_fPIE:
3034       case options::OPT_fno_PIE:
3035       case options::OPT_fpie:
3036       case options::OPT_fno_pie:
3037         break;
3038       }
3039     }
3040     return DAL;
3041   }
3042   return nullptr;
3043 }
3044
3045 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3046                                         ArgStringList &CC1Args) const {
3047   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
3048   bool UseInitArrayDefault =
3049       getTriple().getArch() == llvm::Triple::aarch64 ||
3050       getTriple().getArch() == llvm::Triple::aarch64_be ||
3051       (getTriple().getOS() == llvm::Triple::Linux &&
3052        (!V.isOlderThan(4, 7, 0) || getTriple().isAndroid())) ||
3053       getTriple().getOS() == llvm::Triple::NaCl ||
3054       (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
3055        !getTriple().hasEnvironment());
3056
3057   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
3058                          options::OPT_fno_use_init_array, UseInitArrayDefault))
3059     CC1Args.push_back("-fuse-init-array");
3060 }
3061
3062 /// Mips Toolchain
3063 MipsLLVMToolChain::MipsLLVMToolChain(const Driver &D,
3064                                      const llvm::Triple &Triple,
3065                                      const ArgList &Args)
3066     : Linux(D, Triple, Args) {
3067   // Select the correct multilib according to the given arguments.
3068   DetectedMultilibs Result;
3069   findMIPSMultilibs(D, Triple, "", Args, Result);
3070   Multilibs = Result.Multilibs;
3071   SelectedMultilib = Result.SelectedMultilib;
3072
3073   // Find out the library suffix based on the ABI.
3074   LibSuffix = tools::mips::getMipsABILibSuffix(Args, Triple);
3075   getFilePaths().clear();
3076   getFilePaths().push_back(computeSysRoot() + "/usr/lib" + LibSuffix);
3077 }
3078
3079 void MipsLLVMToolChain::AddClangSystemIncludeArgs(
3080     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
3081   if (DriverArgs.hasArg(options::OPT_nostdinc))
3082     return;
3083
3084   const Driver &D = getDriver();
3085
3086   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3087     SmallString<128> P(D.ResourceDir);
3088     llvm::sys::path::append(P, "include");
3089     addSystemInclude(DriverArgs, CC1Args, P);
3090   }
3091
3092   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3093     return;
3094
3095   const auto &Callback = Multilibs.includeDirsCallback();
3096   if (Callback) {
3097     for (const auto &Path : Callback(SelectedMultilib))
3098       addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3099                                       D.getInstalledDir() + Path);
3100   }
3101 }
3102
3103 Tool *MipsLLVMToolChain::buildLinker() const {
3104   return new tools::gnutools::Linker(*this);
3105 }
3106
3107 std::string MipsLLVMToolChain::computeSysRoot() const {
3108   if (!getDriver().SysRoot.empty())
3109     return getDriver().SysRoot + SelectedMultilib.osSuffix();
3110
3111   const std::string InstalledDir(getDriver().getInstalledDir());
3112   std::string SysRootPath =
3113       InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix();
3114   if (llvm::sys::fs::exists(SysRootPath))
3115     return SysRootPath;
3116
3117   return std::string();
3118 }
3119
3120 ToolChain::CXXStdlibType
3121 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const {
3122   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
3123   if (A) {
3124     StringRef Value = A->getValue();
3125     if (Value != "libc++")
3126       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
3127           << A->getAsString(Args);
3128   }
3129
3130   return ToolChain::CST_Libcxx;
3131 }
3132
3133 std::string MipsLLVMToolChain::findLibCxxIncludePath() const {
3134   if (const auto &Callback = Multilibs.includeDirsCallback()) {
3135     for (std::string Path : Callback(SelectedMultilib)) {
3136       Path = getDriver().getInstalledDir() + Path + "/c++/v1";
3137       if (llvm::sys::fs::exists(Path)) {
3138         return Path;
3139       }
3140     }
3141   }
3142   return "";
3143 }
3144
3145 void MipsLLVMToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
3146                                             ArgStringList &CmdArgs) const {
3147   assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) &&
3148          "Only -lc++ (aka libxx) is suported in this toolchain.");
3149
3150   CmdArgs.push_back("-lc++");
3151   CmdArgs.push_back("-lc++abi");
3152   CmdArgs.push_back("-lunwind");
3153 }
3154
3155 std::string MipsLLVMToolChain::getCompilerRT(const ArgList &Args,
3156                                              StringRef Component,
3157                                              bool Shared) const {
3158   SmallString<128> Path(getDriver().ResourceDir);
3159   llvm::sys::path::append(Path, SelectedMultilib.osSuffix(), "lib" + LibSuffix,
3160                           getOS());
3161   llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" +
3162                                       "mips" + (Shared ? ".so" : ".a")));
3163   return Path.str();
3164 }
3165
3166 /// Hexagon Toolchain
3167
3168 std::string HexagonToolChain::getHexagonTargetDir(
3169       const std::string &InstalledDir,
3170       const SmallVectorImpl<std::string> &PrefixDirs) const {
3171   std::string InstallRelDir;
3172   const Driver &D = getDriver();
3173
3174   // Locate the rest of the toolchain ...
3175   for (auto &I : PrefixDirs)
3176     if (D.getVFS().exists(I))
3177       return I;
3178
3179   if (getVFS().exists(InstallRelDir = InstalledDir + "/../target"))
3180     return InstallRelDir;
3181
3182   return InstalledDir;
3183 }
3184
3185 Optional<unsigned> HexagonToolChain::getSmallDataThreshold(
3186       const ArgList &Args) {
3187   StringRef Gn = "";
3188   if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
3189                                options::OPT_msmall_data_threshold_EQ)) {
3190     Gn = A->getValue();
3191   } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
3192                              options::OPT_fPIC)) {
3193     Gn = "0";
3194   }
3195
3196   unsigned G;
3197   if (!Gn.getAsInteger(10, G))
3198     return G;
3199
3200   return None;
3201 }
3202
3203 void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args,
3204       ToolChain::path_list &LibPaths) const {
3205   const Driver &D = getDriver();
3206
3207   //----------------------------------------------------------------------------
3208   // -L Args
3209   //----------------------------------------------------------------------------
3210   for (Arg *A : Args.filtered(options::OPT_L))
3211     for (const char *Value : A->getValues())
3212       LibPaths.push_back(Value);
3213
3214   //----------------------------------------------------------------------------
3215   // Other standard paths
3216   //----------------------------------------------------------------------------
3217   std::vector<std::string> RootDirs;
3218   std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(),
3219             std::back_inserter(RootDirs));
3220
3221   std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3222                                               D.PrefixDirs);
3223   if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end())
3224     RootDirs.push_back(TargetDir);
3225
3226   bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC);
3227   // Assume G0 with -shared.
3228   bool HasG0 = Args.hasArg(options::OPT_shared);
3229   if (auto G = getSmallDataThreshold(Args))
3230     HasG0 = G.getValue() == 0;
3231
3232   const std::string CpuVer = GetTargetCPUVersion(Args).str();
3233   for (auto &Dir : RootDirs) {
3234     std::string LibDir = Dir + "/hexagon/lib";
3235     std::string LibDirCpu = LibDir + '/' + CpuVer;
3236     if (HasG0) {
3237       if (HasPIC)
3238         LibPaths.push_back(LibDirCpu + "/G0/pic");
3239       LibPaths.push_back(LibDirCpu + "/G0");
3240     }
3241     LibPaths.push_back(LibDirCpu);
3242     LibPaths.push_back(LibDir);
3243   }
3244 }
3245
3246 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
3247                                    const llvm::opt::ArgList &Args)
3248     : Linux(D, Triple, Args) {
3249   const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3250                                                     D.PrefixDirs);
3251
3252   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
3253   // program paths
3254   const std::string BinDir(TargetDir + "/bin");
3255   if (D.getVFS().exists(BinDir))
3256     getProgramPaths().push_back(BinDir);
3257
3258   ToolChain::path_list &LibPaths = getFilePaths();
3259
3260   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
3261   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
3262   // support 'linux' we'll need to fix this up
3263   LibPaths.clear();
3264   getHexagonLibraryPaths(Args, LibPaths);
3265 }
3266
3267 HexagonToolChain::~HexagonToolChain() {}
3268
3269 Tool *HexagonToolChain::buildAssembler() const {
3270   return new tools::hexagon::Assembler(*this);
3271 }
3272
3273 Tool *HexagonToolChain::buildLinker() const {
3274   return new tools::hexagon::Linker(*this);
3275 }
3276
3277 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3278                                                  ArgStringList &CC1Args) const {
3279   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3280       DriverArgs.hasArg(options::OPT_nostdlibinc))
3281     return;
3282
3283   const Driver &D = getDriver();
3284   std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3285                                               D.PrefixDirs);
3286   addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include");
3287 }
3288
3289
3290 void HexagonToolChain::addLibStdCxxIncludePaths(
3291     const llvm::opt::ArgList &DriverArgs,
3292     llvm::opt::ArgStringList &CC1Args) const {
3293   const Driver &D = getDriver();
3294   std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs);
3295   addLibStdCXXIncludePaths(TargetDir, "/hexagon/include/c++", "", "", "", "",
3296                            DriverArgs, CC1Args);
3297 }
3298
3299 ToolChain::CXXStdlibType
3300 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
3301   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
3302   if (!A)
3303     return ToolChain::CST_Libstdcxx;
3304
3305   StringRef Value = A->getValue();
3306   if (Value != "libstdc++")
3307     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3308
3309   return ToolChain::CST_Libstdcxx;
3310 }
3311
3312 //
3313 // Returns the default CPU for Hexagon. This is the default compilation target
3314 // if no Hexagon processor is selected at the command-line.
3315 //
3316 const StringRef HexagonToolChain::GetDefaultCPU() {
3317   return "hexagonv60";
3318 }
3319
3320 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
3321   Arg *CpuArg = nullptr;
3322   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ, options::OPT_march_EQ))
3323     CpuArg = A;
3324
3325   StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
3326   if (CPU.startswith("hexagon"))
3327     return CPU.substr(sizeof("hexagon") - 1);
3328   return CPU;
3329 }
3330 // End Hexagon
3331
3332 /// AMDGPU Toolchain
3333 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
3334                                  const ArgList &Args)
3335   : Generic_ELF(D, Triple, Args) { }
3336
3337 Tool *AMDGPUToolChain::buildLinker() const {
3338   return new tools::amdgpu::Linker(*this);
3339 }
3340 // End AMDGPU
3341
3342 /// NaCl Toolchain
3343 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple,
3344                              const ArgList &Args)
3345     : Generic_ELF(D, Triple, Args) {
3346
3347   // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
3348   // default paths, and must instead only use the paths provided
3349   // with this toolchain based on architecture.
3350   path_list &file_paths = getFilePaths();
3351   path_list &prog_paths = getProgramPaths();
3352
3353   file_paths.clear();
3354   prog_paths.clear();
3355
3356   // Path for library files (libc.a, ...)
3357   std::string FilePath(getDriver().Dir + "/../");
3358
3359   // Path for tools (clang, ld, etc..)
3360   std::string ProgPath(getDriver().Dir + "/../");
3361
3362   // Path for toolchain libraries (libgcc.a, ...)
3363   std::string ToolPath(getDriver().ResourceDir + "/lib/");
3364
3365   switch (Triple.getArch()) {
3366   case llvm::Triple::x86:
3367     file_paths.push_back(FilePath + "x86_64-nacl/lib32");
3368     file_paths.push_back(FilePath + "i686-nacl/usr/lib");
3369     prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
3370     file_paths.push_back(ToolPath + "i686-nacl");
3371     break;
3372   case llvm::Triple::x86_64:
3373     file_paths.push_back(FilePath + "x86_64-nacl/lib");
3374     file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
3375     prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
3376     file_paths.push_back(ToolPath + "x86_64-nacl");
3377     break;
3378   case llvm::Triple::arm:
3379     file_paths.push_back(FilePath + "arm-nacl/lib");
3380     file_paths.push_back(FilePath + "arm-nacl/usr/lib");
3381     prog_paths.push_back(ProgPath + "arm-nacl/bin");
3382     file_paths.push_back(ToolPath + "arm-nacl");
3383     break;
3384   case llvm::Triple::mipsel:
3385     file_paths.push_back(FilePath + "mipsel-nacl/lib");
3386     file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
3387     prog_paths.push_back(ProgPath + "bin");
3388     file_paths.push_back(ToolPath + "mipsel-nacl");
3389     break;
3390   default:
3391     break;
3392   }
3393
3394   NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
3395 }
3396
3397 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3398                                               ArgStringList &CC1Args) const {
3399   const Driver &D = getDriver();
3400   if (DriverArgs.hasArg(options::OPT_nostdinc))
3401     return;
3402
3403   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3404     SmallString<128> P(D.ResourceDir);
3405     llvm::sys::path::append(P, "include");
3406     addSystemInclude(DriverArgs, CC1Args, P.str());
3407   }
3408
3409   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3410     return;
3411
3412   SmallString<128> P(D.Dir + "/../");
3413   switch (getTriple().getArch()) {
3414   case llvm::Triple::x86:
3415     // x86 is special because multilib style uses x86_64-nacl/include for libc
3416     // headers but the SDK wants i686-nacl/usr/include. The other architectures
3417     // have the same substring.
3418     llvm::sys::path::append(P, "i686-nacl/usr/include");
3419     addSystemInclude(DriverArgs, CC1Args, P.str());
3420     llvm::sys::path::remove_filename(P);
3421     llvm::sys::path::remove_filename(P);
3422     llvm::sys::path::remove_filename(P);
3423     llvm::sys::path::append(P, "x86_64-nacl/include");
3424     addSystemInclude(DriverArgs, CC1Args, P.str());
3425     return;
3426   case llvm::Triple::arm:
3427     llvm::sys::path::append(P, "arm-nacl/usr/include");
3428     break;
3429   case llvm::Triple::x86_64:
3430     llvm::sys::path::append(P, "x86_64-nacl/usr/include");
3431     break;
3432   case llvm::Triple::mipsel:
3433     llvm::sys::path::append(P, "mipsel-nacl/usr/include");
3434     break;
3435   default:
3436     return;
3437   }
3438
3439   addSystemInclude(DriverArgs, CC1Args, P.str());
3440   llvm::sys::path::remove_filename(P);
3441   llvm::sys::path::remove_filename(P);
3442   llvm::sys::path::append(P, "include");
3443   addSystemInclude(DriverArgs, CC1Args, P.str());
3444 }
3445
3446 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
3447                                         ArgStringList &CmdArgs) const {
3448   // Check for -stdlib= flags. We only support libc++ but this consumes the arg
3449   // if the value is libc++, and emits an error for other values.
3450   GetCXXStdlibType(Args);
3451   CmdArgs.push_back("-lc++");
3452 }
3453
3454 std::string NaClToolChain::findLibCxxIncludePath() const {
3455   const Driver &D = getDriver();
3456
3457   SmallString<128> P(D.Dir + "/../");
3458   switch (getTriple().getArch()) {
3459   case llvm::Triple::arm:
3460     llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
3461     return P.str();
3462   case llvm::Triple::x86:
3463     llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
3464     return P.str();
3465   case llvm::Triple::x86_64:
3466     llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
3467     return P.str();
3468   case llvm::Triple::mipsel:
3469     llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
3470     return P.str();
3471   default:
3472     return "";
3473   }
3474 }
3475
3476 ToolChain::CXXStdlibType
3477 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const {
3478   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3479     StringRef Value = A->getValue();
3480     if (Value == "libc++")
3481       return ToolChain::CST_Libcxx;
3482     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3483   }
3484
3485   return ToolChain::CST_Libcxx;
3486 }
3487
3488 std::string
3489 NaClToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
3490                                            types::ID InputType) const {
3491   llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
3492   if (TheTriple.getArch() == llvm::Triple::arm &&
3493       TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
3494     TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
3495   return TheTriple.getTriple();
3496 }
3497
3498 Tool *NaClToolChain::buildLinker() const {
3499   return new tools::nacltools::Linker(*this);
3500 }
3501
3502 Tool *NaClToolChain::buildAssembler() const {
3503   if (getTriple().getArch() == llvm::Triple::arm)
3504     return new tools::nacltools::AssemblerARM(*this);
3505   return new tools::gnutools::Assembler(*this);
3506 }
3507 // End NaCl
3508
3509 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
3510 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
3511 /// Currently does not support anything else but compilation.
3512
3513 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
3514                            const ArgList &Args)
3515     : ToolChain(D, Triple, Args) {
3516   // Path mangling to find libexec
3517   std::string Path(getDriver().Dir);
3518
3519   Path += "/../libexec";
3520   getProgramPaths().push_back(Path);
3521 }
3522
3523 TCEToolChain::~TCEToolChain() {}
3524
3525 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
3526
3527 bool TCEToolChain::isPICDefault() const { return false; }
3528
3529 bool TCEToolChain::isPIEDefault() const { return false; }
3530
3531 bool TCEToolChain::isPICDefaultForced() const { return false; }
3532
3533 TCELEToolChain::TCELEToolChain(const Driver &D, const llvm::Triple& Triple,
3534                                const ArgList &Args)
3535   : TCEToolChain(D, Triple, Args) {
3536 }
3537
3538 TCELEToolChain::~TCELEToolChain() {}
3539
3540 // CloudABI - CloudABI tool chain which can call ld(1) directly.
3541
3542 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
3543                    const ArgList &Args)
3544     : Generic_ELF(D, Triple, Args) {
3545   SmallString<128> P(getDriver().Dir);
3546   llvm::sys::path::append(P, "..", getTriple().str(), "lib");
3547   getFilePaths().push_back(P.str());
3548 }
3549
3550 std::string CloudABI::findLibCxxIncludePath() const {
3551   SmallString<128> P(getDriver().Dir);
3552   llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
3553   return P.str();
3554 }
3555
3556 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
3557                                    ArgStringList &CmdArgs) const {
3558   CmdArgs.push_back("-lc++");
3559   CmdArgs.push_back("-lc++abi");
3560   CmdArgs.push_back("-lunwind");
3561 }
3562
3563 Tool *CloudABI::buildLinker() const {
3564   return new tools::cloudabi::Linker(*this);
3565 }
3566
3567 bool CloudABI::isPIEDefault() const {
3568   // Only enable PIE on architectures that support PC-relative
3569   // addressing. PC-relative addressing is required, as the process
3570   // startup code must be able to relocate itself.
3571   switch (getTriple().getArch()) {
3572   case llvm::Triple::aarch64:
3573   case llvm::Triple::x86_64:
3574     return true;
3575   default:
3576     return false;
3577   }
3578 }
3579
3580 SanitizerMask CloudABI::getSupportedSanitizers() const {
3581   SanitizerMask Res = ToolChain::getSupportedSanitizers();
3582   Res |= SanitizerKind::SafeStack;
3583   return Res;
3584 }
3585
3586 SanitizerMask CloudABI::getDefaultSanitizers() const {
3587   return SanitizerKind::SafeStack;
3588 }
3589
3590 /// Haiku - Haiku tool chain which can call as(1) and ld(1) directly.
3591
3592 Haiku::Haiku(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
3593   : Generic_ELF(D, Triple, Args) {
3594
3595 }
3596
3597 std::string Haiku::findLibCxxIncludePath() const {
3598   return getDriver().SysRoot + "/system/develop/headers/c++/v1";
3599 }
3600
3601 void Haiku::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3602                                      llvm::opt::ArgStringList &CC1Args) const {
3603   addLibStdCXXIncludePaths(getDriver().SysRoot, "/system/develop/headers/c++",
3604                            getTriple().str(), "", "", "", DriverArgs, CC1Args);
3605 }
3606
3607 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
3608
3609 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
3610                  const ArgList &Args)
3611     : Generic_ELF(D, Triple, Args) {
3612   getFilePaths().push_back(getDriver().Dir + "/../lib");
3613   getFilePaths().push_back("/usr/lib");
3614 }
3615
3616 Tool *OpenBSD::buildAssembler() const {
3617   return new tools::openbsd::Assembler(*this);
3618 }
3619
3620 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
3621
3622 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
3623
3624 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3625     : Generic_ELF(D, Triple, Args) {
3626   getFilePaths().push_back(getDriver().Dir + "/../lib");
3627   getFilePaths().push_back("/usr/lib");
3628 }
3629
3630 Tool *Bitrig::buildAssembler() const {
3631   return new tools::bitrig::Assembler(*this);
3632 }
3633
3634 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
3635
3636 ToolChain::CXXStdlibType Bitrig::GetDefaultCXXStdlibType() const {
3637   return ToolChain::CST_Libcxx;
3638 }
3639
3640 void Bitrig::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3641                                       llvm::opt::ArgStringList &CC1Args) const {
3642   std::string Triple = getTriple().str();
3643   if (StringRef(Triple).startswith("amd64"))
3644     Triple = "x86_64" + Triple.substr(5);
3645   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/c++/stdc++",
3646                            Triple, "", "", "", DriverArgs, CC1Args);
3647 }
3648
3649 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
3650                                  ArgStringList &CmdArgs) const {
3651   switch (GetCXXStdlibType(Args)) {
3652   case ToolChain::CST_Libcxx:
3653     CmdArgs.push_back("-lc++");
3654     CmdArgs.push_back("-lc++abi");
3655     CmdArgs.push_back("-lpthread");
3656     break;
3657   case ToolChain::CST_Libstdcxx:
3658     CmdArgs.push_back("-lstdc++");
3659     break;
3660   }
3661 }
3662
3663 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
3664
3665 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
3666                  const ArgList &Args)
3667     : Generic_ELF(D, Triple, Args) {
3668
3669   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
3670   // back to '/usr/lib' if it doesn't exist.
3671   if ((Triple.getArch() == llvm::Triple::x86 ||
3672        Triple.getArch() == llvm::Triple::ppc) &&
3673       D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
3674     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
3675   else
3676     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
3677 }
3678
3679 ToolChain::CXXStdlibType FreeBSD::GetDefaultCXXStdlibType() const {
3680   if (getTriple().getOSMajorVersion() >= 10)
3681     return ToolChain::CST_Libcxx;
3682   return ToolChain::CST_Libstdcxx;
3683 }
3684
3685 void FreeBSD::addLibStdCxxIncludePaths(
3686     const llvm::opt::ArgList &DriverArgs,
3687     llvm::opt::ArgStringList &CC1Args) const {
3688   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/c++/4.2", "", "",
3689                            "", "", DriverArgs, CC1Args);
3690 }
3691
3692 void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
3693                                   ArgStringList &CmdArgs) const {
3694   CXXStdlibType Type = GetCXXStdlibType(Args);
3695   bool Profiling = Args.hasArg(options::OPT_pg);
3696
3697   switch (Type) {
3698   case ToolChain::CST_Libcxx:
3699     CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
3700     break;
3701
3702   case ToolChain::CST_Libstdcxx:
3703     CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++");
3704     break;
3705   }
3706 }
3707
3708 Tool *FreeBSD::buildAssembler() const {
3709   return new tools::freebsd::Assembler(*this);
3710 }
3711
3712 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
3713
3714 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const {
3715   // FreeBSD uses SjLj exceptions on ARM oabi.
3716   switch (getTriple().getEnvironment()) {
3717   case llvm::Triple::GNUEABIHF:
3718   case llvm::Triple::GNUEABI:
3719   case llvm::Triple::EABI:
3720     return false;
3721
3722   default:
3723     return (getTriple().getArch() == llvm::Triple::arm ||
3724             getTriple().getArch() == llvm::Triple::thumb);
3725   }
3726 }
3727
3728 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
3729
3730 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3731
3732 SanitizerMask FreeBSD::getSupportedSanitizers() const {
3733   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3734   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3735   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3736                         getTriple().getArch() == llvm::Triple::mips64el;
3737   SanitizerMask Res = ToolChain::getSupportedSanitizers();
3738   Res |= SanitizerKind::Address;
3739   Res |= SanitizerKind::Vptr;
3740   if (IsX86_64 || IsMIPS64) {
3741     Res |= SanitizerKind::Leak;
3742     Res |= SanitizerKind::Thread;
3743   }
3744   if (IsX86 || IsX86_64) {
3745     Res |= SanitizerKind::SafeStack;
3746   }
3747   return Res;
3748 }
3749
3750 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
3751
3752 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3753     : Generic_ELF(D, Triple, Args) {
3754   if (getDriver().UseStdLib) {
3755     // When targeting a 32-bit platform, try the special directory used on
3756     // 64-bit hosts, and only fall back to the main library directory if that
3757     // doesn't work.
3758     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
3759     // what all logic is needed to emulate the '=' prefix here.
3760     switch (Triple.getArch()) {
3761     case llvm::Triple::x86:
3762       getFilePaths().push_back("=/usr/lib/i386");
3763       break;
3764     case llvm::Triple::arm:
3765     case llvm::Triple::armeb:
3766     case llvm::Triple::thumb:
3767     case llvm::Triple::thumbeb:
3768       switch (Triple.getEnvironment()) {
3769       case llvm::Triple::EABI:
3770       case llvm::Triple::GNUEABI:
3771         getFilePaths().push_back("=/usr/lib/eabi");
3772         break;
3773       case llvm::Triple::EABIHF:
3774       case llvm::Triple::GNUEABIHF:
3775         getFilePaths().push_back("=/usr/lib/eabihf");
3776         break;
3777       default:
3778         getFilePaths().push_back("=/usr/lib/oabi");
3779         break;
3780       }
3781       break;
3782     case llvm::Triple::mips64:
3783     case llvm::Triple::mips64el:
3784       if (tools::mips::hasMipsAbiArg(Args, "o32"))
3785         getFilePaths().push_back("=/usr/lib/o32");
3786       else if (tools::mips::hasMipsAbiArg(Args, "64"))
3787         getFilePaths().push_back("=/usr/lib/64");
3788       break;
3789     case llvm::Triple::ppc:
3790       getFilePaths().push_back("=/usr/lib/powerpc");
3791       break;
3792     case llvm::Triple::sparc:
3793       getFilePaths().push_back("=/usr/lib/sparc");
3794       break;
3795     default:
3796       break;
3797     }
3798
3799     getFilePaths().push_back("=/usr/lib");
3800   }
3801 }
3802
3803 Tool *NetBSD::buildAssembler() const {
3804   return new tools::netbsd::Assembler(*this);
3805 }
3806
3807 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
3808
3809 ToolChain::CXXStdlibType NetBSD::GetDefaultCXXStdlibType() const {
3810   unsigned Major, Minor, Micro;
3811   getTriple().getOSVersion(Major, Minor, Micro);
3812   if (Major >= 7 || Major == 0) {
3813     switch (getArch()) {
3814     case llvm::Triple::aarch64:
3815     case llvm::Triple::aarch64_be:
3816     case llvm::Triple::arm:
3817     case llvm::Triple::armeb:
3818     case llvm::Triple::thumb:
3819     case llvm::Triple::thumbeb:
3820     case llvm::Triple::ppc:
3821     case llvm::Triple::ppc64:
3822     case llvm::Triple::ppc64le:
3823     case llvm::Triple::sparc:
3824     case llvm::Triple::sparcv9:
3825     case llvm::Triple::x86:
3826     case llvm::Triple::x86_64:
3827       return ToolChain::CST_Libcxx;
3828     default:
3829       break;
3830     }
3831   }
3832   return ToolChain::CST_Libstdcxx;
3833 }
3834
3835 std::string NetBSD::findLibCxxIncludePath() const {
3836   return getDriver().SysRoot + "/usr/include/c++/";
3837 }
3838
3839 void NetBSD::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3840                                       llvm::opt::ArgStringList &CC1Args) const {
3841   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/g++", "", "", "",
3842                            "", DriverArgs, CC1Args);
3843 }
3844
3845 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
3846
3847 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3848     : Generic_ELF(D, Triple, Args) {
3849   getFilePaths().push_back(getDriver().Dir + "/../lib");
3850   getFilePaths().push_back("/usr/lib");
3851 }
3852
3853 Tool *Minix::buildAssembler() const {
3854   return new tools::minix::Assembler(*this);
3855 }
3856
3857 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
3858
3859 static void addPathIfExists(const Driver &D, const Twine &Path,
3860                             ToolChain::path_list &Paths) {
3861   if (D.getVFS().exists(Path))
3862     Paths.push_back(Path.str());
3863 }
3864
3865 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
3866
3867 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
3868                  const ArgList &Args)
3869     : Generic_GCC(D, Triple, Args) {
3870
3871   GCCInstallation.init(Triple, Args);
3872
3873   path_list &Paths = getFilePaths();
3874   if (GCCInstallation.isValid())
3875     addPathIfExists(D, GCCInstallation.getInstallPath(), Paths);
3876
3877   addPathIfExists(D, getDriver().getInstalledDir(), Paths);
3878   if (getDriver().getInstalledDir() != getDriver().Dir)
3879     addPathIfExists(D, getDriver().Dir, Paths);
3880
3881   addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
3882
3883   std::string LibPath = "/usr/lib/";
3884   switch (Triple.getArch()) {
3885   case llvm::Triple::x86:
3886   case llvm::Triple::sparc:
3887     break;
3888   case llvm::Triple::x86_64:
3889     LibPath += "amd64/";
3890     break;
3891   case llvm::Triple::sparcv9:
3892     LibPath += "sparcv9/";
3893     break;
3894   default:
3895     llvm_unreachable("Unsupported architecture");
3896   }
3897
3898   addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
3899 }
3900
3901 Tool *Solaris::buildAssembler() const {
3902   return new tools::solaris::Assembler(*this);
3903 }
3904
3905 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
3906
3907 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3908                                            ArgStringList &CC1Args) const {
3909   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3910       DriverArgs.hasArg(options::OPT_nostdincxx))
3911     return;
3912
3913   // Include the support directory for things like xlocale and fudged system
3914   // headers.
3915   // FIXME: This is a weird mix of libc++ and libstdc++. We should also be
3916   // checking the value of -stdlib= here and adding the includes for libc++
3917   // rather than libstdc++ if it's requested.
3918   addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
3919
3920   if (GCCInstallation.isValid()) {
3921     GCCVersion Version = GCCInstallation.getVersion();
3922     addSystemInclude(DriverArgs, CC1Args,
3923                      getDriver().SysRoot + "/usr/gcc/" +
3924                      Version.MajorStr + "." +
3925                      Version.MinorStr +
3926                      "/include/c++/" + Version.Text);
3927     addSystemInclude(DriverArgs, CC1Args,
3928                      getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
3929                      "." + Version.MinorStr + "/include/c++/" +
3930                      Version.Text + "/" +
3931                      GCCInstallation.getTriple().str());
3932   }
3933 }
3934
3935 /// \brief Get our best guess at the multiarch triple for a target.
3936 ///
3937 /// Debian-based systems are starting to use a multiarch setup where they use
3938 /// a target-triple directory in the library and header search paths.
3939 /// Unfortunately, this triple does not align with the vanilla target triple,
3940 /// so we provide a rough mapping here.
3941 static std::string getMultiarchTriple(const Driver &D,
3942                                       const llvm::Triple &TargetTriple,
3943                                       StringRef SysRoot) {
3944   llvm::Triple::EnvironmentType TargetEnvironment =
3945       TargetTriple.getEnvironment();
3946
3947   // For most architectures, just use whatever we have rather than trying to be
3948   // clever.
3949   switch (TargetTriple.getArch()) {
3950   default:
3951     break;
3952
3953   // We use the existence of '/lib/<triple>' as a directory to detect some
3954   // common linux triples that don't quite match the Clang triple for both
3955   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3956   // regardless of what the actual target triple is.
3957   case llvm::Triple::arm:
3958   case llvm::Triple::thumb:
3959     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3960       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3961         return "arm-linux-gnueabihf";
3962     } else {
3963       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
3964         return "arm-linux-gnueabi";
3965     }
3966     break;
3967   case llvm::Triple::armeb:
3968   case llvm::Triple::thumbeb:
3969     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3970       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3971         return "armeb-linux-gnueabihf";
3972     } else {
3973       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3974         return "armeb-linux-gnueabi";
3975     }
3976     break;
3977   case llvm::Triple::x86:
3978     if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
3979       return "i386-linux-gnu";
3980     break;
3981   case llvm::Triple::x86_64:
3982     // We don't want this for x32, otherwise it will match x86_64 libs
3983     if (TargetEnvironment != llvm::Triple::GNUX32 &&
3984         D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
3985       return "x86_64-linux-gnu";
3986     break;
3987   case llvm::Triple::aarch64:
3988     if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
3989       return "aarch64-linux-gnu";
3990     break;
3991   case llvm::Triple::aarch64_be:
3992     if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3993       return "aarch64_be-linux-gnu";
3994     break;
3995   case llvm::Triple::mips:
3996     if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
3997       return "mips-linux-gnu";
3998     break;
3999   case llvm::Triple::mipsel:
4000     if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
4001       return "mipsel-linux-gnu";
4002     break;
4003   case llvm::Triple::mips64:
4004     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
4005       return "mips64-linux-gnu";
4006     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
4007       return "mips64-linux-gnuabi64";
4008     break;
4009   case llvm::Triple::mips64el:
4010     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
4011       return "mips64el-linux-gnu";
4012     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
4013       return "mips64el-linux-gnuabi64";
4014     break;
4015   case llvm::Triple::ppc:
4016     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
4017       return "powerpc-linux-gnuspe";
4018     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
4019       return "powerpc-linux-gnu";
4020     break;
4021   case llvm::Triple::ppc64:
4022     if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
4023       return "powerpc64-linux-gnu";
4024     break;
4025   case llvm::Triple::ppc64le:
4026     if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
4027       return "powerpc64le-linux-gnu";
4028     break;
4029   case llvm::Triple::sparc:
4030     if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
4031       return "sparc-linux-gnu";
4032     break;
4033   case llvm::Triple::sparcv9:
4034     if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
4035       return "sparc64-linux-gnu";
4036     break;
4037   case llvm::Triple::systemz:
4038     if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
4039       return "s390x-linux-gnu";
4040     break;
4041   }
4042   return TargetTriple.str();
4043 }
4044
4045 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
4046   if (isMipsArch(Triple.getArch())) {
4047     if (Triple.isAndroid()) {
4048       StringRef CPUName;
4049       StringRef ABIName;
4050       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4051       if (CPUName == "mips32r6")
4052         return "libr6";
4053       if (CPUName == "mips32r2")
4054         return "libr2";
4055     }
4056     // lib32 directory has a special meaning on MIPS targets.
4057     // It contains N32 ABI binaries. Use this folder if produce
4058     // code for N32 ABI only.
4059     if (tools::mips::hasMipsAbiArg(Args, "n32"))
4060       return "lib32";
4061     return Triple.isArch32Bit() ? "lib" : "lib64";
4062   }
4063
4064   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
4065   // using that variant while targeting other architectures causes problems
4066   // because the libraries are laid out in shared system roots that can't cope
4067   // with a 'lib32' library search path being considered. So we only enable
4068   // them when we know we may need it.
4069   //
4070   // FIXME: This is a bit of a hack. We should really unify this code for
4071   // reasoning about oslibdir spellings with the lib dir spellings in the
4072   // GCCInstallationDetector, but that is a more significant refactoring.
4073   if (Triple.getArch() == llvm::Triple::x86 ||
4074       Triple.getArch() == llvm::Triple::ppc)
4075     return "lib32";
4076
4077   if (Triple.getArch() == llvm::Triple::x86_64 &&
4078       Triple.getEnvironment() == llvm::Triple::GNUX32)
4079     return "libx32";
4080
4081   return Triple.isArch32Bit() ? "lib" : "lib64";
4082 }
4083
4084 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
4085                                   const Multilib &Multilib,
4086                                   StringRef InstallPath,
4087                                   ToolChain::path_list &Paths) {
4088   if (const auto &PathsCallback = Multilibs.filePathsCallback())
4089     for (const auto &Path : PathsCallback(Multilib))
4090       addPathIfExists(D, InstallPath + Path, Paths);
4091 }
4092
4093 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
4094     : Generic_ELF(D, Triple, Args) {
4095   GCCInstallation.init(Triple, Args);
4096   Multilibs = GCCInstallation.getMultilibs();
4097   llvm::Triple::ArchType Arch = Triple.getArch();
4098   std::string SysRoot = computeSysRoot();
4099
4100   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
4101   // least) put various tools in a triple-prefixed directory off of the parent
4102   // of the GCC installation. We use the GCC triple here to ensure that we end
4103   // up with tools that support the same amount of cross compiling as the
4104   // detected GCC installation. For example, if we find a GCC installation
4105   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
4106   // used to target i386.
4107   // FIXME: This seems unlikely to be Linux-specific.
4108   ToolChain::path_list &PPaths = getProgramPaths();
4109   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
4110                          GCCInstallation.getTriple().str() + "/bin")
4111                        .str());
4112
4113   Distro Distro(D.getVFS());
4114
4115   if (Distro.IsOpenSUSE() || Distro.IsUbuntu()) {
4116     ExtraOpts.push_back("-z");
4117     ExtraOpts.push_back("relro");
4118   }
4119
4120   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
4121     ExtraOpts.push_back("-X");
4122
4123   const bool IsAndroid = Triple.isAndroid();
4124   const bool IsMips = isMipsArch(Arch);
4125
4126   if (IsMips && !SysRoot.empty())
4127     ExtraOpts.push_back("--sysroot=" + SysRoot);
4128
4129   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
4130   // and the MIPS ABI require .dynsym to be sorted in different ways.
4131   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
4132   // ABI requires a mapping between the GOT and the symbol table.
4133   // Android loader does not support .gnu.hash.
4134   if (!IsMips && !IsAndroid) {
4135     if (Distro.IsRedhat() || Distro.IsOpenSUSE() ||
4136         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick))
4137       ExtraOpts.push_back("--hash-style=gnu");
4138
4139     if (Distro.IsDebian() || Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
4140         Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic)
4141       ExtraOpts.push_back("--hash-style=both");
4142   }
4143
4144   if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6)
4145     ExtraOpts.push_back("--no-add-needed");
4146
4147 #ifdef ENABLE_LINKER_BUILD_ID
4148   ExtraOpts.push_back("--build-id");
4149 #endif
4150
4151   if (Distro.IsOpenSUSE())
4152     ExtraOpts.push_back("--enable-new-dtags");
4153
4154   // The selection of paths to try here is designed to match the patterns which
4155   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
4156   // This was determined by running GCC in a fake filesystem, creating all
4157   // possible permutations of these directories, and seeing which ones it added
4158   // to the link paths.
4159   path_list &Paths = getFilePaths();
4160
4161   const std::string OSLibDir = getOSLibDir(Triple, Args);
4162   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
4163
4164   // Add the multilib suffixed paths where they are available.
4165   if (GCCInstallation.isValid()) {
4166     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
4167     const std::string &LibPath = GCCInstallation.getParentLibPath();
4168     const Multilib &Multilib = GCCInstallation.getMultilib();
4169     const MultilibSet &Multilibs = GCCInstallation.getMultilibs();
4170
4171     // Add toolchain / multilib specific file paths.
4172     addMultilibsFilePaths(D, Multilibs, Multilib,
4173                           GCCInstallation.getInstallPath(), Paths);
4174
4175     // Sourcery CodeBench MIPS toolchain holds some libraries under
4176     // a biarch-like suffix of the GCC installation.
4177     addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(),
4178                     Paths);
4179
4180     // GCC cross compiling toolchains will install target libraries which ship
4181     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
4182     // any part of the GCC installation in
4183     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
4184     // debatable, but is the reality today. We need to search this tree even
4185     // when we have a sysroot somewhere else. It is the responsibility of
4186     // whomever is doing the cross build targeting a sysroot using a GCC
4187     // installation that is *not* within the system root to ensure two things:
4188     //
4189     //  1) Any DSOs that are linked in from this tree or from the install path
4190     //     above must be present on the system root and found via an
4191     //     appropriate rpath.
4192     //  2) There must not be libraries installed into
4193     //     <prefix>/<triple>/<libdir> unless they should be preferred over
4194     //     those within the system root.
4195     //
4196     // Note that this matches the GCC behavior. See the below comment for where
4197     // Clang diverges from GCC's behavior.
4198     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
4199                            OSLibDir + Multilib.osSuffix(),
4200                     Paths);
4201
4202     // If the GCC installation we found is inside of the sysroot, we want to
4203     // prefer libraries installed in the parent prefix of the GCC installation.
4204     // It is important to *not* use these paths when the GCC installation is
4205     // outside of the system root as that can pick up unintended libraries.
4206     // This usually happens when there is an external cross compiler on the
4207     // host system, and a more minimal sysroot available that is the target of
4208     // the cross. Note that GCC does include some of these directories in some
4209     // configurations but this seems somewhere between questionable and simply
4210     // a bug.
4211     if (StringRef(LibPath).startswith(SysRoot)) {
4212       addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
4213       addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
4214     }
4215   }
4216
4217   // Similar to the logic for GCC above, if we currently running Clang inside
4218   // of the requested system root, add its parent library paths to
4219   // those searched.
4220   // FIXME: It's not clear whether we should use the driver's installed
4221   // directory ('Dir' below) or the ResourceDir.
4222   if (StringRef(D.Dir).startswith(SysRoot)) {
4223     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
4224     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
4225   }
4226
4227   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
4228   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
4229   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
4230   addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
4231
4232   // Try walking via the GCC triple path in case of biarch or multiarch GCC
4233   // installations with strange symlinks.
4234   if (GCCInstallation.isValid()) {
4235     addPathIfExists(D,
4236                     SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
4237                         "/../../" + OSLibDir,
4238                     Paths);
4239
4240     // Add the 'other' biarch variant path
4241     Multilib BiarchSibling;
4242     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
4243       addPathIfExists(D, GCCInstallation.getInstallPath() +
4244                              BiarchSibling.gccSuffix(),
4245                       Paths);
4246     }
4247
4248     // See comments above on the multilib variant for details of why this is
4249     // included even from outside the sysroot.
4250     const std::string &LibPath = GCCInstallation.getParentLibPath();
4251     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
4252     const Multilib &Multilib = GCCInstallation.getMultilib();
4253     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
4254                            Multilib.osSuffix(),
4255                     Paths);
4256
4257     // See comments above on the multilib variant for details of why this is
4258     // only included from within the sysroot.
4259     if (StringRef(LibPath).startswith(SysRoot))
4260       addPathIfExists(D, LibPath, Paths);
4261   }
4262
4263   // Similar to the logic for GCC above, if we are currently running Clang
4264   // inside of the requested system root, add its parent library path to those
4265   // searched.
4266   // FIXME: It's not clear whether we should use the driver's installed
4267   // directory ('Dir' below) or the ResourceDir.
4268   if (StringRef(D.Dir).startswith(SysRoot))
4269     addPathIfExists(D, D.Dir + "/../lib", Paths);
4270
4271   addPathIfExists(D, SysRoot + "/lib", Paths);
4272   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
4273 }
4274
4275 bool Linux::HasNativeLLVMSupport() const { return true; }
4276
4277 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
4278
4279 Tool *Linux::buildAssembler() const {
4280   return new tools::gnutools::Assembler(*this);
4281 }
4282
4283 std::string Linux::computeSysRoot() const {
4284   if (!getDriver().SysRoot.empty())
4285     return getDriver().SysRoot;
4286
4287   if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
4288     return std::string();
4289
4290   // Standalone MIPS toolchains use different names for sysroot folder
4291   // and put it into different places. Here we try to check some known
4292   // variants.
4293
4294   const StringRef InstallDir = GCCInstallation.getInstallPath();
4295   const StringRef TripleStr = GCCInstallation.getTriple().str();
4296   const Multilib &Multilib = GCCInstallation.getMultilib();
4297
4298   std::string Path =
4299       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
4300           .str();
4301
4302   if (getVFS().exists(Path))
4303     return Path;
4304
4305   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
4306
4307   if (getVFS().exists(Path))
4308     return Path;
4309
4310   return std::string();
4311 }
4312
4313 std::string Linux::getDynamicLinker(const ArgList &Args) const {
4314   const llvm::Triple::ArchType Arch = getArch();
4315   const llvm::Triple &Triple = getTriple();
4316
4317   const Distro Distro(getDriver().getVFS());
4318
4319   if (Triple.isAndroid())
4320     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
4321
4322   if (Triple.isMusl()) {
4323     std::string ArchName;
4324     bool IsArm = false;
4325
4326     switch (Arch) {
4327     case llvm::Triple::arm:
4328     case llvm::Triple::thumb:
4329       ArchName = "arm";
4330       IsArm = true;
4331       break;
4332     case llvm::Triple::armeb:
4333     case llvm::Triple::thumbeb:
4334       ArchName = "armeb";
4335       IsArm = true;
4336       break;
4337     default:
4338       ArchName = Triple.getArchName().str();
4339     }
4340     if (IsArm &&
4341         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
4342          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
4343       ArchName += "hf";
4344
4345     return "/lib/ld-musl-" + ArchName + ".so.1";
4346   }
4347
4348   std::string LibDir;
4349   std::string Loader;
4350
4351   switch (Arch) {
4352   default:
4353     llvm_unreachable("unsupported architecture");
4354
4355   case llvm::Triple::aarch64:
4356     LibDir = "lib";
4357     Loader = "ld-linux-aarch64.so.1";
4358     break;
4359   case llvm::Triple::aarch64_be:
4360     LibDir = "lib";
4361     Loader = "ld-linux-aarch64_be.so.1";
4362     break;
4363   case llvm::Triple::arm:
4364   case llvm::Triple::thumb:
4365   case llvm::Triple::armeb:
4366   case llvm::Triple::thumbeb: {
4367     const bool HF =
4368         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
4369         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
4370
4371     LibDir = "lib";
4372     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
4373     break;
4374   }
4375   case llvm::Triple::mips:
4376   case llvm::Triple::mipsel:
4377   case llvm::Triple::mips64:
4378   case llvm::Triple::mips64el: {
4379     bool LE = (Triple.getArch() == llvm::Triple::mipsel) ||
4380               (Triple.getArch() == llvm::Triple::mips64el);
4381     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
4382
4383     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
4384
4385     if (tools::mips::isUCLibc(Args))
4386       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
4387     else if (!Triple.hasEnvironment() &&
4388              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
4389       Loader = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
4390     else
4391       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
4392
4393     break;
4394   }
4395   case llvm::Triple::ppc:
4396     LibDir = "lib";
4397     Loader = "ld.so.1";
4398     break;
4399   case llvm::Triple::ppc64:
4400     LibDir = "lib64";
4401     Loader =
4402         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
4403     break;
4404   case llvm::Triple::ppc64le:
4405     LibDir = "lib64";
4406     Loader =
4407         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
4408     break;
4409   case llvm::Triple::sparc:
4410   case llvm::Triple::sparcel:
4411     LibDir = "lib";
4412     Loader = "ld-linux.so.2";
4413     break;
4414   case llvm::Triple::sparcv9:
4415     LibDir = "lib64";
4416     Loader = "ld-linux.so.2";
4417     break;
4418   case llvm::Triple::systemz:
4419     LibDir = "lib";
4420     Loader = "ld64.so.1";
4421     break;
4422   case llvm::Triple::x86:
4423     LibDir = "lib";
4424     Loader = "ld-linux.so.2";
4425     break;
4426   case llvm::Triple::x86_64: {
4427     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
4428
4429     LibDir = X32 ? "libx32" : "lib64";
4430     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
4431     break;
4432   }
4433   }
4434
4435   if (Distro == Distro::Exherbo && (Triple.getVendor() == llvm::Triple::UnknownVendor ||
4436                                     Triple.getVendor() == llvm::Triple::PC))
4437     return "/usr/" + Triple.str() + "/lib/" + Loader;
4438   return "/" + LibDir + "/" + Loader;
4439 }
4440
4441 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4442                                       ArgStringList &CC1Args) const {
4443   const Driver &D = getDriver();
4444   std::string SysRoot = computeSysRoot();
4445
4446   if (DriverArgs.hasArg(options::OPT_nostdinc))
4447     return;
4448
4449   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
4450     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
4451
4452   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
4453     SmallString<128> P(D.ResourceDir);
4454     llvm::sys::path::append(P, "include");
4455     addSystemInclude(DriverArgs, CC1Args, P);
4456   }
4457
4458   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
4459     return;
4460
4461   // Check for configure-time C include directories.
4462   StringRef CIncludeDirs(C_INCLUDE_DIRS);
4463   if (CIncludeDirs != "") {
4464     SmallVector<StringRef, 5> dirs;
4465     CIncludeDirs.split(dirs, ":");
4466     for (StringRef dir : dirs) {
4467       StringRef Prefix =
4468           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
4469       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
4470     }
4471     return;
4472   }
4473
4474   // Lacking those, try to detect the correct set of system includes for the
4475   // target triple.
4476
4477   // Add include directories specific to the selected multilib set and multilib.
4478   if (GCCInstallation.isValid()) {
4479     const auto &Callback = Multilibs.includeDirsCallback();
4480     if (Callback) {
4481       for (const auto &Path : Callback(GCCInstallation.getMultilib()))
4482         addExternCSystemIncludeIfExists(
4483             DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
4484     }
4485   }
4486
4487   // Implement generic Debian multiarch support.
4488   const StringRef X86_64MultiarchIncludeDirs[] = {
4489       "/usr/include/x86_64-linux-gnu",
4490
4491       // FIXME: These are older forms of multiarch. It's not clear that they're
4492       // in use in any released version of Debian, so we should consider
4493       // removing them.
4494       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
4495   const StringRef X86MultiarchIncludeDirs[] = {
4496       "/usr/include/i386-linux-gnu",
4497
4498       // FIXME: These are older forms of multiarch. It's not clear that they're
4499       // in use in any released version of Debian, so we should consider
4500       // removing them.
4501       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
4502       "/usr/include/i486-linux-gnu"};
4503   const StringRef AArch64MultiarchIncludeDirs[] = {
4504       "/usr/include/aarch64-linux-gnu"};
4505   const StringRef ARMMultiarchIncludeDirs[] = {
4506       "/usr/include/arm-linux-gnueabi"};
4507   const StringRef ARMHFMultiarchIncludeDirs[] = {
4508       "/usr/include/arm-linux-gnueabihf"};
4509   const StringRef ARMEBMultiarchIncludeDirs[] = {
4510       "/usr/include/armeb-linux-gnueabi"};
4511   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
4512       "/usr/include/armeb-linux-gnueabihf"};
4513   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
4514   const StringRef MIPSELMultiarchIncludeDirs[] = {
4515       "/usr/include/mipsel-linux-gnu"};
4516   const StringRef MIPS64MultiarchIncludeDirs[] = {
4517       "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
4518   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
4519       "/usr/include/mips64el-linux-gnu",
4520       "/usr/include/mips64el-linux-gnuabi64"};
4521   const StringRef PPCMultiarchIncludeDirs[] = {
4522       "/usr/include/powerpc-linux-gnu"};
4523   const StringRef PPC64MultiarchIncludeDirs[] = {
4524       "/usr/include/powerpc64-linux-gnu"};
4525   const StringRef PPC64LEMultiarchIncludeDirs[] = {
4526       "/usr/include/powerpc64le-linux-gnu"};
4527   const StringRef SparcMultiarchIncludeDirs[] = {
4528       "/usr/include/sparc-linux-gnu"};
4529   const StringRef Sparc64MultiarchIncludeDirs[] = {
4530       "/usr/include/sparc64-linux-gnu"};
4531   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
4532       "/usr/include/s390x-linux-gnu"};
4533   ArrayRef<StringRef> MultiarchIncludeDirs;
4534   switch (getTriple().getArch()) {
4535   case llvm::Triple::x86_64:
4536     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
4537     break;
4538   case llvm::Triple::x86:
4539     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
4540     break;
4541   case llvm::Triple::aarch64:
4542   case llvm::Triple::aarch64_be:
4543     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
4544     break;
4545   case llvm::Triple::arm:
4546   case llvm::Triple::thumb:
4547     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
4548       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
4549     else
4550       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
4551     break;
4552   case llvm::Triple::armeb:
4553   case llvm::Triple::thumbeb:
4554     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
4555       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
4556     else
4557       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
4558     break;
4559   case llvm::Triple::mips:
4560     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
4561     break;
4562   case llvm::Triple::mipsel:
4563     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
4564     break;
4565   case llvm::Triple::mips64:
4566     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
4567     break;
4568   case llvm::Triple::mips64el:
4569     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
4570     break;
4571   case llvm::Triple::ppc:
4572     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
4573     break;
4574   case llvm::Triple::ppc64:
4575     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
4576     break;
4577   case llvm::Triple::ppc64le:
4578     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
4579     break;
4580   case llvm::Triple::sparc:
4581     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
4582     break;
4583   case llvm::Triple::sparcv9:
4584     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
4585     break;
4586   case llvm::Triple::systemz:
4587     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
4588     break;
4589   default:
4590     break;
4591   }
4592   for (StringRef Dir : MultiarchIncludeDirs) {
4593     if (D.getVFS().exists(SysRoot + Dir)) {
4594       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
4595       break;
4596     }
4597   }
4598
4599   if (getTriple().getOS() == llvm::Triple::RTEMS)
4600     return;
4601
4602   // Add an include of '/include' directly. This isn't provided by default by
4603   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
4604   // add even when Clang is acting as-if it were a system compiler.
4605   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
4606
4607   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
4608 }
4609
4610 static std::string DetectLibcxxIncludePath(StringRef base) {
4611   std::error_code EC;
4612   int MaxVersion = 0;
4613   std::string MaxVersionString = "";
4614   for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
4615        LI = LI.increment(EC)) {
4616     StringRef VersionText = llvm::sys::path::filename(LI->path());
4617     int Version;
4618     if (VersionText[0] == 'v' &&
4619         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
4620       if (Version > MaxVersion) {
4621         MaxVersion = Version;
4622         MaxVersionString = VersionText;
4623       }
4624     }
4625   }
4626   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
4627 }
4628
4629 std::string Linux::findLibCxxIncludePath() const {
4630   const std::string LibCXXIncludePathCandidates[] = {
4631       DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
4632       // If this is a development, non-installed, clang, libcxx will
4633       // not be found at ../include/c++ but it likely to be found at
4634       // one of the following two locations:
4635       DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/local/include/c++"),
4636       DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++") };
4637   for (const auto &IncludePath : LibCXXIncludePathCandidates) {
4638     if (IncludePath.empty() || !getVFS().exists(IncludePath))
4639       continue;
4640     // Use the first candidate that exists.
4641     return IncludePath;
4642   }
4643   return "";
4644 }
4645
4646 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
4647                                      llvm::opt::ArgStringList &CC1Args) const {
4648   // We need a detected GCC installation on Linux to provide libstdc++'s
4649   // headers.
4650   if (!GCCInstallation.isValid())
4651     return;
4652
4653   // By default, look for the C++ headers in an include directory adjacent to
4654   // the lib directory of the GCC installation. Note that this is expect to be
4655   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
4656   StringRef LibDir = GCCInstallation.getParentLibPath();
4657   StringRef InstallDir = GCCInstallation.getInstallPath();
4658   StringRef TripleStr = GCCInstallation.getTriple().str();
4659   const Multilib &Multilib = GCCInstallation.getMultilib();
4660   const std::string GCCMultiarchTriple = getMultiarchTriple(
4661       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
4662   const std::string TargetMultiarchTriple =
4663       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
4664   const GCCVersion &Version = GCCInstallation.getVersion();
4665
4666   // The primary search for libstdc++ supports multiarch variants.
4667   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
4668                                "/c++/" + Version.Text, TripleStr,
4669                                GCCMultiarchTriple, TargetMultiarchTriple,
4670                                Multilib.includeSuffix(), DriverArgs, CC1Args))
4671     return;
4672
4673   // Otherwise, fall back on a bunch of options which don't use multiarch
4674   // layouts for simplicity.
4675   const std::string LibStdCXXIncludePathCandidates[] = {
4676       // Gentoo is weird and places its headers inside the GCC install,
4677       // so if the first attempt to find the headers fails, try these patterns.
4678       InstallDir.str() + "/include/g++-v" + Version.Text,
4679       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
4680           Version.MinorStr,
4681       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
4682       // Android standalone toolchain has C++ headers in yet another place.
4683       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4684       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
4685       // without a subdirectory corresponding to the gcc version.
4686       LibDir.str() + "/../include/c++",
4687   };
4688
4689   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
4690     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
4691                                  /*GCCMultiarchTriple*/ "",
4692                                  /*TargetMultiarchTriple*/ "",
4693                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
4694       break;
4695   }
4696 }
4697
4698 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
4699                                ArgStringList &CC1Args) const {
4700   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
4701 }
4702
4703 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
4704                                 ArgStringList &CC1Args) const {
4705   if (GCCInstallation.isValid()) {
4706     CC1Args.push_back("-isystem");
4707     CC1Args.push_back(DriverArgs.MakeArgString(
4708         GCCInstallation.getParentLibPath() + "/../" +
4709         GCCInstallation.getTriple().str() + "/include"));
4710   }
4711 }
4712
4713 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
4714
4715 SanitizerMask Linux::getSupportedSanitizers() const {
4716   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
4717   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4718   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
4719                         getTriple().getArch() == llvm::Triple::mips64el;
4720   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
4721                            getTriple().getArch() == llvm::Triple::ppc64le;
4722   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
4723                          getTriple().getArch() == llvm::Triple::aarch64_be;
4724   SanitizerMask Res = ToolChain::getSupportedSanitizers();
4725   Res |= SanitizerKind::Address;
4726   Res |= SanitizerKind::KernelAddress;
4727   Res |= SanitizerKind::Vptr;
4728   Res |= SanitizerKind::SafeStack;
4729   if (IsX86_64 || IsMIPS64 || IsAArch64)
4730     Res |= SanitizerKind::DataFlow;
4731   if (IsX86_64 || IsMIPS64 || IsAArch64)
4732     Res |= SanitizerKind::Leak;
4733   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
4734     Res |= SanitizerKind::Thread;
4735   if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64)
4736     Res |= SanitizerKind::Memory;
4737   if (IsX86_64 || IsMIPS64)
4738     Res |= SanitizerKind::Efficiency;
4739   if (IsX86 || IsX86_64) {
4740     Res |= SanitizerKind::Function;
4741   }
4742   return Res;
4743 }
4744
4745 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
4746                              llvm::opt::ArgStringList &CmdArgs) const {
4747   if (!needsProfileRT(Args)) return;
4748
4749   // Add linker option -u__llvm_runtime_variable to cause runtime
4750   // initialization module to be linked in.
4751   if (!Args.hasArg(options::OPT_coverage))
4752     CmdArgs.push_back(Args.MakeArgString(
4753         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
4754   ToolChain::addProfileRTLibs(Args, CmdArgs);
4755 }
4756
4757 /// Fuchsia - Fuchsia tool chain which can call as(1) and ld(1) directly.
4758
4759 Fuchsia::Fuchsia(const Driver &D, const llvm::Triple &Triple,
4760                  const ArgList &Args)
4761     : Generic_ELF(D, Triple, Args) {
4762
4763   getFilePaths().push_back(D.SysRoot + "/lib");
4764   getFilePaths().push_back(D.ResourceDir + "/lib/fuchsia");
4765 }
4766
4767 Tool *Fuchsia::buildAssembler() const {
4768   return new tools::gnutools::Assembler(*this);
4769 }
4770
4771 Tool *Fuchsia::buildLinker() const {
4772   return new tools::fuchsia::Linker(*this);
4773 }
4774
4775 ToolChain::RuntimeLibType Fuchsia::GetRuntimeLibType(
4776     const ArgList &Args) const {
4777   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
4778     StringRef Value = A->getValue();
4779     if (Value != "compiler-rt")
4780       getDriver().Diag(diag::err_drv_invalid_rtlib_name)
4781         << A->getAsString(Args);
4782   }
4783
4784   return ToolChain::RLT_CompilerRT;
4785 }
4786
4787 ToolChain::CXXStdlibType
4788 Fuchsia::GetCXXStdlibType(const ArgList &Args) const {
4789   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
4790     StringRef Value = A->getValue();
4791     if (Value != "libc++")
4792       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
4793         << A->getAsString(Args);
4794   }
4795
4796   return ToolChain::CST_Libcxx;
4797 }
4798
4799 void Fuchsia::addClangTargetOptions(const ArgList &DriverArgs,
4800                                     ArgStringList &CC1Args) const {
4801   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
4802                          options::OPT_fno_use_init_array, true))
4803     CC1Args.push_back("-fuse-init-array");
4804 }
4805
4806 void Fuchsia::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4807                                         ArgStringList &CC1Args) const {
4808   const Driver &D = getDriver();
4809
4810   if (DriverArgs.hasArg(options::OPT_nostdinc))
4811     return;
4812
4813   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
4814     SmallString<128> P(D.ResourceDir);
4815     llvm::sys::path::append(P, "include");
4816     addSystemInclude(DriverArgs, CC1Args, P);
4817   }
4818
4819   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
4820     return;
4821
4822   // Check for configure-time C include directories.
4823   StringRef CIncludeDirs(C_INCLUDE_DIRS);
4824   if (CIncludeDirs != "") {
4825     SmallVector<StringRef, 5> dirs;
4826     CIncludeDirs.split(dirs, ":");
4827     for (StringRef dir : dirs) {
4828       StringRef Prefix =
4829           llvm::sys::path::is_absolute(dir) ? StringRef(D.SysRoot) : "";
4830       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
4831     }
4832     return;
4833   }
4834
4835   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
4836 }
4837
4838 std::string Fuchsia::findLibCxxIncludePath() const {
4839   return getDriver().SysRoot + "/include/c++/v1";
4840 }
4841
4842 void Fuchsia::AddCXXStdlibLibArgs(const ArgList &Args,
4843                                   ArgStringList &CmdArgs) const {
4844   (void) GetCXXStdlibType(Args);
4845   CmdArgs.push_back("-lc++");
4846   CmdArgs.push_back("-lc++abi");
4847   CmdArgs.push_back("-lunwind");
4848 }
4849
4850 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
4851
4852 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
4853                      const ArgList &Args)
4854     : Generic_ELF(D, Triple, Args) {
4855
4856   // Path mangling to find libexec
4857   getProgramPaths().push_back(getDriver().getInstalledDir());
4858   if (getDriver().getInstalledDir() != getDriver().Dir)
4859     getProgramPaths().push_back(getDriver().Dir);
4860
4861   getFilePaths().push_back(getDriver().Dir + "/../lib");
4862   getFilePaths().push_back("/usr/lib");
4863   getFilePaths().push_back("/usr/lib/gcc50");
4864 }
4865
4866 Tool *DragonFly::buildAssembler() const {
4867   return new tools::dragonfly::Assembler(*this);
4868 }
4869
4870 Tool *DragonFly::buildLinker() const {
4871   return new tools::dragonfly::Linker(*this);
4872 }
4873
4874 /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
4875 /// which isn't properly a linker but nonetheless performs the step of stitching
4876 /// together object files from the assembler into a single blob.
4877
4878 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
4879                              const ToolChain &HostTC, const ArgList &Args)
4880     : ToolChain(D, Triple, Args), HostTC(HostTC),
4881       CudaInstallation(D, HostTC.getTriple(), Args) {
4882   if (CudaInstallation.isValid())
4883     getProgramPaths().push_back(CudaInstallation.getBinPath());
4884 }
4885
4886 void CudaToolChain::addClangTargetOptions(
4887     const llvm::opt::ArgList &DriverArgs,
4888     llvm::opt::ArgStringList &CC1Args) const {
4889   HostTC.addClangTargetOptions(DriverArgs, CC1Args);
4890
4891   CC1Args.push_back("-fcuda-is-device");
4892
4893   if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
4894                          options::OPT_fno_cuda_flush_denormals_to_zero, false))
4895     CC1Args.push_back("-fcuda-flush-denormals-to-zero");
4896
4897   if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
4898                          options::OPT_fno_cuda_approx_transcendentals, false))
4899     CC1Args.push_back("-fcuda-approx-transcendentals");
4900
4901   if (DriverArgs.hasArg(options::OPT_nocudalib))
4902     return;
4903
4904   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
4905   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
4906   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
4907
4908   if (LibDeviceFile.empty()) {
4909     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
4910     return;
4911   }
4912
4913   CC1Args.push_back("-mlink-cuda-bitcode");
4914   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
4915
4916   // Libdevice in CUDA-7.0 requires PTX version that's more recent
4917   // than LLVM defaults to. Use PTX4.2 which is the PTX version that
4918   // came with CUDA-7.0.
4919   CC1Args.push_back("-target-feature");
4920   CC1Args.push_back("+ptx42");
4921 }
4922
4923 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
4924                                        ArgStringList &CC1Args) const {
4925   // Check our CUDA version if we're going to include the CUDA headers.
4926   if (!DriverArgs.hasArg(options::OPT_nocudainc) &&
4927       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
4928     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
4929     assert(!Arch.empty() && "Must have an explicit GPU arch.");
4930     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
4931   }
4932   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
4933 }
4934
4935 llvm::opt::DerivedArgList *
4936 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
4937                              StringRef BoundArch,
4938                              Action::OffloadKind DeviceOffloadKind) const {
4939   DerivedArgList *DAL =
4940       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
4941   if (!DAL)
4942     DAL = new DerivedArgList(Args.getBaseArgs());
4943
4944   const OptTable &Opts = getDriver().getOpts();
4945
4946   for (Arg *A : Args) {
4947     if (A->getOption().matches(options::OPT_Xarch__)) {
4948       // Skip this argument unless the architecture matches BoundArch
4949       if (BoundArch.empty() || A->getValue(0) != BoundArch)
4950         continue;
4951
4952       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
4953       unsigned Prev = Index;
4954       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
4955
4956       // If the argument parsing failed or more than one argument was
4957       // consumed, the -Xarch_ argument's parameter tried to consume
4958       // extra arguments. Emit an error and ignore.
4959       //
4960       // We also want to disallow any options which would alter the
4961       // driver behavior; that isn't going to work in our model. We
4962       // use isDriverOption() as an approximation, although things
4963       // like -O4 are going to slip through.
4964       if (!XarchArg || Index > Prev + 1) {
4965         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
4966             << A->getAsString(Args);
4967         continue;
4968       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
4969         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
4970             << A->getAsString(Args);
4971         continue;
4972       }
4973       XarchArg->setBaseArg(A);
4974       A = XarchArg.release();
4975       DAL->AddSynthesizedArg(A);
4976     }
4977     DAL->append(A);
4978   }
4979
4980   if (!BoundArch.empty()) {
4981     DAL->eraseArg(options::OPT_march_EQ);
4982     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
4983   }
4984   return DAL;
4985 }
4986
4987 Tool *CudaToolChain::buildAssembler() const {
4988   return new tools::NVPTX::Assembler(*this);
4989 }
4990
4991 Tool *CudaToolChain::buildLinker() const {
4992   return new tools::NVPTX::Linker(*this);
4993 }
4994
4995 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
4996   HostTC.addClangWarningOptions(CC1Args);
4997 }
4998
4999 ToolChain::CXXStdlibType
5000 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
5001   return HostTC.GetCXXStdlibType(Args);
5002 }
5003
5004 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5005                                               ArgStringList &CC1Args) const {
5006   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
5007 }
5008
5009 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
5010                                                  ArgStringList &CC1Args) const {
5011   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
5012 }
5013
5014 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
5015                                         ArgStringList &CC1Args) const {
5016   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
5017 }
5018
5019 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
5020   // The CudaToolChain only supports sanitizers in the sense that it allows
5021   // sanitizer arguments on the command line if they are supported by the host
5022   // toolchain. The CudaToolChain will actually ignore any command line
5023   // arguments for any of these "supported" sanitizers. That means that no
5024   // sanitization of device code is actually supported at this time.
5025   //
5026   // This behavior is necessary because the host and device toolchains
5027   // invocations often share the command line, so the device toolchain must
5028   // tolerate flags meant only for the host toolchain.
5029   return HostTC.getSupportedSanitizers();
5030 }
5031
5032 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
5033                                                const ArgList &Args) const {
5034   return HostTC.computeMSVCVersion(D, Args);
5035 }
5036
5037 /// XCore tool chain
5038 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple,
5039                                const ArgList &Args)
5040     : ToolChain(D, Triple, Args) {
5041   // ProgramPaths are found via 'PATH' environment variable.
5042 }
5043
5044 Tool *XCoreToolChain::buildAssembler() const {
5045   return new tools::XCore::Assembler(*this);
5046 }
5047
5048 Tool *XCoreToolChain::buildLinker() const {
5049   return new tools::XCore::Linker(*this);
5050 }
5051
5052 bool XCoreToolChain::isPICDefault() const { return false; }
5053
5054 bool XCoreToolChain::isPIEDefault() const { return false; }
5055
5056 bool XCoreToolChain::isPICDefaultForced() const { return false; }
5057
5058 bool XCoreToolChain::SupportsProfiling() const { return false; }
5059
5060 bool XCoreToolChain::hasBlocksRuntime() const { return false; }
5061
5062 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5063                                                ArgStringList &CC1Args) const {
5064   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
5065       DriverArgs.hasArg(options::OPT_nostdlibinc))
5066     return;
5067   if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
5068     SmallVector<StringRef, 4> Dirs;
5069     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
5070     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
5071     ArrayRef<StringRef> DirVec(Dirs);
5072     addSystemIncludes(DriverArgs, CC1Args, DirVec);
5073   }
5074 }
5075
5076 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs,
5077                                            ArgStringList &CC1Args) const {
5078   CC1Args.push_back("-nostdsysteminc");
5079 }
5080
5081 void XCoreToolChain::AddClangCXXStdlibIncludeArgs(
5082     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
5083   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
5084       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
5085       DriverArgs.hasArg(options::OPT_nostdincxx))
5086     return;
5087   if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
5088     SmallVector<StringRef, 4> Dirs;
5089     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
5090     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
5091     ArrayRef<StringRef> DirVec(Dirs);
5092     addSystemIncludes(DriverArgs, CC1Args, DirVec);
5093   }
5094 }
5095
5096 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
5097                                          ArgStringList &CmdArgs) const {
5098   // We don't output any lib args. This is handled by xcc.
5099 }
5100
5101 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple,
5102                                  const ArgList &Args)
5103     : Generic_ELF(D, Triple, Args) {
5104   // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use
5105   // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple.
5106   // This won't work to find gcc. Instead we give the installation detector an
5107   // extra triple, which is preferable to further hacks of the logic that at
5108   // present is based solely on getArch(). In particular, it would be wrong to
5109   // choose the myriad installation when targeting a non-myriad sparc install.
5110   switch (Triple.getArch()) {
5111   default:
5112     D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5113                                               << "myriad";
5114   case llvm::Triple::sparc:
5115   case llvm::Triple::sparcel:
5116   case llvm::Triple::shave:
5117     GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"});
5118   }
5119
5120   if (GCCInstallation.isValid()) {
5121     // This directory contains crt{i,n,begin,end}.o as well as libgcc.
5122     // These files are tied to a particular version of gcc.
5123     SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath());
5124     addPathIfExists(D, CompilerSupportDir, getFilePaths());
5125   }
5126   // libstd++ and libc++ must both be found in this one place.
5127   addPathIfExists(D, D.Dir + "/../sparc-myriad-elf/lib", getFilePaths());
5128 }
5129
5130 MyriadToolChain::~MyriadToolChain() {}
5131
5132 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5133                                                 ArgStringList &CC1Args) const {
5134   if (!DriverArgs.hasArg(options::OPT_nostdinc))
5135     addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
5136 }
5137
5138 std::string MyriadToolChain::findLibCxxIncludePath() const {
5139   std::string Path(getDriver().getInstalledDir());
5140   return Path + "/../include/c++/v1";
5141 }
5142
5143 void MyriadToolChain::addLibStdCxxIncludePaths(
5144     const llvm::opt::ArgList &DriverArgs,
5145     llvm::opt::ArgStringList &CC1Args) const {
5146   StringRef LibDir = GCCInstallation.getParentLibPath();
5147   const GCCVersion &Version = GCCInstallation.getVersion();
5148   StringRef TripleStr = GCCInstallation.getTriple().str();
5149   const Multilib &Multilib = GCCInstallation.getMultilib();
5150   addLibStdCXXIncludePaths(
5151       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
5152       "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args);
5153 }
5154
5155 // MyriadToolChain handles several triples:
5156 //  {shave,sparc{,el}}-myriad-{rtems,unknown}-elf
5157 Tool *MyriadToolChain::SelectTool(const JobAction &JA) const {
5158   // The inherited method works fine if not targeting the SHAVE.
5159   if (!isShaveCompilation(getTriple()))
5160     return ToolChain::SelectTool(JA);
5161   switch (JA.getKind()) {
5162   case Action::PreprocessJobClass:
5163   case Action::CompileJobClass:
5164     if (!Compiler)
5165       Compiler.reset(new tools::SHAVE::Compiler(*this));
5166     return Compiler.get();
5167   case Action::AssembleJobClass:
5168     if (!Assembler)
5169       Assembler.reset(new tools::SHAVE::Assembler(*this));
5170     return Assembler.get();
5171   default:
5172     return ToolChain::getTool(JA.getKind());
5173   }
5174 }
5175
5176 Tool *MyriadToolChain::buildLinker() const {
5177   return new tools::Myriad::Linker(*this);
5178 }
5179
5180 SanitizerMask MyriadToolChain::getSupportedSanitizers() const {
5181   return SanitizerKind::Address;
5182 }
5183
5184 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
5185                          const llvm::opt::ArgList &Args)
5186   : ToolChain(D, Triple, Args) {
5187
5188   assert(Triple.isArch32Bit() != Triple.isArch64Bit());
5189   getFilePaths().push_back(
5190       getDriver().SysRoot + "/lib" + (Triple.isArch32Bit() ? "32" : "64"));
5191 }
5192
5193 bool WebAssembly::IsMathErrnoDefault() const { return false; }
5194
5195 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
5196
5197 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
5198
5199 bool WebAssembly::isPICDefault() const { return false; }
5200
5201 bool WebAssembly::isPIEDefault() const { return false; }
5202
5203 bool WebAssembly::isPICDefaultForced() const { return false; }
5204
5205 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
5206
5207 // TODO: Support Objective C stuff.
5208 bool WebAssembly::SupportsObjCGC() const { return false; }
5209
5210 bool WebAssembly::hasBlocksRuntime() const { return false; }
5211
5212 // TODO: Support profiling.
5213 bool WebAssembly::SupportsProfiling() const { return false; }
5214
5215 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
5216
5217 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
5218                                         ArgStringList &CC1Args) const {
5219   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
5220                          options::OPT_fno_use_init_array, true))
5221     CC1Args.push_back("-fuse-init-array");
5222 }
5223
5224 ToolChain::RuntimeLibType WebAssembly::GetDefaultRuntimeLibType() const {
5225   return ToolChain::RLT_CompilerRT;
5226 }
5227
5228 ToolChain::CXXStdlibType WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
5229   return ToolChain::CST_Libcxx;
5230 }
5231
5232 void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5233                                             ArgStringList &CC1Args) const {
5234   if (!DriverArgs.hasArg(options::OPT_nostdinc))
5235     addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
5236 }
5237
5238 void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
5239                                                ArgStringList &CC1Args) const {
5240   if (!DriverArgs.hasArg(options::OPT_nostdlibinc) &&
5241       !DriverArgs.hasArg(options::OPT_nostdincxx))
5242     addSystemInclude(DriverArgs, CC1Args,
5243                      getDriver().SysRoot + "/include/c++/v1");
5244 }
5245
5246 Tool *WebAssembly::buildLinker() const {
5247   return new tools::wasm::Linker(*this);
5248 }
5249
5250 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
5251     : Generic_ELF(D, Triple, Args) {
5252   if (Args.hasArg(options::OPT_static))
5253     D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4";
5254
5255   // Determine where to find the PS4 libraries. We use SCE_ORBIS_SDK_DIR
5256   // if it exists; otherwise use the driver's installation path, which
5257   // should be <SDK_DIR>/host_tools/bin.
5258
5259   SmallString<512> PS4SDKDir;
5260   if (const char *EnvValue = getenv("SCE_ORBIS_SDK_DIR")) {
5261     if (!llvm::sys::fs::exists(EnvValue))
5262       getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue;
5263     PS4SDKDir = EnvValue;
5264   } else {
5265     PS4SDKDir = getDriver().Dir;
5266     llvm::sys::path::append(PS4SDKDir, "/../../");
5267   }
5268
5269   // By default, the driver won't report a warning if it can't find
5270   // PS4's include or lib directories. This behavior could be changed if
5271   // -Weverything or -Winvalid-or-nonexistent-directory options are passed.
5272   // If -isysroot was passed, use that as the SDK base path.
5273   std::string PrefixDir;
5274   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
5275     PrefixDir = A->getValue();
5276     if (!llvm::sys::fs::exists(PrefixDir))
5277       getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir;
5278   } else
5279     PrefixDir = PS4SDKDir.str();
5280
5281   SmallString<512> PS4SDKIncludeDir(PrefixDir);
5282   llvm::sys::path::append(PS4SDKIncludeDir, "target/include");
5283   if (!Args.hasArg(options::OPT_nostdinc) &&
5284       !Args.hasArg(options::OPT_nostdlibinc) &&
5285       !Args.hasArg(options::OPT_isysroot) &&
5286       !Args.hasArg(options::OPT__sysroot_EQ) &&
5287       !llvm::sys::fs::exists(PS4SDKIncludeDir)) {
5288     getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
5289         << "PS4 system headers" << PS4SDKIncludeDir;
5290   }
5291
5292   SmallString<512> PS4SDKLibDir(PS4SDKDir);
5293   llvm::sys::path::append(PS4SDKLibDir, "target/lib");
5294   if (!Args.hasArg(options::OPT_nostdlib) &&
5295       !Args.hasArg(options::OPT_nodefaultlibs) &&
5296       !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) &&
5297       !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) &&
5298       !Args.hasArg(options::OPT_emit_ast) &&
5299       !llvm::sys::fs::exists(PS4SDKLibDir)) {
5300     getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
5301         << "PS4 system libraries" << PS4SDKLibDir;
5302     return;
5303   }
5304   getFilePaths().push_back(PS4SDKLibDir.str());
5305 }
5306
5307 Tool *PS4CPU::buildAssembler() const {
5308   return new tools::PS4cpu::Assemble(*this);
5309 }
5310
5311 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); }
5312
5313 bool PS4CPU::isPICDefault() const { return true; }
5314
5315 bool PS4CPU::HasNativeLLVMSupport() const { return true; }
5316
5317 SanitizerMask PS4CPU::getSupportedSanitizers() const {
5318   SanitizerMask Res = ToolChain::getSupportedSanitizers();
5319   Res |= SanitizerKind::Address;
5320   Res |= SanitizerKind::Vptr;
5321   return Res;
5322 }
5323
5324 Contiki::Contiki(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
5325     : Generic_ELF(D, Triple, Args) {}
5326
5327 SanitizerMask Contiki::getSupportedSanitizers() const {
5328   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
5329   SanitizerMask Res = ToolChain::getSupportedSanitizers();
5330   if (IsX86)
5331     Res |= SanitizerKind::SafeStack;
5332   return Res;
5333 }
5334
5335 /// AVR Toolchain
5336 AVRToolChain::AVRToolChain(const Driver &D, const llvm::Triple &Triple,
5337                            const ArgList &Args)
5338   : Generic_ELF(D, Triple, Args) { }
5339 Tool *AVRToolChain::buildLinker() const {
5340   return new tools::AVR::Linker(*this);
5341 }
5342 // End AVR