]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
Update clang to trunk r290819 and resolve conflicts.
[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"};
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 &TargetTriple,
1809     const llvm::opt::ArgList &Args)
1810     : D(D) {
1811   SmallVector<std::string, 4> CudaPathCandidates;
1812
1813   if (Args.hasArg(options::OPT_cuda_path_EQ))
1814     CudaPathCandidates.push_back(
1815         Args.getLastArgValue(options::OPT_cuda_path_EQ));
1816   else {
1817     CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda");
1818     CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-8.0");
1819     CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.5");
1820     CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.0");
1821   }
1822
1823   for (const auto &CudaPath : CudaPathCandidates) {
1824     if (CudaPath.empty() || !D.getVFS().exists(CudaPath))
1825       continue;
1826
1827     InstallPath = CudaPath;
1828     BinPath = CudaPath + "/bin";
1829     IncludePath = InstallPath + "/include";
1830     LibDevicePath = InstallPath + "/nvvm/libdevice";
1831
1832     auto &FS = D.getVFS();
1833     if (!(FS.exists(IncludePath) && FS.exists(BinPath) &&
1834           FS.exists(LibDevicePath)))
1835       continue;
1836
1837     // On Linux, we have both lib and lib64 directories, and we need to choose
1838     // based on our triple.  On MacOS, we have only a lib directory.
1839     //
1840     // It's sufficient for our purposes to be flexible: If both lib and lib64
1841     // exist, we choose whichever one matches our triple.  Otherwise, if only
1842     // lib exists, we use it.
1843     if (TargetTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
1844       LibPath = InstallPath + "/lib64";
1845     else if (FS.exists(InstallPath + "/lib"))
1846       LibPath = InstallPath + "/lib";
1847     else
1848       continue;
1849
1850     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
1851         FS.getBufferForFile(InstallPath + "/version.txt");
1852     if (!VersionFile) {
1853       // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
1854       // version.txt isn't present.
1855       Version = CudaVersion::CUDA_70;
1856     } else {
1857       Version = ParseCudaVersionFile((*VersionFile)->getBuffer());
1858     }
1859
1860     std::error_code EC;
1861     for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
1862          !EC && LI != LE; LI = LI.increment(EC)) {
1863       StringRef FilePath = LI->path();
1864       StringRef FileName = llvm::sys::path::filename(FilePath);
1865       // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc
1866       const StringRef LibDeviceName = "libdevice.";
1867       if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
1868         continue;
1869       StringRef GpuArch = FileName.slice(
1870           LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
1871       LibDeviceMap[GpuArch] = FilePath.str();
1872       // Insert map entries for specifc devices with this compute
1873       // capability. NVCC's choice of the libdevice library version is
1874       // rather peculiar and depends on the CUDA version.
1875       if (GpuArch == "compute_20") {
1876         LibDeviceMap["sm_20"] = FilePath;
1877         LibDeviceMap["sm_21"] = FilePath;
1878         LibDeviceMap["sm_32"] = FilePath;
1879       } else if (GpuArch == "compute_30") {
1880         LibDeviceMap["sm_30"] = FilePath;
1881         if (Version < CudaVersion::CUDA_80) {
1882           LibDeviceMap["sm_50"] = FilePath;
1883           LibDeviceMap["sm_52"] = FilePath;
1884           LibDeviceMap["sm_53"] = FilePath;
1885         }
1886         LibDeviceMap["sm_60"] = FilePath;
1887         LibDeviceMap["sm_61"] = FilePath;
1888         LibDeviceMap["sm_62"] = FilePath;
1889       } else if (GpuArch == "compute_35") {
1890         LibDeviceMap["sm_35"] = FilePath;
1891         LibDeviceMap["sm_37"] = FilePath;
1892       } else if (GpuArch == "compute_50") {
1893         if (Version >= CudaVersion::CUDA_80) {
1894           LibDeviceMap["sm_50"] = FilePath;
1895           LibDeviceMap["sm_52"] = FilePath;
1896           LibDeviceMap["sm_53"] = FilePath;
1897         }
1898       }
1899     }
1900
1901     IsValid = true;
1902     break;
1903   }
1904 }
1905
1906 void CudaInstallationDetector::AddCudaIncludeArgs(
1907     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
1908   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
1909     // Add cuda_wrappers/* to our system include path.  This lets us wrap
1910     // standard library headers.
1911     SmallString<128> P(D.ResourceDir);
1912     llvm::sys::path::append(P, "include");
1913     llvm::sys::path::append(P, "cuda_wrappers");
1914     CC1Args.push_back("-internal-isystem");
1915     CC1Args.push_back(DriverArgs.MakeArgString(P));
1916   }
1917
1918   if (DriverArgs.hasArg(options::OPT_nocudainc))
1919     return;
1920
1921   if (!isValid()) {
1922     D.Diag(diag::err_drv_no_cuda_installation);
1923     return;
1924   }
1925
1926   CC1Args.push_back("-internal-isystem");
1927   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
1928   CC1Args.push_back("-include");
1929   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
1930 }
1931
1932 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
1933     CudaArch Arch) const {
1934   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
1935       ArchsWithVersionTooLowErrors.count(Arch) > 0)
1936     return;
1937
1938   auto RequiredVersion = MinVersionForCudaArch(Arch);
1939   if (Version < RequiredVersion) {
1940     ArchsWithVersionTooLowErrors.insert(Arch);
1941     D.Diag(diag::err_drv_cuda_version_too_low)
1942         << InstallPath << CudaArchToString(Arch) << CudaVersionToString(Version)
1943         << CudaVersionToString(RequiredVersion);
1944   }
1945 }
1946
1947 void CudaInstallationDetector::print(raw_ostream &OS) const {
1948   if (isValid())
1949     OS << "Found CUDA installation: " << InstallPath << ", version "
1950        << CudaVersionToString(Version) << "\n";
1951 }
1952
1953 namespace {
1954 // Filter to remove Multilibs that don't exist as a suffix to Path
1955 class FilterNonExistent {
1956   StringRef Base, File;
1957   vfs::FileSystem &VFS;
1958
1959 public:
1960   FilterNonExistent(StringRef Base, StringRef File, vfs::FileSystem &VFS)
1961       : Base(Base), File(File), VFS(VFS) {}
1962   bool operator()(const Multilib &M) {
1963     return !VFS.exists(Base + M.gccSuffix() + File);
1964   }
1965 };
1966 } // end anonymous namespace
1967
1968 static void addMultilibFlag(bool Enabled, const char *const Flag,
1969                             std::vector<std::string> &Flags) {
1970   if (Enabled)
1971     Flags.push_back(std::string("+") + Flag);
1972   else
1973     Flags.push_back(std::string("-") + Flag);
1974 }
1975
1976 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1977   return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1978 }
1979
1980 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1981   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1982          Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1983 }
1984
1985 static bool isMips32(llvm::Triple::ArchType Arch) {
1986   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1987 }
1988
1989 static bool isMips64(llvm::Triple::ArchType Arch) {
1990   return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1991 }
1992
1993 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1994   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1995 }
1996
1997 static bool isMips16(const ArgList &Args) {
1998   Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1999   return A && A->getOption().matches(options::OPT_mips16);
2000 }
2001
2002 static bool isMicroMips(const ArgList &Args) {
2003   Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
2004   return A && A->getOption().matches(options::OPT_mmicromips);
2005 }
2006
2007 namespace {
2008 struct DetectedMultilibs {
2009   /// The set of multilibs that the detected installation supports.
2010   MultilibSet Multilibs;
2011
2012   /// The primary multilib appropriate for the given flags.
2013   Multilib SelectedMultilib;
2014
2015   /// On Biarch systems, this corresponds to the default multilib when
2016   /// targeting the non-default multilib. Otherwise, it is empty.
2017   llvm::Optional<Multilib> BiarchSibling;
2018 };
2019 } // end anonymous namespace
2020
2021 static Multilib makeMultilib(StringRef commonSuffix) {
2022   return Multilib(commonSuffix, commonSuffix, commonSuffix);
2023 }
2024
2025 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
2026                                 FilterNonExistent &NonExistent,
2027                                 DetectedMultilibs &Result) {
2028   // Check for Code Sourcery toolchain multilibs
2029   MultilibSet CSMipsMultilibs;
2030   {
2031     auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
2032
2033     auto MArchMicroMips =
2034         makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
2035
2036     auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
2037
2038     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
2039
2040     auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
2041
2042     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
2043
2044     auto DefaultFloat =
2045         makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
2046
2047     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
2048
2049     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2050
2051     // Note that this one's osSuffix is ""
2052     auto MAbi64 = makeMultilib("")
2053                       .gccSuffix("/64")
2054                       .includeSuffix("/64")
2055                       .flag("+mabi=n64")
2056                       .flag("-mabi=n32")
2057                       .flag("-m32");
2058
2059     CSMipsMultilibs =
2060         MultilibSet()
2061             .Either(MArchMips16, MArchMicroMips, MArchDefault)
2062             .Maybe(UCLibc)
2063             .Either(SoftFloat, Nan2008, DefaultFloat)
2064             .FilterOut("/micromips/nan2008")
2065             .FilterOut("/mips16/nan2008")
2066             .Either(BigEndian, LittleEndian)
2067             .Maybe(MAbi64)
2068             .FilterOut("/mips16.*/64")
2069             .FilterOut("/micromips.*/64")
2070             .FilterOut(NonExistent)
2071             .setIncludeDirsCallback([](const Multilib &M) {
2072               std::vector<std::string> Dirs({"/include"});
2073               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
2074                 Dirs.push_back(
2075                     "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
2076               else
2077                 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
2078               return Dirs;
2079             });
2080   }
2081
2082   MultilibSet DebianMipsMultilibs;
2083   {
2084     Multilib MAbiN32 =
2085         Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
2086
2087     Multilib M64 = Multilib()
2088                        .gccSuffix("/64")
2089                        .includeSuffix("/64")
2090                        .flag("+m64")
2091                        .flag("-m32")
2092                        .flag("-mabi=n32");
2093
2094     Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
2095
2096     DebianMipsMultilibs =
2097         MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
2098   }
2099
2100   // Sort candidates. Toolchain that best meets the directories tree goes first.
2101   // Then select the first toolchains matches command line flags.
2102   MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
2103   if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
2104     std::iter_swap(Candidates, Candidates + 1);
2105   for (const MultilibSet *Candidate : Candidates) {
2106     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2107       if (Candidate == &DebianMipsMultilibs)
2108         Result.BiarchSibling = Multilib();
2109       Result.Multilibs = *Candidate;
2110       return true;
2111     }
2112   }
2113   return false;
2114 }
2115
2116 static bool findMipsAndroidMultilibs(vfs::FileSystem &VFS, StringRef Path,
2117                                      const Multilib::flags_list &Flags,
2118                                      FilterNonExistent &NonExistent,
2119                                      DetectedMultilibs &Result) {
2120
2121   MultilibSet AndroidMipsMultilibs =
2122       MultilibSet()
2123           .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
2124           .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
2125           .FilterOut(NonExistent);
2126
2127   MultilibSet AndroidMipselMultilibs =
2128       MultilibSet()
2129           .Either(Multilib().flag("+march=mips32"),
2130                   Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
2131                   Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
2132           .FilterOut(NonExistent);
2133
2134   MultilibSet AndroidMips64elMultilibs =
2135       MultilibSet()
2136           .Either(
2137               Multilib().flag("+march=mips64r6"),
2138               Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
2139               Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
2140               Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
2141           .FilterOut(NonExistent);
2142
2143   MultilibSet *MS = &AndroidMipsMultilibs;
2144   if (VFS.exists(Path + "/mips-r6"))
2145     MS = &AndroidMipselMultilibs;
2146   else if (VFS.exists(Path + "/32"))
2147     MS = &AndroidMips64elMultilibs;
2148   if (MS->select(Flags, Result.SelectedMultilib)) {
2149     Result.Multilibs = *MS;
2150     return true;
2151   }
2152   return false;
2153 }
2154
2155 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
2156                                   FilterNonExistent &NonExistent,
2157                                   DetectedMultilibs &Result) {
2158   // Musl toolchain multilibs
2159   MultilibSet MuslMipsMultilibs;
2160   {
2161     auto MArchMipsR2 = makeMultilib("")
2162                            .osSuffix("/mips-r2-hard-musl")
2163                            .flag("+EB")
2164                            .flag("-EL")
2165                            .flag("+march=mips32r2");
2166
2167     auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
2168                              .flag("-EB")
2169                              .flag("+EL")
2170                              .flag("+march=mips32r2");
2171
2172     MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
2173
2174     // Specify the callback that computes the include directories.
2175     MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
2176       return std::vector<std::string>(
2177           {"/../sysroot" + M.osSuffix() + "/usr/include"});
2178     });
2179   }
2180   if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2181     Result.Multilibs = MuslMipsMultilibs;
2182     return true;
2183   }
2184   return false;
2185 }
2186
2187 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
2188                                  FilterNonExistent &NonExistent,
2189                                  DetectedMultilibs &Result) {
2190   // CodeScape MTI toolchain v1.2 and early.
2191   MultilibSet MtiMipsMultilibsV1;
2192   {
2193     auto MArchMips32 = makeMultilib("/mips32")
2194                            .flag("+m32")
2195                            .flag("-m64")
2196                            .flag("-mmicromips")
2197                            .flag("+march=mips32");
2198
2199     auto MArchMicroMips = makeMultilib("/micromips")
2200                               .flag("+m32")
2201                               .flag("-m64")
2202                               .flag("+mmicromips");
2203
2204     auto MArchMips64r2 = makeMultilib("/mips64r2")
2205                              .flag("-m32")
2206                              .flag("+m64")
2207                              .flag("+march=mips64r2");
2208
2209     auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
2210         "-march=mips64r2");
2211
2212     auto MArchDefault = makeMultilib("")
2213                             .flag("+m32")
2214                             .flag("-m64")
2215                             .flag("-mmicromips")
2216                             .flag("+march=mips32r2");
2217
2218     auto Mips16 = makeMultilib("/mips16").flag("+mips16");
2219
2220     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
2221
2222     auto MAbi64 =
2223         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
2224
2225     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
2226
2227     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2228
2229     auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
2230
2231     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
2232
2233     MtiMipsMultilibsV1 =
2234         MultilibSet()
2235             .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
2236                     MArchDefault)
2237             .Maybe(UCLibc)
2238             .Maybe(Mips16)
2239             .FilterOut("/mips64/mips16")
2240             .FilterOut("/mips64r2/mips16")
2241             .FilterOut("/micromips/mips16")
2242             .Maybe(MAbi64)
2243             .FilterOut("/micromips/64")
2244             .FilterOut("/mips32/64")
2245             .FilterOut("^/64")
2246             .FilterOut("/mips16/64")
2247             .Either(BigEndian, LittleEndian)
2248             .Maybe(SoftFloat)
2249             .Maybe(Nan2008)
2250             .FilterOut(".*sof/nan2008")
2251             .FilterOut(NonExistent)
2252             .setIncludeDirsCallback([](const Multilib &M) {
2253               std::vector<std::string> Dirs({"/include"});
2254               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
2255                 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
2256               else
2257                 Dirs.push_back("/../../../../sysroot/usr/include");
2258               return Dirs;
2259             });
2260   }
2261
2262   // CodeScape IMG toolchain starting from v1.3.
2263   MultilibSet MtiMipsMultilibsV2;
2264   {
2265     auto BeHard = makeMultilib("/mips-r2-hard")
2266                       .flag("+EB")
2267                       .flag("-msoft-float")
2268                       .flag("-mnan=2008")
2269                       .flag("-muclibc");
2270     auto BeSoft = makeMultilib("/mips-r2-soft")
2271                       .flag("+EB")
2272                       .flag("+msoft-float")
2273                       .flag("-mnan=2008");
2274     auto ElHard = makeMultilib("/mipsel-r2-hard")
2275                       .flag("+EL")
2276                       .flag("-msoft-float")
2277                       .flag("-mnan=2008")
2278                       .flag("-muclibc");
2279     auto ElSoft = makeMultilib("/mipsel-r2-soft")
2280                       .flag("+EL")
2281                       .flag("+msoft-float")
2282                       .flag("-mnan=2008")
2283                       .flag("-mmicromips");
2284     auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
2285                          .flag("+EB")
2286                          .flag("-msoft-float")
2287                          .flag("+mnan=2008")
2288                          .flag("-muclibc");
2289     auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
2290                          .flag("+EL")
2291                          .flag("-msoft-float")
2292                          .flag("+mnan=2008")
2293                          .flag("-muclibc")
2294                          .flag("-mmicromips");
2295     auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
2296                                .flag("+EB")
2297                                .flag("-msoft-float")
2298                                .flag("+mnan=2008")
2299                                .flag("+muclibc");
2300     auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
2301                                .flag("+EL")
2302                                .flag("-msoft-float")
2303                                .flag("+mnan=2008")
2304                                .flag("+muclibc");
2305     auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
2306                             .flag("+EB")
2307                             .flag("-msoft-float")
2308                             .flag("-mnan=2008")
2309                             .flag("+muclibc");
2310     auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
2311                             .flag("+EL")
2312                             .flag("-msoft-float")
2313                             .flag("-mnan=2008")
2314                             .flag("+muclibc");
2315     auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
2316                               .flag("+EL")
2317                               .flag("-msoft-float")
2318                               .flag("+mnan=2008")
2319                               .flag("+mmicromips");
2320     auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
2321                            .flag("+EL")
2322                            .flag("+msoft-float")
2323                            .flag("-mnan=2008")
2324                            .flag("+mmicromips");
2325
2326     auto O32 =
2327         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
2328     auto N32 =
2329         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
2330     auto N64 =
2331         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
2332
2333     MtiMipsMultilibsV2 =
2334         MultilibSet()
2335             .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
2336                      BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
2337                      ElHardUclibc, ElMicroHardNan, ElMicroSoft})
2338             .Either(O32, N32, N64)
2339             .FilterOut(NonExistent)
2340             .setIncludeDirsCallback([](const Multilib &M) {
2341               return std::vector<std::string>({"/../../../../sysroot" +
2342                                                M.includeSuffix() +
2343                                                "/../usr/include"});
2344             })
2345             .setFilePathsCallback([](const Multilib &M) {
2346               return std::vector<std::string>(
2347                   {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
2348             });
2349   }
2350   for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
2351     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2352       Result.Multilibs = *Candidate;
2353       return true;
2354     }
2355   }
2356   return false;
2357 }
2358
2359 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
2360                                  FilterNonExistent &NonExistent,
2361                                  DetectedMultilibs &Result) {
2362   // CodeScape IMG toolchain v1.2 and early.
2363   MultilibSet ImgMultilibsV1;
2364   {
2365     auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
2366
2367     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
2368
2369     auto MAbi64 =
2370         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
2371
2372     ImgMultilibsV1 =
2373         MultilibSet()
2374             .Maybe(Mips64r6)
2375             .Maybe(MAbi64)
2376             .Maybe(LittleEndian)
2377             .FilterOut(NonExistent)
2378             .setIncludeDirsCallback([](const Multilib &M) {
2379               return std::vector<std::string>(
2380                   {"/include", "/../../../../sysroot/usr/include"});
2381             });
2382   }
2383
2384   // CodeScape IMG toolchain starting from v1.3.
2385   MultilibSet ImgMultilibsV2;
2386   {
2387     auto BeHard = makeMultilib("/mips-r6-hard")
2388                       .flag("+EB")
2389                       .flag("-msoft-float")
2390                       .flag("-mmicromips");
2391     auto BeSoft = makeMultilib("/mips-r6-soft")
2392                       .flag("+EB")
2393                       .flag("+msoft-float")
2394                       .flag("-mmicromips");
2395     auto ElHard = makeMultilib("/mipsel-r6-hard")
2396                       .flag("+EL")
2397                       .flag("-msoft-float")
2398                       .flag("-mmicromips");
2399     auto ElSoft = makeMultilib("/mipsel-r6-soft")
2400                       .flag("+EL")
2401                       .flag("+msoft-float")
2402                       .flag("-mmicromips");
2403     auto BeMicroHard = makeMultilib("/micromips-r6-hard")
2404                            .flag("+EB")
2405                            .flag("-msoft-float")
2406                            .flag("+mmicromips");
2407     auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
2408                            .flag("+EB")
2409                            .flag("+msoft-float")
2410                            .flag("+mmicromips");
2411     auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
2412                            .flag("+EL")
2413                            .flag("-msoft-float")
2414                            .flag("+mmicromips");
2415     auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
2416                            .flag("+EL")
2417                            .flag("+msoft-float")
2418                            .flag("+mmicromips");
2419
2420     auto O32 =
2421         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
2422     auto N32 =
2423         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
2424     auto N64 =
2425         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
2426
2427     ImgMultilibsV2 =
2428         MultilibSet()
2429             .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
2430                      ElMicroHard, ElMicroSoft})
2431             .Either(O32, N32, N64)
2432             .FilterOut(NonExistent)
2433             .setIncludeDirsCallback([](const Multilib &M) {
2434               return std::vector<std::string>({"/../../../../sysroot" +
2435                                                M.includeSuffix() +
2436                                                "/../usr/include"});
2437             })
2438             .setFilePathsCallback([](const Multilib &M) {
2439               return std::vector<std::string>(
2440                   {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
2441             });
2442   }
2443   for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
2444     if (Candidate->select(Flags, Result.SelectedMultilib)) {
2445       Result.Multilibs = *Candidate;
2446       return true;
2447     }
2448   }
2449   return false;
2450 }
2451
2452 static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
2453                               StringRef Path, const ArgList &Args,
2454                               DetectedMultilibs &Result) {
2455   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
2456
2457   StringRef CPUName;
2458   StringRef ABIName;
2459   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
2460
2461   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2462
2463   Multilib::flags_list Flags;
2464   addMultilibFlag(isMips32(TargetArch), "m32", Flags);
2465   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
2466   addMultilibFlag(isMips16(Args), "mips16", Flags);
2467   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
2468   addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
2469                       CPUName == "mips32r5" || CPUName == "p5600",
2470                   "march=mips32r2", Flags);
2471   addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
2472   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
2473   addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
2474                       CPUName == "mips64r5" || CPUName == "octeon",
2475                   "march=mips64r2", Flags);
2476   addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
2477   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
2478   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
2479   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
2480                   Flags);
2481   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
2482   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
2483   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
2484   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
2485   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
2486   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
2487
2488   if (TargetTriple.isAndroid())
2489     return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
2490                                     Result);
2491
2492   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2493       TargetTriple.getOS() == llvm::Triple::Linux &&
2494       TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2495     return findMipsMuslMultilibs(Flags, NonExistent, Result);
2496
2497   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2498       TargetTriple.getOS() == llvm::Triple::Linux &&
2499       TargetTriple.getEnvironment() == llvm::Triple::GNU)
2500     return findMipsMtiMultilibs(Flags, NonExistent, Result);
2501
2502   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
2503       TargetTriple.getOS() == llvm::Triple::Linux &&
2504       TargetTriple.getEnvironment() == llvm::Triple::GNU)
2505     return findMipsImgMultilibs(Flags, NonExistent, Result);
2506
2507   if (findMipsCsMultilibs(Flags, NonExistent, Result))
2508     return true;
2509
2510   // Fallback to the regular toolchain-tree structure.
2511   Multilib Default;
2512   Result.Multilibs.push_back(Default);
2513   Result.Multilibs.FilterOut(NonExistent);
2514
2515   if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
2516     Result.BiarchSibling = Multilib();
2517     return true;
2518   }
2519
2520   return false;
2521 }
2522
2523 static void findAndroidArmMultilibs(const Driver &D,
2524                                     const llvm::Triple &TargetTriple,
2525                                     StringRef Path, const ArgList &Args,
2526                                     DetectedMultilibs &Result) {
2527   // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
2528   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
2529   Multilib ArmV7Multilib = makeMultilib("/armv7-a")
2530                                .flag("+armv7")
2531                                .flag("-thumb");
2532   Multilib ThumbMultilib = makeMultilib("/thumb")
2533                                .flag("-armv7")
2534                                .flag("+thumb");
2535   Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
2536                                .flag("+armv7")
2537                                .flag("+thumb");
2538   Multilib DefaultMultilib = makeMultilib("")
2539                                .flag("-armv7")
2540                                .flag("-thumb");
2541   MultilibSet AndroidArmMultilibs =
2542       MultilibSet()
2543           .Either(ThumbMultilib, ArmV7Multilib,
2544                   ArmV7ThumbMultilib, DefaultMultilib)
2545           .FilterOut(NonExistent);
2546
2547   Multilib::flags_list Flags;
2548   llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
2549   bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
2550   bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
2551   bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
2552   bool IsThumbMode = IsThumbArch ||
2553       Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
2554       (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::IK_THUMB);
2555   bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
2556       (llvm::ARM::parseArchVersion(Arch) == 7 ||
2557        (IsArmArch && Arch == "" && IsV7SubArch));
2558   addMultilibFlag(IsArmV7Mode, "armv7", Flags);
2559   addMultilibFlag(IsThumbMode, "thumb", Flags);
2560
2561   if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
2562     Result.Multilibs = AndroidArmMultilibs;
2563 }
2564
2565 static bool findBiarchMultilibs(const Driver &D,
2566                                 const llvm::Triple &TargetTriple,
2567                                 StringRef Path, const ArgList &Args,
2568                                 bool NeedsBiarchSuffix,
2569                                 DetectedMultilibs &Result) {
2570   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
2571   // in what would normally be GCCInstallPath and put the 64-bit
2572   // libs in a subdirectory named 64. The simple logic we follow is that
2573   // *if* there is a subdirectory of the right name with crtbegin.o in it,
2574   // we use that. If not, and if not a biarch triple alias, we look for
2575   // crtbegin.o without the subdirectory.
2576
2577   Multilib Default;
2578   Multilib Alt64 = Multilib()
2579                        .gccSuffix("/64")
2580                        .includeSuffix("/64")
2581                        .flag("-m32")
2582                        .flag("+m64")
2583                        .flag("-mx32");
2584   Multilib Alt32 = Multilib()
2585                        .gccSuffix("/32")
2586                        .includeSuffix("/32")
2587                        .flag("+m32")
2588                        .flag("-m64")
2589                        .flag("-mx32");
2590   Multilib Altx32 = Multilib()
2591                         .gccSuffix("/x32")
2592                         .includeSuffix("/x32")
2593                         .flag("-m32")
2594                         .flag("-m64")
2595                         .flag("+mx32");
2596
2597   // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
2598   FilterNonExistent NonExistent(
2599       Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
2600
2601   // Determine default multilib from: 32, 64, x32
2602   // Also handle cases such as 64 on 32, 32 on 64, etc.
2603   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2604   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
2605   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2606     Want = WANT64;
2607   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2608     Want = WANT64;
2609   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2610     Want = WANT32;
2611   else {
2612     if (TargetTriple.isArch32Bit())
2613       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2614     else if (IsX32)
2615       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2616     else
2617       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2618   }
2619
2620   if (Want == WANT32)
2621     Default.flag("+m32").flag("-m64").flag("-mx32");
2622   else if (Want == WANT64)
2623     Default.flag("-m32").flag("+m64").flag("-mx32");
2624   else if (Want == WANTX32)
2625     Default.flag("-m32").flag("-m64").flag("+mx32");
2626   else
2627     return false;
2628
2629   Result.Multilibs.push_back(Default);
2630   Result.Multilibs.push_back(Alt64);
2631   Result.Multilibs.push_back(Alt32);
2632   Result.Multilibs.push_back(Altx32);
2633
2634   Result.Multilibs.FilterOut(NonExistent);
2635
2636   Multilib::flags_list Flags;
2637   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
2638   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
2639   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
2640
2641   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
2642     return false;
2643
2644   if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
2645       Result.SelectedMultilib == Altx32)
2646     Result.BiarchSibling = Default;
2647
2648   return true;
2649 }
2650
2651 void Generic_GCC::GCCInstallationDetector::scanLibDirForGCCTripleSolaris(
2652     const llvm::Triple &TargetArch, const llvm::opt::ArgList &Args,
2653     const std::string &LibDir, StringRef CandidateTriple,
2654     bool NeedsBiarchSuffix) {
2655   // Solaris is a special case. The GCC installation is under
2656   // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/, so we
2657   // need to iterate twice.
2658   std::error_code EC;
2659   for (vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir, EC), LE;
2660        !EC && LI != LE; LI = LI.increment(EC)) {
2661     StringRef VersionText = llvm::sys::path::filename(LI->getName());
2662     GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2663
2664     if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2665       if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2666         continue; // Saw this path before; no need to look at it again.
2667     if (CandidateVersion.isOlderThan(4, 1, 1))
2668       continue;
2669     if (CandidateVersion <= Version)
2670       continue;
2671
2672     GCCInstallPath =
2673         LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str();
2674     if (!D.getVFS().exists(GCCInstallPath))
2675       continue;
2676
2677     // If we make it here there has to be at least one GCC version, let's just
2678     // use the latest one.
2679     std::error_code EEC;
2680     for (vfs::directory_iterator
2681              LLI = D.getVFS().dir_begin(GCCInstallPath, EEC),
2682              LLE;
2683          !EEC && LLI != LLE; LLI = LLI.increment(EEC)) {
2684
2685       StringRef SubVersionText = llvm::sys::path::filename(LLI->getName());
2686       GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText);
2687
2688       if (CandidateSubVersion > Version)
2689         Version = CandidateSubVersion;
2690     }
2691
2692     GCCTriple.setTriple(CandidateTriple);
2693
2694     GCCInstallPath += "/" + Version.Text;
2695     GCCParentLibPath = GCCInstallPath + "/../../../../";
2696
2697     IsValid = true;
2698   }
2699 }
2700
2701 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2702     const llvm::Triple &TargetTriple, const ArgList &Args,
2703     StringRef Path, bool NeedsBiarchSuffix) {
2704   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2705   DetectedMultilibs Detected;
2706
2707   // Android standalone toolchain could have multilibs for ARM and Thumb.
2708   // Debian mips multilibs behave more like the rest of the biarch ones,
2709   // so handle them there
2710   if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2711     // It should also work without multilibs in a simplified toolchain.
2712     findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2713   } else if (isMipsArch(TargetArch)) {
2714     if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2715       return false;
2716   } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2717                                   NeedsBiarchSuffix, Detected)) {
2718     return false;
2719   }
2720
2721   Multilibs = Detected.Multilibs;
2722   SelectedMultilib = Detected.SelectedMultilib;
2723   BiarchSibling = Detected.BiarchSibling;
2724
2725   return true;
2726 }
2727
2728 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2729     const llvm::Triple &TargetTriple, const ArgList &Args,
2730     const std::string &LibDir, StringRef CandidateTriple,
2731     bool NeedsBiarchSuffix) {
2732   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2733   // There are various different suffixes involving the triple we
2734   // check for. We also record what is necessary to walk from each back
2735   // up to the lib directory. Specifically, the number of "up" steps
2736   // in the second half of each row is 1 + the number of path separators
2737   // in the first half.
2738   const std::string LibAndInstallSuffixes[][2] = {
2739       {"/gcc/" + CandidateTriple.str(), "/../../.."},
2740
2741       // Debian puts cross-compilers in gcc-cross
2742       {"/gcc-cross/" + CandidateTriple.str(), "/../../.."},
2743
2744       {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
2745        "/../../../.."},
2746
2747       // The Freescale PPC SDK has the gcc libraries in
2748       // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
2749       {"/" + CandidateTriple.str(), "/../.."},
2750
2751       // Ubuntu has a strange mis-matched pair of triples that this happens to
2752       // match.
2753       // FIXME: It may be worthwhile to generalize this and look for a second
2754       // triple.
2755       {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}};
2756
2757   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2758     scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple,
2759                                   NeedsBiarchSuffix);
2760     return;
2761   }
2762
2763   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
2764   const unsigned NumLibSuffixes = (llvm::array_lengthof(LibAndInstallSuffixes) -
2765                                    (TargetArch != llvm::Triple::x86));
2766   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
2767     StringRef LibSuffix = LibAndInstallSuffixes[i][0];
2768     std::error_code EC;
2769     for (vfs::directory_iterator
2770              LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC),
2771              LE;
2772          !EC && LI != LE; LI = LI.increment(EC)) {
2773       StringRef VersionText = llvm::sys::path::filename(LI->getName());
2774       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2775       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2776         if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2777           continue; // Saw this path before; no need to look at it again.
2778       if (CandidateVersion.isOlderThan(4, 1, 1))
2779         continue;
2780       if (CandidateVersion <= Version)
2781         continue;
2782
2783       if (!ScanGCCForMultilibs(TargetTriple, Args, LI->getName(),
2784                                NeedsBiarchSuffix))
2785         continue;
2786
2787       Version = CandidateVersion;
2788       GCCTriple.setTriple(CandidateTriple);
2789       // FIXME: We hack together the directory name here instead of
2790       // using LI to ensure stable path separators across Windows and
2791       // Linux.
2792       GCCInstallPath =
2793           LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str();
2794       GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1];
2795       IsValid = true;
2796     }
2797   }
2798 }
2799
2800 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2801     const llvm::Triple &TargetTriple, const ArgList &Args,
2802     StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2803   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2804       D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
2805                                   CandidateTriple.str());
2806   if (File) {
2807     SmallVector<StringRef, 2> Lines;
2808     File.get()->getBuffer().split(Lines, "\n");
2809     for (StringRef Line : Lines) {
2810       // CURRENT=triple-version
2811       if (Line.consume_front("CURRENT=")) {
2812         const std::pair<StringRef, StringRef> ActiveVersion =
2813           Line.rsplit('-');
2814         // Note: Strictly speaking, we should be reading
2815         // /etc/env.d/gcc/${CURRENT} now. However, the file doesn't
2816         // contain anything new or especially useful to us.
2817         const std::string GentooPath = D.SysRoot + "/usr/lib/gcc/" +
2818                                        ActiveVersion.first.str() + "/" +
2819                                        ActiveVersion.second.str();
2820         if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2821           if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2822                                    NeedsBiarchSuffix))
2823             return false;
2824
2825           Version = GCCVersion::Parse(ActiveVersion.second);
2826           GCCInstallPath = GentooPath;
2827           GCCParentLibPath = GentooPath + "/../../..";
2828           GCCTriple.setTriple(ActiveVersion.first);
2829           IsValid = true;
2830           return true;
2831         }
2832       }
2833     }
2834   }
2835
2836   return false;
2837 }
2838
2839 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2840                          const ArgList &Args)
2841     : ToolChain(D, Triple, Args), GCCInstallation(D),
2842       CudaInstallation(D, Triple, Args) {
2843   getProgramPaths().push_back(getDriver().getInstalledDir());
2844   if (getDriver().getInstalledDir() != getDriver().Dir)
2845     getProgramPaths().push_back(getDriver().Dir);
2846 }
2847
2848 Generic_GCC::~Generic_GCC() {}
2849
2850 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2851   switch (AC) {
2852   case Action::PreprocessJobClass:
2853     if (!Preprocess)
2854       Preprocess.reset(new tools::gcc::Preprocessor(*this));
2855     return Preprocess.get();
2856   case Action::CompileJobClass:
2857     if (!Compile)
2858       Compile.reset(new tools::gcc::Compiler(*this));
2859     return Compile.get();
2860   default:
2861     return ToolChain::getTool(AC);
2862   }
2863 }
2864
2865 Tool *Generic_GCC::buildAssembler() const {
2866   return new tools::gnutools::Assembler(*this);
2867 }
2868
2869 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2870
2871 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2872   // Print the information about how we detected the GCC installation.
2873   GCCInstallation.print(OS);
2874   CudaInstallation.print(OS);
2875 }
2876
2877 bool Generic_GCC::IsUnwindTablesDefault() const {
2878   return getArch() == llvm::Triple::x86_64;
2879 }
2880
2881 bool Generic_GCC::isPICDefault() const {
2882   switch (getArch()) {
2883   case llvm::Triple::x86_64:
2884     return getTriple().isOSWindows();
2885   case llvm::Triple::ppc64:
2886   case llvm::Triple::ppc64le:
2887     return !getTriple().isOSBinFormatMachO() && !getTriple().isMacOSX();
2888   default:
2889     return false;
2890   }
2891 }
2892
2893 bool Generic_GCC::isPIEDefault() const { return false; }
2894
2895 bool Generic_GCC::isPICDefaultForced() const {
2896   return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2897 }
2898
2899 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2900   switch (getTriple().getArch()) {
2901   case llvm::Triple::x86:
2902   case llvm::Triple::x86_64:
2903   case llvm::Triple::aarch64:
2904   case llvm::Triple::aarch64_be:
2905   case llvm::Triple::arm:
2906   case llvm::Triple::armeb:
2907   case llvm::Triple::bpfel:
2908   case llvm::Triple::bpfeb:
2909   case llvm::Triple::thumb:
2910   case llvm::Triple::thumbeb:
2911   case llvm::Triple::ppc:
2912   case llvm::Triple::ppc64:
2913   case llvm::Triple::ppc64le:
2914   case llvm::Triple::systemz:
2915   case llvm::Triple::mips:
2916   case llvm::Triple::mipsel:
2917     return true;
2918   case llvm::Triple::mips64:
2919   case llvm::Triple::mips64el:
2920     // Enabled for Debian mips64/mips64el only. Other targets are unable to
2921     // distinguish N32 from N64.
2922     if (getTriple().getEnvironment() == llvm::Triple::GNUABI64)
2923       return true;
2924     return false;
2925   default:
2926     return false;
2927   }
2928 }
2929
2930 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2931                                                ArgStringList &CC1Args) const {
2932   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2933       DriverArgs.hasArg(options::OPT_nostdincxx))
2934     return;
2935
2936   switch (GetCXXStdlibType(DriverArgs)) {
2937   case ToolChain::CST_Libcxx: {
2938     std::string Path = findLibCxxIncludePath();
2939     if (!Path.empty())
2940       addSystemInclude(DriverArgs, CC1Args, Path);
2941     break;
2942   }
2943
2944   case ToolChain::CST_Libstdcxx:
2945     addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2946     break;
2947   }
2948 }
2949
2950 std::string Generic_GCC::findLibCxxIncludePath() const {
2951   // FIXME: The Linux behavior would probaby be a better approach here.
2952   return getDriver().SysRoot + "/usr/include/c++/v1";
2953 }
2954
2955 void
2956 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2957                                       llvm::opt::ArgStringList &CC1Args) const {
2958   // By default, we don't assume we know where libstdc++ might be installed.
2959   // FIXME: If we have a valid GCCInstallation, use it.
2960 }
2961
2962 /// \brief Helper to add the variant paths of a libstdc++ installation.
2963 bool Generic_GCC::addLibStdCXXIncludePaths(
2964     Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2965     StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2966     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2967   if (!getVFS().exists(Base + Suffix))
2968     return false;
2969
2970   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2971
2972   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2973   // that path exists or we have neither a GCC nor target multiarch triple, use
2974   // this vanilla search path.
2975   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2976       getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2977     addSystemInclude(DriverArgs, CC1Args,
2978                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2979   } else {
2980     // Otherwise try to use multiarch naming schemes which have normalized the
2981     // triples and put the triple before the suffix.
2982     //
2983     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2984     // the target triple, so we support that here.
2985     addSystemInclude(DriverArgs, CC1Args,
2986                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2987     addSystemInclude(DriverArgs, CC1Args,
2988                      Base + "/" + TargetMultiarchTriple + Suffix);
2989   }
2990
2991   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2992   return true;
2993 }
2994
2995 llvm::opt::DerivedArgList *
2996 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
2997                            Action::OffloadKind DeviceOffloadKind) const {
2998
2999   // If this tool chain is used for an OpenMP offloading device we have to make
3000   // sure we always generate a shared library regardless of the commands the
3001   // user passed to the host. This is required because the runtime library
3002   // is required to load the device image dynamically at run time.
3003   if (DeviceOffloadKind == Action::OFK_OpenMP) {
3004     DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3005     const OptTable &Opts = getDriver().getOpts();
3006
3007     // Request the shared library. Given that these options are decided
3008     // implicitly, they do not refer to any base argument.
3009     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3010     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3011
3012     // Filter all the arguments we don't care passing to the offloading
3013     // toolchain as they can mess up with the creation of a shared library.
3014     for (auto *A : Args) {
3015       switch ((options::ID)A->getOption().getID()) {
3016       default:
3017         DAL->append(A);
3018         break;
3019       case options::OPT_shared:
3020       case options::OPT_dynamic:
3021       case options::OPT_static:
3022       case options::OPT_fPIC:
3023       case options::OPT_fno_PIC:
3024       case options::OPT_fpic:
3025       case options::OPT_fno_pic:
3026       case options::OPT_fPIE:
3027       case options::OPT_fno_PIE:
3028       case options::OPT_fpie:
3029       case options::OPT_fno_pie:
3030         break;
3031       }
3032     }
3033     return DAL;
3034   }
3035   return nullptr;
3036 }
3037
3038 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3039                                         ArgStringList &CC1Args) const {
3040   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
3041   bool UseInitArrayDefault =
3042       getTriple().getArch() == llvm::Triple::aarch64 ||
3043       getTriple().getArch() == llvm::Triple::aarch64_be ||
3044       (getTriple().getOS() == llvm::Triple::Linux &&
3045        (!V.isOlderThan(4, 7, 0) || getTriple().isAndroid())) ||
3046       getTriple().getOS() == llvm::Triple::NaCl ||
3047       (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
3048        !getTriple().hasEnvironment());
3049
3050   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
3051                          options::OPT_fno_use_init_array, UseInitArrayDefault))
3052     CC1Args.push_back("-fuse-init-array");
3053 }
3054
3055 /// Mips Toolchain
3056 MipsLLVMToolChain::MipsLLVMToolChain(const Driver &D,
3057                                      const llvm::Triple &Triple,
3058                                      const ArgList &Args)
3059     : Linux(D, Triple, Args) {
3060   // Select the correct multilib according to the given arguments.
3061   DetectedMultilibs Result;
3062   findMIPSMultilibs(D, Triple, "", Args, Result);
3063   Multilibs = Result.Multilibs;
3064   SelectedMultilib = Result.SelectedMultilib;
3065
3066   // Find out the library suffix based on the ABI.
3067   LibSuffix = tools::mips::getMipsABILibSuffix(Args, Triple);
3068   getFilePaths().clear();
3069   getFilePaths().push_back(computeSysRoot() + "/usr/lib" + LibSuffix);
3070 }
3071
3072 void MipsLLVMToolChain::AddClangSystemIncludeArgs(
3073     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
3074   if (DriverArgs.hasArg(options::OPT_nostdinc))
3075     return;
3076
3077   const Driver &D = getDriver();
3078
3079   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3080     SmallString<128> P(D.ResourceDir);
3081     llvm::sys::path::append(P, "include");
3082     addSystemInclude(DriverArgs, CC1Args, P);
3083   }
3084
3085   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3086     return;
3087
3088   const auto &Callback = Multilibs.includeDirsCallback();
3089   if (Callback) {
3090     for (const auto &Path : Callback(SelectedMultilib))
3091       addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3092                                       D.getInstalledDir() + Path);
3093   }
3094 }
3095
3096 Tool *MipsLLVMToolChain::buildLinker() const {
3097   return new tools::gnutools::Linker(*this);
3098 }
3099
3100 std::string MipsLLVMToolChain::computeSysRoot() const {
3101   if (!getDriver().SysRoot.empty())
3102     return getDriver().SysRoot + SelectedMultilib.osSuffix();
3103
3104   const std::string InstalledDir(getDriver().getInstalledDir());
3105   std::string SysRootPath =
3106       InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix();
3107   if (llvm::sys::fs::exists(SysRootPath))
3108     return SysRootPath;
3109
3110   return std::string();
3111 }
3112
3113 ToolChain::CXXStdlibType
3114 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const {
3115   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
3116   if (A) {
3117     StringRef Value = A->getValue();
3118     if (Value != "libc++")
3119       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
3120           << A->getAsString(Args);
3121   }
3122
3123   return ToolChain::CST_Libcxx;
3124 }
3125
3126 std::string MipsLLVMToolChain::findLibCxxIncludePath() const {
3127   if (const auto &Callback = Multilibs.includeDirsCallback()) {
3128     for (std::string Path : Callback(SelectedMultilib)) {
3129       Path = getDriver().getInstalledDir() + Path + "/c++/v1";
3130       if (llvm::sys::fs::exists(Path)) {
3131         return Path;
3132       }
3133     }
3134   }
3135   return "";
3136 }
3137
3138 void MipsLLVMToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
3139                                             ArgStringList &CmdArgs) const {
3140   assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) &&
3141          "Only -lc++ (aka libxx) is suported in this toolchain.");
3142
3143   CmdArgs.push_back("-lc++");
3144   CmdArgs.push_back("-lc++abi");
3145   CmdArgs.push_back("-lunwind");
3146 }
3147
3148 std::string MipsLLVMToolChain::getCompilerRT(const ArgList &Args,
3149                                              StringRef Component,
3150                                              bool Shared) const {
3151   SmallString<128> Path(getDriver().ResourceDir);
3152   llvm::sys::path::append(Path, SelectedMultilib.osSuffix(), "lib" + LibSuffix,
3153                           getOS());
3154   llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" +
3155                                       "mips" + (Shared ? ".so" : ".a")));
3156   return Path.str();
3157 }
3158
3159 /// Hexagon Toolchain
3160
3161 std::string HexagonToolChain::getHexagonTargetDir(
3162       const std::string &InstalledDir,
3163       const SmallVectorImpl<std::string> &PrefixDirs) const {
3164   std::string InstallRelDir;
3165   const Driver &D = getDriver();
3166
3167   // Locate the rest of the toolchain ...
3168   for (auto &I : PrefixDirs)
3169     if (D.getVFS().exists(I))
3170       return I;
3171
3172   if (getVFS().exists(InstallRelDir = InstalledDir + "/../target"))
3173     return InstallRelDir;
3174
3175   return InstalledDir;
3176 }
3177
3178 Optional<unsigned> HexagonToolChain::getSmallDataThreshold(
3179       const ArgList &Args) {
3180   StringRef Gn = "";
3181   if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
3182                                options::OPT_msmall_data_threshold_EQ)) {
3183     Gn = A->getValue();
3184   } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
3185                              options::OPT_fPIC)) {
3186     Gn = "0";
3187   }
3188
3189   unsigned G;
3190   if (!Gn.getAsInteger(10, G))
3191     return G;
3192
3193   return None;
3194 }
3195
3196 void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args,
3197       ToolChain::path_list &LibPaths) const {
3198   const Driver &D = getDriver();
3199
3200   //----------------------------------------------------------------------------
3201   // -L Args
3202   //----------------------------------------------------------------------------
3203   for (Arg *A : Args.filtered(options::OPT_L))
3204     for (const char *Value : A->getValues())
3205       LibPaths.push_back(Value);
3206
3207   //----------------------------------------------------------------------------
3208   // Other standard paths
3209   //----------------------------------------------------------------------------
3210   std::vector<std::string> RootDirs;
3211   std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(),
3212             std::back_inserter(RootDirs));
3213
3214   std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3215                                               D.PrefixDirs);
3216   if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end())
3217     RootDirs.push_back(TargetDir);
3218
3219   bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC);
3220   // Assume G0 with -shared.
3221   bool HasG0 = Args.hasArg(options::OPT_shared);
3222   if (auto G = getSmallDataThreshold(Args))
3223     HasG0 = G.getValue() == 0;
3224
3225   const std::string CpuVer = GetTargetCPUVersion(Args).str();
3226   for (auto &Dir : RootDirs) {
3227     std::string LibDir = Dir + "/hexagon/lib";
3228     std::string LibDirCpu = LibDir + '/' + CpuVer;
3229     if (HasG0) {
3230       if (HasPIC)
3231         LibPaths.push_back(LibDirCpu + "/G0/pic");
3232       LibPaths.push_back(LibDirCpu + "/G0");
3233     }
3234     LibPaths.push_back(LibDirCpu);
3235     LibPaths.push_back(LibDir);
3236   }
3237 }
3238
3239 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
3240                                    const llvm::opt::ArgList &Args)
3241     : Linux(D, Triple, Args) {
3242   const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3243                                                     D.PrefixDirs);
3244
3245   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
3246   // program paths
3247   const std::string BinDir(TargetDir + "/bin");
3248   if (D.getVFS().exists(BinDir))
3249     getProgramPaths().push_back(BinDir);
3250
3251   ToolChain::path_list &LibPaths = getFilePaths();
3252
3253   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
3254   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
3255   // support 'linux' we'll need to fix this up
3256   LibPaths.clear();
3257   getHexagonLibraryPaths(Args, LibPaths);
3258 }
3259
3260 HexagonToolChain::~HexagonToolChain() {}
3261
3262 Tool *HexagonToolChain::buildAssembler() const {
3263   return new tools::hexagon::Assembler(*this);
3264 }
3265
3266 Tool *HexagonToolChain::buildLinker() const {
3267   return new tools::hexagon::Linker(*this);
3268 }
3269
3270 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3271                                                  ArgStringList &CC1Args) const {
3272   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3273       DriverArgs.hasArg(options::OPT_nostdlibinc))
3274     return;
3275
3276   const Driver &D = getDriver();
3277   std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
3278                                               D.PrefixDirs);
3279   addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include");
3280 }
3281
3282
3283 void HexagonToolChain::addLibStdCxxIncludePaths(
3284     const llvm::opt::ArgList &DriverArgs,
3285     llvm::opt::ArgStringList &CC1Args) const {
3286   const Driver &D = getDriver();
3287   std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs);
3288   addLibStdCXXIncludePaths(TargetDir, "/hexagon/include/c++", "", "", "", "",
3289                            DriverArgs, CC1Args);
3290 }
3291
3292 ToolChain::CXXStdlibType
3293 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
3294   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
3295   if (!A)
3296     return ToolChain::CST_Libstdcxx;
3297
3298   StringRef Value = A->getValue();
3299   if (Value != "libstdc++")
3300     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3301
3302   return ToolChain::CST_Libstdcxx;
3303 }
3304
3305 //
3306 // Returns the default CPU for Hexagon. This is the default compilation target
3307 // if no Hexagon processor is selected at the command-line.
3308 //
3309 const StringRef HexagonToolChain::GetDefaultCPU() {
3310   return "hexagonv60";
3311 }
3312
3313 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
3314   Arg *CpuArg = nullptr;
3315   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ, options::OPT_march_EQ))
3316     CpuArg = A;
3317
3318   StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
3319   if (CPU.startswith("hexagon"))
3320     return CPU.substr(sizeof("hexagon") - 1);
3321   return CPU;
3322 }
3323 // End Hexagon
3324
3325 /// AMDGPU Toolchain
3326 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
3327                                  const ArgList &Args)
3328   : Generic_ELF(D, Triple, Args) { }
3329
3330 Tool *AMDGPUToolChain::buildLinker() const {
3331   return new tools::amdgpu::Linker(*this);
3332 }
3333 // End AMDGPU
3334
3335 /// NaCl Toolchain
3336 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple,
3337                              const ArgList &Args)
3338     : Generic_ELF(D, Triple, Args) {
3339
3340   // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
3341   // default paths, and must instead only use the paths provided
3342   // with this toolchain based on architecture.
3343   path_list &file_paths = getFilePaths();
3344   path_list &prog_paths = getProgramPaths();
3345
3346   file_paths.clear();
3347   prog_paths.clear();
3348
3349   // Path for library files (libc.a, ...)
3350   std::string FilePath(getDriver().Dir + "/../");
3351
3352   // Path for tools (clang, ld, etc..)
3353   std::string ProgPath(getDriver().Dir + "/../");
3354
3355   // Path for toolchain libraries (libgcc.a, ...)
3356   std::string ToolPath(getDriver().ResourceDir + "/lib/");
3357
3358   switch (Triple.getArch()) {
3359   case llvm::Triple::x86:
3360     file_paths.push_back(FilePath + "x86_64-nacl/lib32");
3361     file_paths.push_back(FilePath + "i686-nacl/usr/lib");
3362     prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
3363     file_paths.push_back(ToolPath + "i686-nacl");
3364     break;
3365   case llvm::Triple::x86_64:
3366     file_paths.push_back(FilePath + "x86_64-nacl/lib");
3367     file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
3368     prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
3369     file_paths.push_back(ToolPath + "x86_64-nacl");
3370     break;
3371   case llvm::Triple::arm:
3372     file_paths.push_back(FilePath + "arm-nacl/lib");
3373     file_paths.push_back(FilePath + "arm-nacl/usr/lib");
3374     prog_paths.push_back(ProgPath + "arm-nacl/bin");
3375     file_paths.push_back(ToolPath + "arm-nacl");
3376     break;
3377   case llvm::Triple::mipsel:
3378     file_paths.push_back(FilePath + "mipsel-nacl/lib");
3379     file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
3380     prog_paths.push_back(ProgPath + "bin");
3381     file_paths.push_back(ToolPath + "mipsel-nacl");
3382     break;
3383   default:
3384     break;
3385   }
3386
3387   NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
3388 }
3389
3390 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3391                                               ArgStringList &CC1Args) const {
3392   const Driver &D = getDriver();
3393   if (DriverArgs.hasArg(options::OPT_nostdinc))
3394     return;
3395
3396   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3397     SmallString<128> P(D.ResourceDir);
3398     llvm::sys::path::append(P, "include");
3399     addSystemInclude(DriverArgs, CC1Args, P.str());
3400   }
3401
3402   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3403     return;
3404
3405   SmallString<128> P(D.Dir + "/../");
3406   switch (getTriple().getArch()) {
3407   case llvm::Triple::x86:
3408     // x86 is special because multilib style uses x86_64-nacl/include for libc
3409     // headers but the SDK wants i686-nacl/usr/include. The other architectures
3410     // have the same substring.
3411     llvm::sys::path::append(P, "i686-nacl/usr/include");
3412     addSystemInclude(DriverArgs, CC1Args, P.str());
3413     llvm::sys::path::remove_filename(P);
3414     llvm::sys::path::remove_filename(P);
3415     llvm::sys::path::remove_filename(P);
3416     llvm::sys::path::append(P, "x86_64-nacl/include");
3417     addSystemInclude(DriverArgs, CC1Args, P.str());
3418     return;
3419   case llvm::Triple::arm:
3420     llvm::sys::path::append(P, "arm-nacl/usr/include");
3421     break;
3422   case llvm::Triple::x86_64:
3423     llvm::sys::path::append(P, "x86_64-nacl/usr/include");
3424     break;
3425   case llvm::Triple::mipsel:
3426     llvm::sys::path::append(P, "mipsel-nacl/usr/include");
3427     break;
3428   default:
3429     return;
3430   }
3431
3432   addSystemInclude(DriverArgs, CC1Args, P.str());
3433   llvm::sys::path::remove_filename(P);
3434   llvm::sys::path::remove_filename(P);
3435   llvm::sys::path::append(P, "include");
3436   addSystemInclude(DriverArgs, CC1Args, P.str());
3437 }
3438
3439 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
3440                                         ArgStringList &CmdArgs) const {
3441   // Check for -stdlib= flags. We only support libc++ but this consumes the arg
3442   // if the value is libc++, and emits an error for other values.
3443   GetCXXStdlibType(Args);
3444   CmdArgs.push_back("-lc++");
3445 }
3446
3447 std::string NaClToolChain::findLibCxxIncludePath() const {
3448   const Driver &D = getDriver();
3449
3450   SmallString<128> P(D.Dir + "/../");
3451   switch (getTriple().getArch()) {
3452   case llvm::Triple::arm:
3453     llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
3454     return P.str();
3455   case llvm::Triple::x86:
3456     llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
3457     return P.str();
3458   case llvm::Triple::x86_64:
3459     llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
3460     return P.str();
3461   case llvm::Triple::mipsel:
3462     llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
3463     return P.str();
3464   default:
3465     return "";
3466   }
3467 }
3468
3469 ToolChain::CXXStdlibType
3470 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const {
3471   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3472     StringRef Value = A->getValue();
3473     if (Value == "libc++")
3474       return ToolChain::CST_Libcxx;
3475     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3476   }
3477
3478   return ToolChain::CST_Libcxx;
3479 }
3480
3481 std::string
3482 NaClToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
3483                                            types::ID InputType) const {
3484   llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
3485   if (TheTriple.getArch() == llvm::Triple::arm &&
3486       TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
3487     TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
3488   return TheTriple.getTriple();
3489 }
3490
3491 Tool *NaClToolChain::buildLinker() const {
3492   return new tools::nacltools::Linker(*this);
3493 }
3494
3495 Tool *NaClToolChain::buildAssembler() const {
3496   if (getTriple().getArch() == llvm::Triple::arm)
3497     return new tools::nacltools::AssemblerARM(*this);
3498   return new tools::gnutools::Assembler(*this);
3499 }
3500 // End NaCl
3501
3502 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
3503 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
3504 /// Currently does not support anything else but compilation.
3505
3506 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
3507                            const ArgList &Args)
3508     : ToolChain(D, Triple, Args) {
3509   // Path mangling to find libexec
3510   std::string Path(getDriver().Dir);
3511
3512   Path += "/../libexec";
3513   getProgramPaths().push_back(Path);
3514 }
3515
3516 TCEToolChain::~TCEToolChain() {}
3517
3518 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
3519
3520 bool TCEToolChain::isPICDefault() const { return false; }
3521
3522 bool TCEToolChain::isPIEDefault() const { return false; }
3523
3524 bool TCEToolChain::isPICDefaultForced() const { return false; }
3525
3526 TCELEToolChain::TCELEToolChain(const Driver &D, const llvm::Triple& Triple,
3527                                const ArgList &Args)
3528   : TCEToolChain(D, Triple, Args) {
3529 }
3530
3531 TCELEToolChain::~TCELEToolChain() {}
3532
3533 // CloudABI - CloudABI tool chain which can call ld(1) directly.
3534
3535 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
3536                    const ArgList &Args)
3537     : Generic_ELF(D, Triple, Args) {
3538   SmallString<128> P(getDriver().Dir);
3539   llvm::sys::path::append(P, "..", getTriple().str(), "lib");
3540   getFilePaths().push_back(P.str());
3541 }
3542
3543 std::string CloudABI::findLibCxxIncludePath() const {
3544   SmallString<128> P(getDriver().Dir);
3545   llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
3546   return P.str();
3547 }
3548
3549 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
3550                                    ArgStringList &CmdArgs) const {
3551   CmdArgs.push_back("-lc++");
3552   CmdArgs.push_back("-lc++abi");
3553   CmdArgs.push_back("-lunwind");
3554 }
3555
3556 Tool *CloudABI::buildLinker() const {
3557   return new tools::cloudabi::Linker(*this);
3558 }
3559
3560 bool CloudABI::isPIEDefault() const {
3561   // Only enable PIE on architectures that support PC-relative
3562   // addressing. PC-relative addressing is required, as the process
3563   // startup code must be able to relocate itself.
3564   switch (getTriple().getArch()) {
3565   case llvm::Triple::aarch64:
3566   case llvm::Triple::x86_64:
3567     return true;
3568   default:
3569     return false;
3570   }
3571 }
3572
3573 SanitizerMask CloudABI::getSupportedSanitizers() const {
3574   SanitizerMask Res = ToolChain::getSupportedSanitizers();
3575   Res |= SanitizerKind::SafeStack;
3576   return Res;
3577 }
3578
3579 SanitizerMask CloudABI::getDefaultSanitizers() const {
3580   return SanitizerKind::SafeStack;
3581 }
3582
3583 /// Haiku - Haiku tool chain which can call as(1) and ld(1) directly.
3584
3585 Haiku::Haiku(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
3586   : Generic_ELF(D, Triple, Args) {
3587
3588 }
3589
3590 std::string Haiku::findLibCxxIncludePath() const {
3591   return getDriver().SysRoot + "/system/develop/headers/c++/v1";
3592 }
3593
3594 void Haiku::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3595                                      llvm::opt::ArgStringList &CC1Args) const {
3596   addLibStdCXXIncludePaths(getDriver().SysRoot, "/system/develop/headers/c++",
3597                            getTriple().str(), "", "", "", DriverArgs, CC1Args);
3598 }
3599
3600 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
3601
3602 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
3603                  const ArgList &Args)
3604     : Generic_ELF(D, Triple, Args) {
3605   getFilePaths().push_back(getDriver().Dir + "/../lib");
3606   getFilePaths().push_back("/usr/lib");
3607 }
3608
3609 Tool *OpenBSD::buildAssembler() const {
3610   return new tools::openbsd::Assembler(*this);
3611 }
3612
3613 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
3614
3615 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
3616
3617 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3618     : Generic_ELF(D, Triple, Args) {
3619   getFilePaths().push_back(getDriver().Dir + "/../lib");
3620   getFilePaths().push_back("/usr/lib");
3621 }
3622
3623 Tool *Bitrig::buildAssembler() const {
3624   return new tools::bitrig::Assembler(*this);
3625 }
3626
3627 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
3628
3629 ToolChain::CXXStdlibType Bitrig::GetDefaultCXXStdlibType() const {
3630   return ToolChain::CST_Libcxx;
3631 }
3632
3633 void Bitrig::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3634                                       llvm::opt::ArgStringList &CC1Args) const {
3635   std::string Triple = getTriple().str();
3636   if (StringRef(Triple).startswith("amd64"))
3637     Triple = "x86_64" + Triple.substr(5);
3638   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/c++/stdc++",
3639                            Triple, "", "", "", DriverArgs, CC1Args);
3640 }
3641
3642 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
3643                                  ArgStringList &CmdArgs) const {
3644   switch (GetCXXStdlibType(Args)) {
3645   case ToolChain::CST_Libcxx:
3646     CmdArgs.push_back("-lc++");
3647     CmdArgs.push_back("-lc++abi");
3648     CmdArgs.push_back("-lpthread");
3649     break;
3650   case ToolChain::CST_Libstdcxx:
3651     CmdArgs.push_back("-lstdc++");
3652     break;
3653   }
3654 }
3655
3656 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
3657
3658 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
3659                  const ArgList &Args)
3660     : Generic_ELF(D, Triple, Args) {
3661
3662   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
3663   // back to '/usr/lib' if it doesn't exist.
3664   if ((Triple.getArch() == llvm::Triple::x86 ||
3665        Triple.getArch() == llvm::Triple::ppc) &&
3666       D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
3667     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
3668   else
3669     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
3670 }
3671
3672 ToolChain::CXXStdlibType FreeBSD::GetDefaultCXXStdlibType() const {
3673   if (getTriple().getOSMajorVersion() >= 10)
3674     return ToolChain::CST_Libcxx;
3675   return ToolChain::CST_Libstdcxx;
3676 }
3677
3678 void FreeBSD::addLibStdCxxIncludePaths(
3679     const llvm::opt::ArgList &DriverArgs,
3680     llvm::opt::ArgStringList &CC1Args) const {
3681   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/c++/4.2", "", "",
3682                            "", "", DriverArgs, CC1Args);
3683 }
3684
3685 void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
3686                                   ArgStringList &CmdArgs) const {
3687   CXXStdlibType Type = GetCXXStdlibType(Args);
3688   bool Profiling = Args.hasArg(options::OPT_pg);
3689
3690   switch (Type) {
3691   case ToolChain::CST_Libcxx:
3692     CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
3693     break;
3694
3695   case ToolChain::CST_Libstdcxx:
3696     CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++");
3697     break;
3698   }
3699 }
3700
3701 Tool *FreeBSD::buildAssembler() const {
3702   return new tools::freebsd::Assembler(*this);
3703 }
3704
3705 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
3706
3707 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const {
3708   // FreeBSD uses SjLj exceptions on ARM oabi.
3709   switch (getTriple().getEnvironment()) {
3710   case llvm::Triple::GNUEABIHF:
3711   case llvm::Triple::GNUEABI:
3712   case llvm::Triple::EABI:
3713     return false;
3714
3715   default:
3716     return (getTriple().getArch() == llvm::Triple::arm ||
3717             getTriple().getArch() == llvm::Triple::thumb);
3718   }
3719 }
3720
3721 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
3722
3723 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3724
3725 SanitizerMask FreeBSD::getSupportedSanitizers() const {
3726   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3727   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3728   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3729                         getTriple().getArch() == llvm::Triple::mips64el;
3730   SanitizerMask Res = ToolChain::getSupportedSanitizers();
3731   Res |= SanitizerKind::Address;
3732   Res |= SanitizerKind::Vptr;
3733   if (IsX86_64 || IsMIPS64) {
3734     Res |= SanitizerKind::Leak;
3735     Res |= SanitizerKind::Thread;
3736   }
3737   if (IsX86 || IsX86_64) {
3738     Res |= SanitizerKind::SafeStack;
3739   }
3740   return Res;
3741 }
3742
3743 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
3744
3745 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3746     : Generic_ELF(D, Triple, Args) {
3747   if (getDriver().UseStdLib) {
3748     // When targeting a 32-bit platform, try the special directory used on
3749     // 64-bit hosts, and only fall back to the main library directory if that
3750     // doesn't work.
3751     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
3752     // what all logic is needed to emulate the '=' prefix here.
3753     switch (Triple.getArch()) {
3754     case llvm::Triple::x86:
3755       getFilePaths().push_back("=/usr/lib/i386");
3756       break;
3757     case llvm::Triple::arm:
3758     case llvm::Triple::armeb:
3759     case llvm::Triple::thumb:
3760     case llvm::Triple::thumbeb:
3761       switch (Triple.getEnvironment()) {
3762       case llvm::Triple::EABI:
3763       case llvm::Triple::GNUEABI:
3764         getFilePaths().push_back("=/usr/lib/eabi");
3765         break;
3766       case llvm::Triple::EABIHF:
3767       case llvm::Triple::GNUEABIHF:
3768         getFilePaths().push_back("=/usr/lib/eabihf");
3769         break;
3770       default:
3771         getFilePaths().push_back("=/usr/lib/oabi");
3772         break;
3773       }
3774       break;
3775     case llvm::Triple::mips64:
3776     case llvm::Triple::mips64el:
3777       if (tools::mips::hasMipsAbiArg(Args, "o32"))
3778         getFilePaths().push_back("=/usr/lib/o32");
3779       else if (tools::mips::hasMipsAbiArg(Args, "64"))
3780         getFilePaths().push_back("=/usr/lib/64");
3781       break;
3782     case llvm::Triple::ppc:
3783       getFilePaths().push_back("=/usr/lib/powerpc");
3784       break;
3785     case llvm::Triple::sparc:
3786       getFilePaths().push_back("=/usr/lib/sparc");
3787       break;
3788     default:
3789       break;
3790     }
3791
3792     getFilePaths().push_back("=/usr/lib");
3793   }
3794 }
3795
3796 Tool *NetBSD::buildAssembler() const {
3797   return new tools::netbsd::Assembler(*this);
3798 }
3799
3800 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
3801
3802 ToolChain::CXXStdlibType NetBSD::GetDefaultCXXStdlibType() const {
3803   unsigned Major, Minor, Micro;
3804   getTriple().getOSVersion(Major, Minor, Micro);
3805   if (Major >= 7 || Major == 0) {
3806     switch (getArch()) {
3807     case llvm::Triple::aarch64:
3808     case llvm::Triple::arm:
3809     case llvm::Triple::armeb:
3810     case llvm::Triple::thumb:
3811     case llvm::Triple::thumbeb:
3812     case llvm::Triple::ppc:
3813     case llvm::Triple::ppc64:
3814     case llvm::Triple::ppc64le:
3815     case llvm::Triple::sparc:
3816     case llvm::Triple::sparcv9:
3817     case llvm::Triple::x86:
3818     case llvm::Triple::x86_64:
3819       return ToolChain::CST_Libcxx;
3820     default:
3821       break;
3822     }
3823   }
3824   return ToolChain::CST_Libstdcxx;
3825 }
3826
3827 std::string NetBSD::findLibCxxIncludePath() const {
3828   return getDriver().SysRoot + "/usr/include/c++/";
3829 }
3830
3831 void NetBSD::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3832                                       llvm::opt::ArgStringList &CC1Args) const {
3833   addLibStdCXXIncludePaths(getDriver().SysRoot, "/usr/include/g++", "", "", "",
3834                            "", DriverArgs, CC1Args);
3835 }
3836
3837 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
3838
3839 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3840     : Generic_ELF(D, Triple, Args) {
3841   getFilePaths().push_back(getDriver().Dir + "/../lib");
3842   getFilePaths().push_back("/usr/lib");
3843 }
3844
3845 Tool *Minix::buildAssembler() const {
3846   return new tools::minix::Assembler(*this);
3847 }
3848
3849 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
3850
3851 static void addPathIfExists(const Driver &D, const Twine &Path,
3852                             ToolChain::path_list &Paths) {
3853   if (D.getVFS().exists(Path))
3854     Paths.push_back(Path.str());
3855 }
3856
3857 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
3858
3859 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
3860                  const ArgList &Args)
3861     : Generic_GCC(D, Triple, Args) {
3862
3863   GCCInstallation.init(Triple, Args);
3864
3865   path_list &Paths = getFilePaths();
3866   if (GCCInstallation.isValid())
3867     addPathIfExists(D, GCCInstallation.getInstallPath(), Paths);
3868
3869   addPathIfExists(D, getDriver().getInstalledDir(), Paths);
3870   if (getDriver().getInstalledDir() != getDriver().Dir)
3871     addPathIfExists(D, getDriver().Dir, Paths);
3872
3873   addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
3874
3875   std::string LibPath = "/usr/lib/";
3876   switch (Triple.getArch()) {
3877   case llvm::Triple::x86:
3878   case llvm::Triple::sparc:
3879     break;
3880   case llvm::Triple::x86_64:
3881     LibPath += "amd64/";
3882     break;
3883   case llvm::Triple::sparcv9:
3884     LibPath += "sparcv9/";
3885     break;
3886   default:
3887     llvm_unreachable("Unsupported architecture");
3888   }
3889
3890   addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
3891 }
3892
3893 Tool *Solaris::buildAssembler() const {
3894   return new tools::solaris::Assembler(*this);
3895 }
3896
3897 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
3898
3899 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3900                                            ArgStringList &CC1Args) const {
3901   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3902       DriverArgs.hasArg(options::OPT_nostdincxx))
3903     return;
3904
3905   // Include the support directory for things like xlocale and fudged system
3906   // headers.
3907   // FIXME: This is a weird mix of libc++ and libstdc++. We should also be
3908   // checking the value of -stdlib= here and adding the includes for libc++
3909   // rather than libstdc++ if it's requested.
3910   addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
3911
3912   if (GCCInstallation.isValid()) {
3913     GCCVersion Version = GCCInstallation.getVersion();
3914     addSystemInclude(DriverArgs, CC1Args,
3915                      getDriver().SysRoot + "/usr/gcc/" +
3916                      Version.MajorStr + "." +
3917                      Version.MinorStr +
3918                      "/include/c++/" + Version.Text);
3919     addSystemInclude(DriverArgs, CC1Args,
3920                      getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
3921                      "." + Version.MinorStr + "/include/c++/" +
3922                      Version.Text + "/" +
3923                      GCCInstallation.getTriple().str());
3924   }
3925 }
3926
3927 /// \brief Get our best guess at the multiarch triple for a target.
3928 ///
3929 /// Debian-based systems are starting to use a multiarch setup where they use
3930 /// a target-triple directory in the library and header search paths.
3931 /// Unfortunately, this triple does not align with the vanilla target triple,
3932 /// so we provide a rough mapping here.
3933 static std::string getMultiarchTriple(const Driver &D,
3934                                       const llvm::Triple &TargetTriple,
3935                                       StringRef SysRoot) {
3936   llvm::Triple::EnvironmentType TargetEnvironment =
3937       TargetTriple.getEnvironment();
3938
3939   // For most architectures, just use whatever we have rather than trying to be
3940   // clever.
3941   switch (TargetTriple.getArch()) {
3942   default:
3943     break;
3944
3945   // We use the existence of '/lib/<triple>' as a directory to detect some
3946   // common linux triples that don't quite match the Clang triple for both
3947   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3948   // regardless of what the actual target triple is.
3949   case llvm::Triple::arm:
3950   case llvm::Triple::thumb:
3951     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3952       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3953         return "arm-linux-gnueabihf";
3954     } else {
3955       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
3956         return "arm-linux-gnueabi";
3957     }
3958     break;
3959   case llvm::Triple::armeb:
3960   case llvm::Triple::thumbeb:
3961     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3962       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3963         return "armeb-linux-gnueabihf";
3964     } else {
3965       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3966         return "armeb-linux-gnueabi";
3967     }
3968     break;
3969   case llvm::Triple::x86:
3970     if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
3971       return "i386-linux-gnu";
3972     break;
3973   case llvm::Triple::x86_64:
3974     // We don't want this for x32, otherwise it will match x86_64 libs
3975     if (TargetEnvironment != llvm::Triple::GNUX32 &&
3976         D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
3977       return "x86_64-linux-gnu";
3978     break;
3979   case llvm::Triple::aarch64:
3980     if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
3981       return "aarch64-linux-gnu";
3982     break;
3983   case llvm::Triple::aarch64_be:
3984     if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3985       return "aarch64_be-linux-gnu";
3986     break;
3987   case llvm::Triple::mips:
3988     if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
3989       return "mips-linux-gnu";
3990     break;
3991   case llvm::Triple::mipsel:
3992     if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
3993       return "mipsel-linux-gnu";
3994     break;
3995   case llvm::Triple::mips64:
3996     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
3997       return "mips64-linux-gnu";
3998     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
3999       return "mips64-linux-gnuabi64";
4000     break;
4001   case llvm::Triple::mips64el:
4002     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
4003       return "mips64el-linux-gnu";
4004     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
4005       return "mips64el-linux-gnuabi64";
4006     break;
4007   case llvm::Triple::ppc:
4008     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
4009       return "powerpc-linux-gnuspe";
4010     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
4011       return "powerpc-linux-gnu";
4012     break;
4013   case llvm::Triple::ppc64:
4014     if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
4015       return "powerpc64-linux-gnu";
4016     break;
4017   case llvm::Triple::ppc64le:
4018     if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
4019       return "powerpc64le-linux-gnu";
4020     break;
4021   case llvm::Triple::sparc:
4022     if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
4023       return "sparc-linux-gnu";
4024     break;
4025   case llvm::Triple::sparcv9:
4026     if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
4027       return "sparc64-linux-gnu";
4028     break;
4029   case llvm::Triple::systemz:
4030     if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
4031       return "s390x-linux-gnu";
4032     break;
4033   }
4034   return TargetTriple.str();
4035 }
4036
4037 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
4038   if (isMipsArch(Triple.getArch())) {
4039     if (Triple.isAndroid()) {
4040       StringRef CPUName;
4041       StringRef ABIName;
4042       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4043       if (CPUName == "mips32r6")
4044         return "libr6";
4045       if (CPUName == "mips32r2")
4046         return "libr2";
4047     }
4048     // lib32 directory has a special meaning on MIPS targets.
4049     // It contains N32 ABI binaries. Use this folder if produce
4050     // code for N32 ABI only.
4051     if (tools::mips::hasMipsAbiArg(Args, "n32"))
4052       return "lib32";
4053     return Triple.isArch32Bit() ? "lib" : "lib64";
4054   }
4055
4056   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
4057   // using that variant while targeting other architectures causes problems
4058   // because the libraries are laid out in shared system roots that can't cope
4059   // with a 'lib32' library search path being considered. So we only enable
4060   // them when we know we may need it.
4061   //
4062   // FIXME: This is a bit of a hack. We should really unify this code for
4063   // reasoning about oslibdir spellings with the lib dir spellings in the
4064   // GCCInstallationDetector, but that is a more significant refactoring.
4065   if (Triple.getArch() == llvm::Triple::x86 ||
4066       Triple.getArch() == llvm::Triple::ppc)
4067     return "lib32";
4068
4069   if (Triple.getArch() == llvm::Triple::x86_64 &&
4070       Triple.getEnvironment() == llvm::Triple::GNUX32)
4071     return "libx32";
4072
4073   return Triple.isArch32Bit() ? "lib" : "lib64";
4074 }
4075
4076 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
4077                                   const Multilib &Multilib,
4078                                   StringRef InstallPath,
4079                                   ToolChain::path_list &Paths) {
4080   if (const auto &PathsCallback = Multilibs.filePathsCallback())
4081     for (const auto &Path : PathsCallback(Multilib))
4082       addPathIfExists(D, InstallPath + Path, Paths);
4083 }
4084
4085 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
4086     : Generic_ELF(D, Triple, Args) {
4087   GCCInstallation.init(Triple, Args);
4088   Multilibs = GCCInstallation.getMultilibs();
4089   llvm::Triple::ArchType Arch = Triple.getArch();
4090   std::string SysRoot = computeSysRoot();
4091
4092   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
4093   // least) put various tools in a triple-prefixed directory off of the parent
4094   // of the GCC installation. We use the GCC triple here to ensure that we end
4095   // up with tools that support the same amount of cross compiling as the
4096   // detected GCC installation. For example, if we find a GCC installation
4097   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
4098   // used to target i386.
4099   // FIXME: This seems unlikely to be Linux-specific.
4100   ToolChain::path_list &PPaths = getProgramPaths();
4101   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
4102                          GCCInstallation.getTriple().str() + "/bin")
4103                        .str());
4104
4105   Distro Distro(D.getVFS());
4106
4107   if (Distro.IsOpenSUSE() || Distro.IsUbuntu()) {
4108     ExtraOpts.push_back("-z");
4109     ExtraOpts.push_back("relro");
4110   }
4111
4112   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
4113     ExtraOpts.push_back("-X");
4114
4115   const bool IsAndroid = Triple.isAndroid();
4116   const bool IsMips = isMipsArch(Arch);
4117
4118   if (IsMips && !SysRoot.empty())
4119     ExtraOpts.push_back("--sysroot=" + SysRoot);
4120
4121   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
4122   // and the MIPS ABI require .dynsym to be sorted in different ways.
4123   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
4124   // ABI requires a mapping between the GOT and the symbol table.
4125   // Android loader does not support .gnu.hash.
4126   if (!IsMips && !IsAndroid) {
4127     if (Distro.IsRedhat() || Distro.IsOpenSUSE() ||
4128         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick))
4129       ExtraOpts.push_back("--hash-style=gnu");
4130
4131     if (Distro.IsDebian() || Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
4132         Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic)
4133       ExtraOpts.push_back("--hash-style=both");
4134   }
4135
4136   if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6)
4137     ExtraOpts.push_back("--no-add-needed");
4138
4139 #ifdef ENABLE_LINKER_BUILD_ID
4140   ExtraOpts.push_back("--build-id");
4141 #endif
4142
4143   if (Distro.IsOpenSUSE())
4144     ExtraOpts.push_back("--enable-new-dtags");
4145
4146   // The selection of paths to try here is designed to match the patterns which
4147   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
4148   // This was determined by running GCC in a fake filesystem, creating all
4149   // possible permutations of these directories, and seeing which ones it added
4150   // to the link paths.
4151   path_list &Paths = getFilePaths();
4152
4153   const std::string OSLibDir = getOSLibDir(Triple, Args);
4154   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
4155
4156   // Add the multilib suffixed paths where they are available.
4157   if (GCCInstallation.isValid()) {
4158     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
4159     const std::string &LibPath = GCCInstallation.getParentLibPath();
4160     const Multilib &Multilib = GCCInstallation.getMultilib();
4161     const MultilibSet &Multilibs = GCCInstallation.getMultilibs();
4162
4163     // Add toolchain / multilib specific file paths.
4164     addMultilibsFilePaths(D, Multilibs, Multilib,
4165                           GCCInstallation.getInstallPath(), Paths);
4166
4167     // Sourcery CodeBench MIPS toolchain holds some libraries under
4168     // a biarch-like suffix of the GCC installation.
4169     addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(),
4170                     Paths);
4171
4172     // GCC cross compiling toolchains will install target libraries which ship
4173     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
4174     // any part of the GCC installation in
4175     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
4176     // debatable, but is the reality today. We need to search this tree even
4177     // when we have a sysroot somewhere else. It is the responsibility of
4178     // whomever is doing the cross build targeting a sysroot using a GCC
4179     // installation that is *not* within the system root to ensure two things:
4180     //
4181     //  1) Any DSOs that are linked in from this tree or from the install path
4182     //     above must be present on the system root and found via an
4183     //     appropriate rpath.
4184     //  2) There must not be libraries installed into
4185     //     <prefix>/<triple>/<libdir> unless they should be preferred over
4186     //     those within the system root.
4187     //
4188     // Note that this matches the GCC behavior. See the below comment for where
4189     // Clang diverges from GCC's behavior.
4190     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
4191                            OSLibDir + Multilib.osSuffix(),
4192                     Paths);
4193
4194     // If the GCC installation we found is inside of the sysroot, we want to
4195     // prefer libraries installed in the parent prefix of the GCC installation.
4196     // It is important to *not* use these paths when the GCC installation is
4197     // outside of the system root as that can pick up unintended libraries.
4198     // This usually happens when there is an external cross compiler on the
4199     // host system, and a more minimal sysroot available that is the target of
4200     // the cross. Note that GCC does include some of these directories in some
4201     // configurations but this seems somewhere between questionable and simply
4202     // a bug.
4203     if (StringRef(LibPath).startswith(SysRoot)) {
4204       addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
4205       addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
4206     }
4207   }
4208
4209   // Similar to the logic for GCC above, if we currently running Clang inside
4210   // of the requested system root, add its parent library paths to
4211   // those searched.
4212   // FIXME: It's not clear whether we should use the driver's installed
4213   // directory ('Dir' below) or the ResourceDir.
4214   if (StringRef(D.Dir).startswith(SysRoot)) {
4215     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
4216     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
4217   }
4218
4219   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
4220   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
4221   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
4222   addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
4223
4224   // Try walking via the GCC triple path in case of biarch or multiarch GCC
4225   // installations with strange symlinks.
4226   if (GCCInstallation.isValid()) {
4227     addPathIfExists(D,
4228                     SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
4229                         "/../../" + OSLibDir,
4230                     Paths);
4231
4232     // Add the 'other' biarch variant path
4233     Multilib BiarchSibling;
4234     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
4235       addPathIfExists(D, GCCInstallation.getInstallPath() +
4236                              BiarchSibling.gccSuffix(),
4237                       Paths);
4238     }
4239
4240     // See comments above on the multilib variant for details of why this is
4241     // included even from outside the sysroot.
4242     const std::string &LibPath = GCCInstallation.getParentLibPath();
4243     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
4244     const Multilib &Multilib = GCCInstallation.getMultilib();
4245     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
4246                            Multilib.osSuffix(),
4247                     Paths);
4248
4249     // See comments above on the multilib variant for details of why this is
4250     // only included from within the sysroot.
4251     if (StringRef(LibPath).startswith(SysRoot))
4252       addPathIfExists(D, LibPath, Paths);
4253   }
4254
4255   // Similar to the logic for GCC above, if we are currently running Clang
4256   // inside of the requested system root, add its parent library path to those
4257   // searched.
4258   // FIXME: It's not clear whether we should use the driver's installed
4259   // directory ('Dir' below) or the ResourceDir.
4260   if (StringRef(D.Dir).startswith(SysRoot))
4261     addPathIfExists(D, D.Dir + "/../lib", Paths);
4262
4263   addPathIfExists(D, SysRoot + "/lib", Paths);
4264   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
4265 }
4266
4267 bool Linux::HasNativeLLVMSupport() const { return true; }
4268
4269 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
4270
4271 Tool *Linux::buildAssembler() const {
4272   return new tools::gnutools::Assembler(*this);
4273 }
4274
4275 std::string Linux::computeSysRoot() const {
4276   if (!getDriver().SysRoot.empty())
4277     return getDriver().SysRoot;
4278
4279   if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
4280     return std::string();
4281
4282   // Standalone MIPS toolchains use different names for sysroot folder
4283   // and put it into different places. Here we try to check some known
4284   // variants.
4285
4286   const StringRef InstallDir = GCCInstallation.getInstallPath();
4287   const StringRef TripleStr = GCCInstallation.getTriple().str();
4288   const Multilib &Multilib = GCCInstallation.getMultilib();
4289
4290   std::string Path =
4291       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
4292           .str();
4293
4294   if (getVFS().exists(Path))
4295     return Path;
4296
4297   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
4298
4299   if (getVFS().exists(Path))
4300     return Path;
4301
4302   return std::string();
4303 }
4304
4305 std::string Linux::getDynamicLinker(const ArgList &Args) const {
4306   const llvm::Triple::ArchType Arch = getArch();
4307   const llvm::Triple &Triple = getTriple();
4308
4309   const Distro Distro(getDriver().getVFS());
4310
4311   if (Triple.isAndroid())
4312     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
4313
4314   if (Triple.isMusl()) {
4315     std::string ArchName;
4316     bool IsArm = false;
4317
4318     switch (Arch) {
4319     case llvm::Triple::arm:
4320     case llvm::Triple::thumb:
4321       ArchName = "arm";
4322       IsArm = true;
4323       break;
4324     case llvm::Triple::armeb:
4325     case llvm::Triple::thumbeb:
4326       ArchName = "armeb";
4327       IsArm = true;
4328       break;
4329     default:
4330       ArchName = Triple.getArchName().str();
4331     }
4332     if (IsArm &&
4333         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
4334          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
4335       ArchName += "hf";
4336
4337     return "/lib/ld-musl-" + ArchName + ".so.1";
4338   }
4339
4340   std::string LibDir;
4341   std::string Loader;
4342
4343   switch (Arch) {
4344   default:
4345     llvm_unreachable("unsupported architecture");
4346
4347   case llvm::Triple::aarch64:
4348     LibDir = "lib";
4349     Loader = "ld-linux-aarch64.so.1";
4350     break;
4351   case llvm::Triple::aarch64_be:
4352     LibDir = "lib";
4353     Loader = "ld-linux-aarch64_be.so.1";
4354     break;
4355   case llvm::Triple::arm:
4356   case llvm::Triple::thumb:
4357   case llvm::Triple::armeb:
4358   case llvm::Triple::thumbeb: {
4359     const bool HF =
4360         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
4361         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
4362
4363     LibDir = "lib";
4364     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
4365     break;
4366   }
4367   case llvm::Triple::mips:
4368   case llvm::Triple::mipsel:
4369   case llvm::Triple::mips64:
4370   case llvm::Triple::mips64el: {
4371     bool LE = (Triple.getArch() == llvm::Triple::mipsel) ||
4372               (Triple.getArch() == llvm::Triple::mips64el);
4373     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
4374
4375     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
4376
4377     if (tools::mips::isUCLibc(Args))
4378       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
4379     else if (!Triple.hasEnvironment() &&
4380              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
4381       Loader = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
4382     else
4383       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
4384
4385     break;
4386   }
4387   case llvm::Triple::ppc:
4388     LibDir = "lib";
4389     Loader = "ld.so.1";
4390     break;
4391   case llvm::Triple::ppc64:
4392     LibDir = "lib64";
4393     Loader =
4394         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
4395     break;
4396   case llvm::Triple::ppc64le:
4397     LibDir = "lib64";
4398     Loader =
4399         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
4400     break;
4401   case llvm::Triple::sparc:
4402   case llvm::Triple::sparcel:
4403     LibDir = "lib";
4404     Loader = "ld-linux.so.2";
4405     break;
4406   case llvm::Triple::sparcv9:
4407     LibDir = "lib64";
4408     Loader = "ld-linux.so.2";
4409     break;
4410   case llvm::Triple::systemz:
4411     LibDir = "lib";
4412     Loader = "ld64.so.1";
4413     break;
4414   case llvm::Triple::x86:
4415     LibDir = "lib";
4416     Loader = "ld-linux.so.2";
4417     break;
4418   case llvm::Triple::x86_64: {
4419     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
4420
4421     LibDir = X32 ? "libx32" : "lib64";
4422     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
4423     break;
4424   }
4425   }
4426
4427   if (Distro == Distro::Exherbo && (Triple.getVendor() == llvm::Triple::UnknownVendor ||
4428                                     Triple.getVendor() == llvm::Triple::PC))
4429     return "/usr/" + Triple.str() + "/lib/" + Loader;
4430   return "/" + LibDir + "/" + Loader;
4431 }
4432
4433 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4434                                       ArgStringList &CC1Args) const {
4435   const Driver &D = getDriver();
4436   std::string SysRoot = computeSysRoot();
4437
4438   if (DriverArgs.hasArg(options::OPT_nostdinc))
4439     return;
4440
4441   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
4442     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
4443
4444   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
4445     SmallString<128> P(D.ResourceDir);
4446     llvm::sys::path::append(P, "include");
4447     addSystemInclude(DriverArgs, CC1Args, P);
4448   }
4449
4450   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
4451     return;
4452
4453   // Check for configure-time C include directories.
4454   StringRef CIncludeDirs(C_INCLUDE_DIRS);
4455   if (CIncludeDirs != "") {
4456     SmallVector<StringRef, 5> dirs;
4457     CIncludeDirs.split(dirs, ":");
4458     for (StringRef dir : dirs) {
4459       StringRef Prefix =
4460           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
4461       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
4462     }
4463     return;
4464   }
4465
4466   // Lacking those, try to detect the correct set of system includes for the
4467   // target triple.
4468
4469   // Add include directories specific to the selected multilib set and multilib.
4470   if (GCCInstallation.isValid()) {
4471     const auto &Callback = Multilibs.includeDirsCallback();
4472     if (Callback) {
4473       for (const auto &Path : Callback(GCCInstallation.getMultilib()))
4474         addExternCSystemIncludeIfExists(
4475             DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
4476     }
4477   }
4478
4479   // Implement generic Debian multiarch support.
4480   const StringRef X86_64MultiarchIncludeDirs[] = {
4481       "/usr/include/x86_64-linux-gnu",
4482
4483       // FIXME: These are older forms of multiarch. It's not clear that they're
4484       // in use in any released version of Debian, so we should consider
4485       // removing them.
4486       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
4487   const StringRef X86MultiarchIncludeDirs[] = {
4488       "/usr/include/i386-linux-gnu",
4489
4490       // FIXME: These are older forms of multiarch. It's not clear that they're
4491       // in use in any released version of Debian, so we should consider
4492       // removing them.
4493       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
4494       "/usr/include/i486-linux-gnu"};
4495   const StringRef AArch64MultiarchIncludeDirs[] = {
4496       "/usr/include/aarch64-linux-gnu"};
4497   const StringRef ARMMultiarchIncludeDirs[] = {
4498       "/usr/include/arm-linux-gnueabi"};
4499   const StringRef ARMHFMultiarchIncludeDirs[] = {
4500       "/usr/include/arm-linux-gnueabihf"};
4501   const StringRef ARMEBMultiarchIncludeDirs[] = {
4502       "/usr/include/armeb-linux-gnueabi"};
4503   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
4504       "/usr/include/armeb-linux-gnueabihf"};
4505   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
4506   const StringRef MIPSELMultiarchIncludeDirs[] = {
4507       "/usr/include/mipsel-linux-gnu"};
4508   const StringRef MIPS64MultiarchIncludeDirs[] = {
4509       "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
4510   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
4511       "/usr/include/mips64el-linux-gnu",
4512       "/usr/include/mips64el-linux-gnuabi64"};
4513   const StringRef PPCMultiarchIncludeDirs[] = {
4514       "/usr/include/powerpc-linux-gnu"};
4515   const StringRef PPC64MultiarchIncludeDirs[] = {
4516       "/usr/include/powerpc64-linux-gnu"};
4517   const StringRef PPC64LEMultiarchIncludeDirs[] = {
4518       "/usr/include/powerpc64le-linux-gnu"};
4519   const StringRef SparcMultiarchIncludeDirs[] = {
4520       "/usr/include/sparc-linux-gnu"};
4521   const StringRef Sparc64MultiarchIncludeDirs[] = {
4522       "/usr/include/sparc64-linux-gnu"};
4523   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
4524       "/usr/include/s390x-linux-gnu"};
4525   ArrayRef<StringRef> MultiarchIncludeDirs;
4526   switch (getTriple().getArch()) {
4527   case llvm::Triple::x86_64:
4528     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
4529     break;
4530   case llvm::Triple::x86:
4531     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
4532     break;
4533   case llvm::Triple::aarch64:
4534   case llvm::Triple::aarch64_be:
4535     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
4536     break;
4537   case llvm::Triple::arm:
4538   case llvm::Triple::thumb:
4539     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
4540       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
4541     else
4542       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
4543     break;
4544   case llvm::Triple::armeb:
4545   case llvm::Triple::thumbeb:
4546     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
4547       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
4548     else
4549       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
4550     break;
4551   case llvm::Triple::mips:
4552     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
4553     break;
4554   case llvm::Triple::mipsel:
4555     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
4556     break;
4557   case llvm::Triple::mips64:
4558     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
4559     break;
4560   case llvm::Triple::mips64el:
4561     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
4562     break;
4563   case llvm::Triple::ppc:
4564     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
4565     break;
4566   case llvm::Triple::ppc64:
4567     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
4568     break;
4569   case llvm::Triple::ppc64le:
4570     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
4571     break;
4572   case llvm::Triple::sparc:
4573     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
4574     break;
4575   case llvm::Triple::sparcv9:
4576     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
4577     break;
4578   case llvm::Triple::systemz:
4579     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
4580     break;
4581   default:
4582     break;
4583   }
4584   for (StringRef Dir : MultiarchIncludeDirs) {
4585     if (D.getVFS().exists(SysRoot + Dir)) {
4586       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
4587       break;
4588     }
4589   }
4590
4591   if (getTriple().getOS() == llvm::Triple::RTEMS)
4592     return;
4593
4594   // Add an include of '/include' directly. This isn't provided by default by
4595   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
4596   // add even when Clang is acting as-if it were a system compiler.
4597   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
4598
4599   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
4600 }
4601
4602 static std::string DetectLibcxxIncludePath(StringRef base) {
4603   std::error_code EC;
4604   int MaxVersion = 0;
4605   std::string MaxVersionString = "";
4606   for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
4607        LI = LI.increment(EC)) {
4608     StringRef VersionText = llvm::sys::path::filename(LI->path());
4609     int Version;
4610     if (VersionText[0] == 'v' &&
4611         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
4612       if (Version > MaxVersion) {
4613         MaxVersion = Version;
4614         MaxVersionString = VersionText;
4615       }
4616     }
4617   }
4618   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
4619 }
4620
4621 std::string Linux::findLibCxxIncludePath() const {
4622   const std::string LibCXXIncludePathCandidates[] = {
4623       DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
4624       // If this is a development, non-installed, clang, libcxx will
4625       // not be found at ../include/c++ but it likely to be found at
4626       // one of the following two locations:
4627       DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/local/include/c++"),
4628       DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++") };
4629   for (const auto &IncludePath : LibCXXIncludePathCandidates) {
4630     if (IncludePath.empty() || !getVFS().exists(IncludePath))
4631       continue;
4632     // Use the first candidate that exists.
4633     return IncludePath;
4634   }
4635   return "";
4636 }
4637
4638 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
4639                                      llvm::opt::ArgStringList &CC1Args) const {
4640   // We need a detected GCC installation on Linux to provide libstdc++'s
4641   // headers.
4642   if (!GCCInstallation.isValid())
4643     return;
4644
4645   // By default, look for the C++ headers in an include directory adjacent to
4646   // the lib directory of the GCC installation. Note that this is expect to be
4647   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
4648   StringRef LibDir = GCCInstallation.getParentLibPath();
4649   StringRef InstallDir = GCCInstallation.getInstallPath();
4650   StringRef TripleStr = GCCInstallation.getTriple().str();
4651   const Multilib &Multilib = GCCInstallation.getMultilib();
4652   const std::string GCCMultiarchTriple = getMultiarchTriple(
4653       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
4654   const std::string TargetMultiarchTriple =
4655       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
4656   const GCCVersion &Version = GCCInstallation.getVersion();
4657
4658   // The primary search for libstdc++ supports multiarch variants.
4659   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
4660                                "/c++/" + Version.Text, TripleStr,
4661                                GCCMultiarchTriple, TargetMultiarchTriple,
4662                                Multilib.includeSuffix(), DriverArgs, CC1Args))
4663     return;
4664
4665   // Otherwise, fall back on a bunch of options which don't use multiarch
4666   // layouts for simplicity.
4667   const std::string LibStdCXXIncludePathCandidates[] = {
4668       // Gentoo is weird and places its headers inside the GCC install,
4669       // so if the first attempt to find the headers fails, try these patterns.
4670       InstallDir.str() + "/include/g++-v" + Version.Text,
4671       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
4672           Version.MinorStr,
4673       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
4674       // Android standalone toolchain has C++ headers in yet another place.
4675       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4676       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
4677       // without a subdirectory corresponding to the gcc version.
4678       LibDir.str() + "/../include/c++",
4679   };
4680
4681   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
4682     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
4683                                  /*GCCMultiarchTriple*/ "",
4684                                  /*TargetMultiarchTriple*/ "",
4685                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
4686       break;
4687   }
4688 }
4689
4690 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
4691                                ArgStringList &CC1Args) const {
4692   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
4693 }
4694
4695 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
4696                                 ArgStringList &CC1Args) const {
4697   if (GCCInstallation.isValid()) {
4698     CC1Args.push_back("-isystem");
4699     CC1Args.push_back(DriverArgs.MakeArgString(
4700         GCCInstallation.getParentLibPath() + "/../" +
4701         GCCInstallation.getTriple().str() + "/include"));
4702   }
4703 }
4704
4705 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
4706
4707 SanitizerMask Linux::getSupportedSanitizers() const {
4708   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
4709   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4710   const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
4711                         getTriple().getArch() == llvm::Triple::mips64el;
4712   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
4713                            getTriple().getArch() == llvm::Triple::ppc64le;
4714   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
4715                          getTriple().getArch() == llvm::Triple::aarch64_be;
4716   SanitizerMask Res = ToolChain::getSupportedSanitizers();
4717   Res |= SanitizerKind::Address;
4718   Res |= SanitizerKind::KernelAddress;
4719   Res |= SanitizerKind::Vptr;
4720   Res |= SanitizerKind::SafeStack;
4721   if (IsX86_64 || IsMIPS64 || IsAArch64)
4722     Res |= SanitizerKind::DataFlow;
4723   if (IsX86_64 || IsMIPS64 || IsAArch64)
4724     Res |= SanitizerKind::Leak;
4725   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
4726     Res |= SanitizerKind::Thread;
4727   if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64)
4728     Res |= SanitizerKind::Memory;
4729   if (IsX86_64 || IsMIPS64)
4730     Res |= SanitizerKind::Efficiency;
4731   if (IsX86 || IsX86_64) {
4732     Res |= SanitizerKind::Function;
4733   }
4734   return Res;
4735 }
4736
4737 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
4738                              llvm::opt::ArgStringList &CmdArgs) const {
4739   if (!needsProfileRT(Args)) return;
4740
4741   // Add linker option -u__llvm_runtime_variable to cause runtime
4742   // initialization module to be linked in.
4743   if (!Args.hasArg(options::OPT_coverage))
4744     CmdArgs.push_back(Args.MakeArgString(
4745         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
4746   ToolChain::addProfileRTLibs(Args, CmdArgs);
4747 }
4748
4749 /// Fuchsia - Fuchsia tool chain which can call as(1) and ld(1) directly.
4750
4751 Fuchsia::Fuchsia(const Driver &D, const llvm::Triple &Triple,
4752                  const ArgList &Args)
4753     : Generic_ELF(D, Triple, Args) {
4754
4755   getFilePaths().push_back(D.SysRoot + "/lib");
4756   getFilePaths().push_back(D.ResourceDir + "/lib/fuchsia");
4757 }
4758
4759 Tool *Fuchsia::buildAssembler() const {
4760   return new tools::gnutools::Assembler(*this);
4761 }
4762
4763 Tool *Fuchsia::buildLinker() const {
4764   return new tools::fuchsia::Linker(*this);
4765 }
4766
4767 ToolChain::RuntimeLibType Fuchsia::GetRuntimeLibType(
4768     const ArgList &Args) const {
4769   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
4770     StringRef Value = A->getValue();
4771     if (Value != "compiler-rt")
4772       getDriver().Diag(diag::err_drv_invalid_rtlib_name)
4773         << A->getAsString(Args);
4774   }
4775
4776   return ToolChain::RLT_CompilerRT;
4777 }
4778
4779 ToolChain::CXXStdlibType
4780 Fuchsia::GetCXXStdlibType(const ArgList &Args) const {
4781   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
4782     StringRef Value = A->getValue();
4783     if (Value != "libc++")
4784       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
4785         << A->getAsString(Args);
4786   }
4787
4788   return ToolChain::CST_Libcxx;
4789 }
4790
4791 void Fuchsia::addClangTargetOptions(const ArgList &DriverArgs,
4792                                     ArgStringList &CC1Args) const {
4793   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
4794                          options::OPT_fno_use_init_array, true))
4795     CC1Args.push_back("-fuse-init-array");
4796 }
4797
4798 void Fuchsia::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4799                                         ArgStringList &CC1Args) const {
4800   const Driver &D = getDriver();
4801
4802   if (DriverArgs.hasArg(options::OPT_nostdinc))
4803     return;
4804
4805   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
4806     SmallString<128> P(D.ResourceDir);
4807     llvm::sys::path::append(P, "include");
4808     addSystemInclude(DriverArgs, CC1Args, P);
4809   }
4810
4811   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
4812     return;
4813
4814   // Check for configure-time C include directories.
4815   StringRef CIncludeDirs(C_INCLUDE_DIRS);
4816   if (CIncludeDirs != "") {
4817     SmallVector<StringRef, 5> dirs;
4818     CIncludeDirs.split(dirs, ":");
4819     for (StringRef dir : dirs) {
4820       StringRef Prefix =
4821           llvm::sys::path::is_absolute(dir) ? StringRef(D.SysRoot) : "";
4822       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
4823     }
4824     return;
4825   }
4826
4827   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
4828 }
4829
4830 std::string Fuchsia::findLibCxxIncludePath() const {
4831   return getDriver().SysRoot + "/include/c++/v1";
4832 }
4833
4834 void Fuchsia::AddCXXStdlibLibArgs(const ArgList &Args,
4835                                   ArgStringList &CmdArgs) const {
4836   (void) GetCXXStdlibType(Args);
4837   CmdArgs.push_back("-lc++");
4838   CmdArgs.push_back("-lc++abi");
4839   CmdArgs.push_back("-lunwind");
4840 }
4841
4842 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
4843
4844 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
4845                      const ArgList &Args)
4846     : Generic_ELF(D, Triple, Args) {
4847
4848   // Path mangling to find libexec
4849   getProgramPaths().push_back(getDriver().getInstalledDir());
4850   if (getDriver().getInstalledDir() != getDriver().Dir)
4851     getProgramPaths().push_back(getDriver().Dir);
4852
4853   getFilePaths().push_back(getDriver().Dir + "/../lib");
4854   getFilePaths().push_back("/usr/lib");
4855   getFilePaths().push_back("/usr/lib/gcc50");
4856 }
4857
4858 Tool *DragonFly::buildAssembler() const {
4859   return new tools::dragonfly::Assembler(*this);
4860 }
4861
4862 Tool *DragonFly::buildLinker() const {
4863   return new tools::dragonfly::Linker(*this);
4864 }
4865
4866 /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
4867 /// which isn't properly a linker but nonetheless performs the step of stitching
4868 /// together object files from the assembler into a single blob.
4869
4870 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
4871                              const ToolChain &HostTC, const ArgList &Args)
4872     : ToolChain(D, Triple, Args), HostTC(HostTC),
4873       CudaInstallation(D, Triple, Args) {
4874   if (CudaInstallation.isValid())
4875     getProgramPaths().push_back(CudaInstallation.getBinPath());
4876 }
4877
4878 void CudaToolChain::addClangTargetOptions(
4879     const llvm::opt::ArgList &DriverArgs,
4880     llvm::opt::ArgStringList &CC1Args) const {
4881   HostTC.addClangTargetOptions(DriverArgs, CC1Args);
4882
4883   CC1Args.push_back("-fcuda-is-device");
4884
4885   if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
4886                          options::OPT_fno_cuda_flush_denormals_to_zero, false))
4887     CC1Args.push_back("-fcuda-flush-denormals-to-zero");
4888
4889   if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
4890                          options::OPT_fno_cuda_approx_transcendentals, false))
4891     CC1Args.push_back("-fcuda-approx-transcendentals");
4892
4893   if (DriverArgs.hasArg(options::OPT_nocudalib))
4894     return;
4895
4896   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
4897   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
4898   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
4899
4900   if (LibDeviceFile.empty()) {
4901     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
4902     return;
4903   }
4904
4905   CC1Args.push_back("-mlink-cuda-bitcode");
4906   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
4907
4908   // Libdevice in CUDA-7.0 requires PTX version that's more recent
4909   // than LLVM defaults to. Use PTX4.2 which is the PTX version that
4910   // came with CUDA-7.0.
4911   CC1Args.push_back("-target-feature");
4912   CC1Args.push_back("+ptx42");
4913 }
4914
4915 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
4916                                        ArgStringList &CC1Args) const {
4917   // Check our CUDA version if we're going to include the CUDA headers.
4918   if (!DriverArgs.hasArg(options::OPT_nocudainc) &&
4919       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
4920     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
4921     assert(!Arch.empty() && "Must have an explicit GPU arch.");
4922     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
4923   }
4924   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
4925 }
4926
4927 llvm::opt::DerivedArgList *
4928 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
4929                              StringRef BoundArch,
4930                              Action::OffloadKind DeviceOffloadKind) const {
4931   DerivedArgList *DAL =
4932       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
4933   if (!DAL)
4934     DAL = new DerivedArgList(Args.getBaseArgs());
4935
4936   const OptTable &Opts = getDriver().getOpts();
4937
4938   for (Arg *A : Args) {
4939     if (A->getOption().matches(options::OPT_Xarch__)) {
4940       // Skip this argument unless the architecture matches BoundArch
4941       if (BoundArch.empty() || A->getValue(0) != BoundArch)
4942         continue;
4943
4944       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
4945       unsigned Prev = Index;
4946       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
4947
4948       // If the argument parsing failed or more than one argument was
4949       // consumed, the -Xarch_ argument's parameter tried to consume
4950       // extra arguments. Emit an error and ignore.
4951       //
4952       // We also want to disallow any options which would alter the
4953       // driver behavior; that isn't going to work in our model. We
4954       // use isDriverOption() as an approximation, although things
4955       // like -O4 are going to slip through.
4956       if (!XarchArg || Index > Prev + 1) {
4957         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
4958             << A->getAsString(Args);
4959         continue;
4960       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
4961         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
4962             << A->getAsString(Args);
4963         continue;
4964       }
4965       XarchArg->setBaseArg(A);
4966       A = XarchArg.release();
4967       DAL->AddSynthesizedArg(A);
4968     }
4969     DAL->append(A);
4970   }
4971
4972   if (!BoundArch.empty()) {
4973     DAL->eraseArg(options::OPT_march_EQ);
4974     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
4975   }
4976   return DAL;
4977 }
4978
4979 Tool *CudaToolChain::buildAssembler() const {
4980   return new tools::NVPTX::Assembler(*this);
4981 }
4982
4983 Tool *CudaToolChain::buildLinker() const {
4984   return new tools::NVPTX::Linker(*this);
4985 }
4986
4987 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
4988   HostTC.addClangWarningOptions(CC1Args);
4989 }
4990
4991 ToolChain::CXXStdlibType
4992 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
4993   return HostTC.GetCXXStdlibType(Args);
4994 }
4995
4996 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4997                                               ArgStringList &CC1Args) const {
4998   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
4999 }
5000
5001 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
5002                                                  ArgStringList &CC1Args) const {
5003   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
5004 }
5005
5006 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
5007                                         ArgStringList &CC1Args) const {
5008   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
5009 }
5010
5011 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
5012   // The CudaToolChain only supports sanitizers in the sense that it allows
5013   // sanitizer arguments on the command line if they are supported by the host
5014   // toolchain. The CudaToolChain will actually ignore any command line
5015   // arguments for any of these "supported" sanitizers. That means that no
5016   // sanitization of device code is actually supported at this time.
5017   //
5018   // This behavior is necessary because the host and device toolchains
5019   // invocations often share the command line, so the device toolchain must
5020   // tolerate flags meant only for the host toolchain.
5021   return HostTC.getSupportedSanitizers();
5022 }
5023
5024 /// XCore tool chain
5025 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple,
5026                                const ArgList &Args)
5027     : ToolChain(D, Triple, Args) {
5028   // ProgramPaths are found via 'PATH' environment variable.
5029 }
5030
5031 Tool *XCoreToolChain::buildAssembler() const {
5032   return new tools::XCore::Assembler(*this);
5033 }
5034
5035 Tool *XCoreToolChain::buildLinker() const {
5036   return new tools::XCore::Linker(*this);
5037 }
5038
5039 bool XCoreToolChain::isPICDefault() const { return false; }
5040
5041 bool XCoreToolChain::isPIEDefault() const { return false; }
5042
5043 bool XCoreToolChain::isPICDefaultForced() const { return false; }
5044
5045 bool XCoreToolChain::SupportsProfiling() const { return false; }
5046
5047 bool XCoreToolChain::hasBlocksRuntime() const { return false; }
5048
5049 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5050                                                ArgStringList &CC1Args) const {
5051   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
5052       DriverArgs.hasArg(options::OPT_nostdlibinc))
5053     return;
5054   if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
5055     SmallVector<StringRef, 4> Dirs;
5056     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
5057     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
5058     ArrayRef<StringRef> DirVec(Dirs);
5059     addSystemIncludes(DriverArgs, CC1Args, DirVec);
5060   }
5061 }
5062
5063 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs,
5064                                            ArgStringList &CC1Args) const {
5065   CC1Args.push_back("-nostdsysteminc");
5066 }
5067
5068 void XCoreToolChain::AddClangCXXStdlibIncludeArgs(
5069     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
5070   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
5071       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
5072       DriverArgs.hasArg(options::OPT_nostdincxx))
5073     return;
5074   if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
5075     SmallVector<StringRef, 4> Dirs;
5076     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
5077     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
5078     ArrayRef<StringRef> DirVec(Dirs);
5079     addSystemIncludes(DriverArgs, CC1Args, DirVec);
5080   }
5081 }
5082
5083 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
5084                                          ArgStringList &CmdArgs) const {
5085   // We don't output any lib args. This is handled by xcc.
5086 }
5087
5088 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple,
5089                                  const ArgList &Args)
5090     : Generic_ELF(D, Triple, Args) {
5091   // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use
5092   // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple.
5093   // This won't work to find gcc. Instead we give the installation detector an
5094   // extra triple, which is preferable to further hacks of the logic that at
5095   // present is based solely on getArch(). In particular, it would be wrong to
5096   // choose the myriad installation when targeting a non-myriad sparc install.
5097   switch (Triple.getArch()) {
5098   default:
5099     D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5100                                               << "myriad";
5101   case llvm::Triple::sparc:
5102   case llvm::Triple::sparcel:
5103   case llvm::Triple::shave:
5104     GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"});
5105   }
5106
5107   if (GCCInstallation.isValid()) {
5108     // This directory contains crt{i,n,begin,end}.o as well as libgcc.
5109     // These files are tied to a particular version of gcc.
5110     SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath());
5111     addPathIfExists(D, CompilerSupportDir, getFilePaths());
5112   }
5113   // libstd++ and libc++ must both be found in this one place.
5114   addPathIfExists(D, D.Dir + "/../sparc-myriad-elf/lib", getFilePaths());
5115 }
5116
5117 MyriadToolChain::~MyriadToolChain() {}
5118
5119 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5120                                                 ArgStringList &CC1Args) const {
5121   if (!DriverArgs.hasArg(options::OPT_nostdinc))
5122     addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
5123 }
5124
5125 std::string MyriadToolChain::findLibCxxIncludePath() const {
5126   std::string Path(getDriver().getInstalledDir());
5127   return Path + "/../include/c++/v1";
5128 }
5129
5130 void MyriadToolChain::addLibStdCxxIncludePaths(
5131     const llvm::opt::ArgList &DriverArgs,
5132     llvm::opt::ArgStringList &CC1Args) const {
5133   StringRef LibDir = GCCInstallation.getParentLibPath();
5134   const GCCVersion &Version = GCCInstallation.getVersion();
5135   StringRef TripleStr = GCCInstallation.getTriple().str();
5136   const Multilib &Multilib = GCCInstallation.getMultilib();
5137   addLibStdCXXIncludePaths(
5138       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
5139       "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args);
5140 }
5141
5142 // MyriadToolChain handles several triples:
5143 //  {shave,sparc{,el}}-myriad-{rtems,unknown}-elf
5144 Tool *MyriadToolChain::SelectTool(const JobAction &JA) const {
5145   // The inherited method works fine if not targeting the SHAVE.
5146   if (!isShaveCompilation(getTriple()))
5147     return ToolChain::SelectTool(JA);
5148   switch (JA.getKind()) {
5149   case Action::PreprocessJobClass:
5150   case Action::CompileJobClass:
5151     if (!Compiler)
5152       Compiler.reset(new tools::SHAVE::Compiler(*this));
5153     return Compiler.get();
5154   case Action::AssembleJobClass:
5155     if (!Assembler)
5156       Assembler.reset(new tools::SHAVE::Assembler(*this));
5157     return Assembler.get();
5158   default:
5159     return ToolChain::getTool(JA.getKind());
5160   }
5161 }
5162
5163 Tool *MyriadToolChain::buildLinker() const {
5164   return new tools::Myriad::Linker(*this);
5165 }
5166
5167 SanitizerMask MyriadToolChain::getSupportedSanitizers() const {
5168   return SanitizerKind::Address;
5169 }
5170
5171 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
5172                          const llvm::opt::ArgList &Args)
5173   : ToolChain(D, Triple, Args) {
5174
5175   assert(Triple.isArch32Bit() != Triple.isArch64Bit());
5176   getFilePaths().push_back(
5177       getDriver().SysRoot + "/lib" + (Triple.isArch32Bit() ? "32" : "64"));
5178 }
5179
5180 bool WebAssembly::IsMathErrnoDefault() const { return false; }
5181
5182 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
5183
5184 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
5185
5186 bool WebAssembly::isPICDefault() const { return false; }
5187
5188 bool WebAssembly::isPIEDefault() const { return false; }
5189
5190 bool WebAssembly::isPICDefaultForced() const { return false; }
5191
5192 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
5193
5194 // TODO: Support Objective C stuff.
5195 bool WebAssembly::SupportsObjCGC() const { return false; }
5196
5197 bool WebAssembly::hasBlocksRuntime() const { return false; }
5198
5199 // TODO: Support profiling.
5200 bool WebAssembly::SupportsProfiling() const { return false; }
5201
5202 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
5203
5204 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
5205                                         ArgStringList &CC1Args) const {
5206   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
5207                          options::OPT_fno_use_init_array, true))
5208     CC1Args.push_back("-fuse-init-array");
5209 }
5210
5211 ToolChain::RuntimeLibType WebAssembly::GetDefaultRuntimeLibType() const {
5212   return ToolChain::RLT_CompilerRT;
5213 }
5214
5215 ToolChain::CXXStdlibType WebAssembly::GetCXXStdlibType(const ArgList &Args) const {
5216   return ToolChain::CST_Libcxx;
5217 }
5218
5219 void WebAssembly::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
5220                                             ArgStringList &CC1Args) const {
5221   if (!DriverArgs.hasArg(options::OPT_nostdinc))
5222     addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
5223 }
5224
5225 void WebAssembly::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
5226                                                ArgStringList &CC1Args) const {
5227   if (!DriverArgs.hasArg(options::OPT_nostdlibinc) &&
5228       !DriverArgs.hasArg(options::OPT_nostdincxx))
5229     addSystemInclude(DriverArgs, CC1Args,
5230                      getDriver().SysRoot + "/include/c++/v1");
5231 }
5232
5233 Tool *WebAssembly::buildLinker() const {
5234   return new tools::wasm::Linker(*this);
5235 }
5236
5237 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
5238     : Generic_ELF(D, Triple, Args) {
5239   if (Args.hasArg(options::OPT_static))
5240     D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4";
5241
5242   // Determine where to find the PS4 libraries. We use SCE_ORBIS_SDK_DIR
5243   // if it exists; otherwise use the driver's installation path, which
5244   // should be <SDK_DIR>/host_tools/bin.
5245
5246   SmallString<512> PS4SDKDir;
5247   if (const char *EnvValue = getenv("SCE_ORBIS_SDK_DIR")) {
5248     if (!llvm::sys::fs::exists(EnvValue))
5249       getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue;
5250     PS4SDKDir = EnvValue;
5251   } else {
5252     PS4SDKDir = getDriver().Dir;
5253     llvm::sys::path::append(PS4SDKDir, "/../../");
5254   }
5255
5256   // By default, the driver won't report a warning if it can't find
5257   // PS4's include or lib directories. This behavior could be changed if
5258   // -Weverything or -Winvalid-or-nonexistent-directory options are passed.
5259   // If -isysroot was passed, use that as the SDK base path.
5260   std::string PrefixDir;
5261   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
5262     PrefixDir = A->getValue();
5263     if (!llvm::sys::fs::exists(PrefixDir))
5264       getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir;
5265   } else
5266     PrefixDir = PS4SDKDir.str();
5267
5268   SmallString<512> PS4SDKIncludeDir(PrefixDir);
5269   llvm::sys::path::append(PS4SDKIncludeDir, "target/include");
5270   if (!Args.hasArg(options::OPT_nostdinc) &&
5271       !Args.hasArg(options::OPT_nostdlibinc) &&
5272       !Args.hasArg(options::OPT_isysroot) &&
5273       !Args.hasArg(options::OPT__sysroot_EQ) &&
5274       !llvm::sys::fs::exists(PS4SDKIncludeDir)) {
5275     getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
5276         << "PS4 system headers" << PS4SDKIncludeDir;
5277   }
5278
5279   SmallString<512> PS4SDKLibDir(PS4SDKDir);
5280   llvm::sys::path::append(PS4SDKLibDir, "target/lib");
5281   if (!Args.hasArg(options::OPT_nostdlib) &&
5282       !Args.hasArg(options::OPT_nodefaultlibs) &&
5283       !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) &&
5284       !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) &&
5285       !Args.hasArg(options::OPT_emit_ast) &&
5286       !llvm::sys::fs::exists(PS4SDKLibDir)) {
5287     getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
5288         << "PS4 system libraries" << PS4SDKLibDir;
5289     return;
5290   }
5291   getFilePaths().push_back(PS4SDKLibDir.str());
5292 }
5293
5294 Tool *PS4CPU::buildAssembler() const {
5295   return new tools::PS4cpu::Assemble(*this);
5296 }
5297
5298 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); }
5299
5300 bool PS4CPU::isPICDefault() const { return true; }
5301
5302 bool PS4CPU::HasNativeLLVMSupport() const { return true; }
5303
5304 SanitizerMask PS4CPU::getSupportedSanitizers() const {
5305   SanitizerMask Res = ToolChain::getSupportedSanitizers();
5306   Res |= SanitizerKind::Address;
5307   Res |= SanitizerKind::Vptr;
5308   return Res;
5309 }
5310
5311 Contiki::Contiki(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
5312     : Generic_ELF(D, Triple, Args) {}
5313
5314 SanitizerMask Contiki::getSupportedSanitizers() const {
5315   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
5316   SanitizerMask Res = ToolChain::getSupportedSanitizers();
5317   if (IsX86)
5318     Res |= SanitizerKind::SafeStack;
5319   return Res;
5320 }