]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp
Merge ^/head r279893 through r279984.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains.cpp
1 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
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/ObjCRuntime.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
14 #include "clang/Driver/Compilation.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Driver/SanitizerArgs.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Option/Arg.h"
24 #include "llvm/Option/ArgList.h"
25 #include "llvm/Option/OptTable.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/Program.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cstdlib> // ::getenv
34 #include <system_error>
35
36 using namespace clang::driver;
37 using namespace clang::driver::toolchains;
38 using namespace clang;
39 using namespace llvm::opt;
40
41 MachO::MachO(const Driver &D, const llvm::Triple &Triple,
42                        const ArgList &Args)
43   : ToolChain(D, Triple, Args) {
44   getProgramPaths().push_back(getDriver().getInstalledDir());
45   if (getDriver().getInstalledDir() != getDriver().Dir)
46     getProgramPaths().push_back(getDriver().Dir);
47
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,
56                const ArgList & Args)
57   : MachO(D, Triple, Args), TargetInitialized(false) {
58   // Compute the initial Darwin version from the triple
59   unsigned Major, Minor, Micro;
60   if (!Triple.getMacOSXVersion(Major, Minor, Micro))
61     getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
62       Triple.getOSName();
63   llvm::raw_string_ostream(MacosxVersionMin)
64     << Major << '.' << Minor << '.' << Micro;
65
66   // FIXME: DarwinVersion is only used to find GCC's libexec directory.
67   // It should be removed when we stop supporting that.
68   DarwinVersion[0] = Minor + 4;
69   DarwinVersion[1] = Micro;
70   DarwinVersion[2] = 0;
71
72   // Compute the initial iOS version from the triple
73   Triple.getiOSVersion(Major, Minor, Micro);
74   llvm::raw_string_ostream(iOSVersionMin)
75     << Major << '.' << Minor << '.' << Micro;
76 }
77
78 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
79   types::ID Ty = types::lookupTypeForExtension(Ext);
80
81   // Darwin always preprocesses assembly files (unless -x is used explicitly).
82   if (Ty == types::TY_PP_Asm)
83     return types::TY_Asm;
84
85   return Ty;
86 }
87
88 bool MachO::HasNativeLLVMSupport() const {
89   return true;
90 }
91
92 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
93 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
94   if (isTargetIOSBased())
95     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
96   if (isNonFragile)
97     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
98   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
99 }
100
101 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
102 bool Darwin::hasBlocksRuntime() const {
103   if (isTargetIOSBased())
104     return !isIPhoneOSVersionLT(3, 2);
105   else {
106     assert(isTargetMacOS() && "unexpected darwin target");
107     return !isMacosxVersionLT(10, 6);
108   }
109 }
110
111 static const char *GetArmArchForMArch(StringRef Value) {
112   return llvm::StringSwitch<const char*>(Value)
113     .Case("armv6k", "armv6")
114     .Case("armv6m", "armv6m")
115     .Case("armv5tej", "armv5")
116     .Case("xscale", "xscale")
117     .Case("armv4t", "armv4t")
118     .Case("armv7", "armv7")
119     .Cases("armv7a", "armv7-a", "armv7")
120     .Cases("armv7r", "armv7-r", "armv7")
121     .Cases("armv7em", "armv7e-m", "armv7em")
122     .Cases("armv7k", "armv7-k", "armv7k")
123     .Cases("armv7m", "armv7-m", "armv7m")
124     .Cases("armv7s", "armv7-s", "armv7s")
125     .Default(nullptr);
126 }
127
128 static const char *GetArmArchForMCpu(StringRef Value) {
129   return llvm::StringSwitch<const char *>(Value)
130     .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
131     .Cases("arm10e", "arm10tdmi", "armv5")
132     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
133     .Case("xscale", "xscale")
134     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
135     .Case("cortex-m0", "armv6m")
136     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
137     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "armv7")
138     .Cases("cortex-r4", "cortex-r5", "armv7r")
139     .Case("cortex-m3", "armv7m")
140     .Cases("cortex-m4", "cortex-m7", "armv7em")
141     .Case("swift", "armv7s")
142     .Default(nullptr);
143 }
144
145 static bool isSoftFloatABI(const ArgList &Args) {
146   Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
147                            options::OPT_mfloat_abi_EQ);
148   if (!A)
149     return false;
150
151   return A->getOption().matches(options::OPT_msoft_float) ||
152          (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
153           A->getValue() == StringRef("soft"));
154 }
155
156 StringRef MachO::getMachOArchName(const ArgList &Args) const {
157   switch (getTriple().getArch()) {
158   default:
159     return getDefaultUniversalArchName();
160
161   case llvm::Triple::aarch64:
162     return "arm64";
163
164   case llvm::Triple::thumb:
165   case llvm::Triple::arm: {
166     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
167       if (const char *Arch = GetArmArchForMArch(A->getValue()))
168         return Arch;
169
170     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
171       if (const char *Arch = GetArmArchForMCpu(A->getValue()))
172         return Arch;
173
174     return "arm";
175   }
176   }
177 }
178
179 Darwin::~Darwin() {
180 }
181
182 MachO::~MachO() {
183 }
184
185
186 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
187                                                     types::ID InputType) const {
188   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
189
190   return Triple.getTriple();
191 }
192
193 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
194                                                 types::ID InputType) const {
195   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
196
197   // If the target isn't initialized (e.g., an unknown Darwin platform, return
198   // the default triple).
199   if (!isTargetInitialized())
200     return Triple.getTriple();
201
202   SmallString<16> Str;
203   Str += isTargetIOSBased() ? "ios" : "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 {
232   return new tools::darwin::Link(*this);
233 }
234
235 Tool *MachO::buildAssembler() const {
236   return new tools::darwin::Assemble(*this);
237 }
238
239 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
240                          const ArgList &Args)
241   : Darwin(D, Triple, Args) {
242 }
243
244 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
245   // For iOS, 64-bit, promote certain warnings to errors.
246   if (!isTargetMacOS() && getTriple().isArch64Bit()) {
247     // Always enable -Wdeprecated-objc-isa-usage and promote it
248     // to an error.
249     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
250     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
251
252     // Also error about implicit function declarations, as that
253     // can impact calling conventions.
254     CC1Args.push_back("-Werror=implicit-function-declaration");
255   }
256 }
257
258 /// \brief Determine whether Objective-C automated reference counting is
259 /// enabled.
260 static bool isObjCAutoRefCount(const ArgList &Args) {
261   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
262 }
263
264 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
265                                  ArgStringList &CmdArgs) const {
266   // Avoid linking compatibility stubs on i386 mac.
267   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
268     return;
269
270   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
271
272   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
273       runtime.hasSubscripting())
274     return;
275
276   CmdArgs.push_back("-force_load");
277   SmallString<128> P(getDriver().ClangExecutable);
278   llvm::sys::path::remove_filename(P); // 'clang'
279   llvm::sys::path::remove_filename(P); // 'bin'
280   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
281   // Mash in the platform.
282   if (isTargetIOSSimulator())
283     P += "iphonesimulator";
284   else if (isTargetIPhoneOS())
285     P += "iphoneos";
286   else
287     P += "macosx";
288   P += ".a";
289
290   CmdArgs.push_back(Args.MakeArgString(P));
291 }
292
293 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
294                               StringRef DarwinLibName, bool AlwaysLink,
295                               bool IsEmbedded, bool AddRPath) const {
296   SmallString<128> Dir(getDriver().ResourceDir);
297   llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
298
299   SmallString<128> P(Dir);
300   llvm::sys::path::append(P, DarwinLibName);
301
302   // For now, allow missing resource libraries to support developers who may
303   // not have compiler-rt checked out or integrated into their build (unless
304   // we explicitly force linking with this library).
305   if (AlwaysLink || llvm::sys::fs::exists(P.str()))
306     CmdArgs.push_back(Args.MakeArgString(P.str()));
307
308   // Adding the rpaths might negatively interact when other rpaths are involved,
309   // so we should make sure we add the rpaths last, after all user-specified
310   // rpaths. This is currently true from this place, but we need to be
311   // careful if this function is ever called before user's rpaths are emitted.
312   if (AddRPath) {
313     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
314
315     // Add @executable_path to rpath to support having the dylib copied with
316     // the executable.
317     CmdArgs.push_back("-rpath");
318     CmdArgs.push_back("@executable_path");
319
320     // Add the path to the resource dir to rpath to support using the dylib
321     // from the default location without copying.
322     CmdArgs.push_back("-rpath");
323     CmdArgs.push_back(Args.MakeArgString(Dir.str()));
324   }
325 }
326
327 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
328                                         ArgStringList &CmdArgs) const {
329   // Darwin only supports the compiler-rt based runtime libraries.
330   switch (GetRuntimeLibType(Args)) {
331   case ToolChain::RLT_CompilerRT:
332     break;
333   default:
334     getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
335       << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
336     return;
337   }
338
339   // Darwin doesn't support real static executables, don't link any runtime
340   // libraries with -static.
341   if (Args.hasArg(options::OPT_static) ||
342       Args.hasArg(options::OPT_fapple_kext) ||
343       Args.hasArg(options::OPT_mkernel))
344     return;
345
346   // Reject -static-libgcc for now, we can deal with this when and if someone
347   // cares. This is useful in situations where someone wants to statically link
348   // something like libstdc++, and needs its runtime support routines.
349   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
350     getDriver().Diag(diag::err_drv_unsupported_opt)
351       << A->getAsString(Args);
352     return;
353   }
354
355   // If we are building profile support, link that library in.
356   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
357                    false) ||
358       Args.hasArg(options::OPT_fprofile_generate) ||
359       Args.hasArg(options::OPT_fprofile_instr_generate) ||
360       Args.hasArg(options::OPT_fcreate_profile) ||
361       Args.hasArg(options::OPT_coverage)) {
362     // Select the appropriate runtime library for the target.
363     if (isTargetIOSBased())
364       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
365     else
366       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
367   }
368
369   const SanitizerArgs &Sanitize = getSanitizerArgs();
370
371   // Add Ubsan runtime library, if required.
372   if (Sanitize.needsUbsanRt()) {
373     // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
374     if (isTargetIOSBased()) {
375       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
376         << "-fsanitize=undefined";
377     } else {
378       assert(isTargetMacOS() && "unexpected non OS X target");
379       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
380
381       // The Ubsan runtime library requires C++.
382       AddCXXStdlibLibArgs(Args, CmdArgs);
383     }
384   }
385
386   // Add ASAN runtime library, if required. Dynamic libraries and bundles
387   // should not be linked with the runtime library.
388   if (Sanitize.needsAsanRt()) {
389     // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds.
390     if (isTargetIPhoneOS()) {
391       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
392         << "-fsanitize=address";
393     } else {
394       if (!Args.hasArg(options::OPT_dynamiclib) &&
395           !Args.hasArg(options::OPT_bundle)) {
396         // The ASAN runtime library requires C++.
397         AddCXXStdlibLibArgs(Args, CmdArgs);
398       }
399       if (isTargetMacOS()) {
400         AddLinkRuntimeLib(Args, CmdArgs,
401                           "libclang_rt.asan_osx_dynamic.dylib",
402                           /*AlwaysLink*/ true, /*IsEmbedded*/ false,
403                           /*AddRPath*/ true);
404       } else {
405         if (isTargetIOSSimulator()) {
406           AddLinkRuntimeLib(Args, CmdArgs,
407                             "libclang_rt.asan_iossim_dynamic.dylib",
408                             /*AlwaysLink*/ true, /*IsEmbedded*/ false,
409                             /*AddRPath*/ true);
410         }
411       }
412     }
413   }
414
415   // Otherwise link libSystem, then the dynamic runtime library, and finally any
416   // target specific static runtime library.
417   CmdArgs.push_back("-lSystem");
418
419   // Select the dynamic runtime library and the target specific static library.
420   if (isTargetIOSBased()) {
421     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
422     // it never went into the SDK.
423     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
424     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
425         getTriple().getArch() != llvm::Triple::aarch64)
426       CmdArgs.push_back("-lgcc_s.1");
427
428     // We currently always need a static runtime library for iOS.
429     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
430   } else {
431     assert(isTargetMacOS() && "unexpected non MacOS platform");
432     // The dynamic runtime library was merged with libSystem for 10.6 and
433     // beyond; only 10.4 and 10.5 need an additional runtime library.
434     if (isMacosxVersionLT(10, 5))
435       CmdArgs.push_back("-lgcc_s.10.4");
436     else if (isMacosxVersionLT(10, 6))
437       CmdArgs.push_back("-lgcc_s.10.5");
438
439     // For OS X, we thought we would only need a static runtime library when
440     // targeting 10.4, to provide versions of the static functions which were
441     // omitted from 10.4.dylib.
442     //
443     // Unfortunately, that turned out to not be true, because Darwin system
444     // headers can still use eprintf on i386, and it is not exported from
445     // libSystem. Therefore, we still must provide a runtime library just for
446     // the tiny tiny handful of projects that *might* use that symbol.
447     if (isMacosxVersionLT(10, 5)) {
448       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
449     } else {
450       if (getTriple().getArch() == llvm::Triple::x86)
451         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
452       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
453     }
454   }
455 }
456
457 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
458   const OptTable &Opts = getDriver().getOpts();
459
460   // Support allowing the SDKROOT environment variable used by xcrun and other
461   // Xcode tools to define the default sysroot, by making it the default for
462   // isysroot.
463   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
464     // Warn if the path does not exist.
465     if (!llvm::sys::fs::exists(A->getValue()))
466       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
467   } else {
468     if (char *env = ::getenv("SDKROOT")) {
469       // We only use this value as the default if it is an absolute path,
470       // exists, and it is not the root path.
471       if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
472           StringRef(env) != "/") {
473         Args.append(Args.MakeSeparateArg(
474                       nullptr, Opts.getOption(options::OPT_isysroot), env));
475       }
476     }
477   }
478
479   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
480   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
481
482   if (OSXVersion && iOSVersion) {
483     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
484           << OSXVersion->getAsString(Args)
485           << iOSVersion->getAsString(Args);
486     iOSVersion = nullptr;
487   } else if (!OSXVersion && !iOSVersion) {
488     // If no deployment target was specified on the command line, check for
489     // environment defines.
490     StringRef OSXTarget;
491     StringRef iOSTarget;
492     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
493       OSXTarget = env;
494     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
495       iOSTarget = env;
496
497     // If no '-miphoneos-version-min' specified on the command line and
498     // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
499     // based on -isysroot.
500     if (iOSTarget.empty()) {
501       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
502         StringRef first, second;
503         StringRef isysroot = A->getValue();
504         std::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
505         if (second != "")
506           iOSTarget = second.substr(0,3);
507       }
508     }
509
510     // If no OSX or iOS target has been specified and we're compiling for armv7,
511     // go ahead as assume we're targeting iOS.
512     StringRef MachOArchName = getMachOArchName(Args);
513     if (OSXTarget.empty() && iOSTarget.empty() &&
514         (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
515          MachOArchName == "arm64"))
516         iOSTarget = iOSVersionMin;
517
518     // Allow conflicts among OSX and iOS for historical reasons, but choose the
519     // default platform.
520     if (!OSXTarget.empty() && !iOSTarget.empty()) {
521       if (getTriple().getArch() == llvm::Triple::arm ||
522           getTriple().getArch() == llvm::Triple::aarch64 ||
523           getTriple().getArch() == llvm::Triple::thumb)
524         OSXTarget = "";
525       else
526         iOSTarget = "";
527     }
528
529     if (!OSXTarget.empty()) {
530       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
531       OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
532       Args.append(OSXVersion);
533     } else if (!iOSTarget.empty()) {
534       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
535       iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
536       Args.append(iOSVersion);
537     } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
538                MachOArchName != "armv7em") {
539       // Otherwise, assume we are targeting OS X.
540       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
541       OSXVersion = Args.MakeJoinedArg(nullptr, O, MacosxVersionMin);
542       Args.append(OSXVersion);
543     }
544   }
545
546   DarwinPlatformKind Platform;
547   if (OSXVersion)
548     Platform = MacOS;
549   else if (iOSVersion)
550     Platform = IPhoneOS;
551   else
552     llvm_unreachable("Unable to infer Darwin variant");
553
554   // Set the tool chain target information.
555   unsigned Major, Minor, Micro;
556   bool HadExtra;
557   if (Platform == MacOS) {
558     assert(!iOSVersion && "Unknown target platform!");
559     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
560                                    Micro, HadExtra) || HadExtra ||
561         Major != 10 || Minor >= 100 || Micro >= 100)
562       getDriver().Diag(diag::err_drv_invalid_version_number)
563         << OSXVersion->getAsString(Args);
564   } else if (Platform == IPhoneOS) {
565     assert(iOSVersion && "Unknown target platform!");
566     if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor,
567                                    Micro, HadExtra) || HadExtra ||
568         Major >= 10 || Minor >= 100 || Micro >= 100)
569       getDriver().Diag(diag::err_drv_invalid_version_number)
570         << iOSVersion->getAsString(Args);
571   } else
572     llvm_unreachable("unknown kind of Darwin platform");
573
574   // Recognize iOS targets with an x86 architecture as the iOS simulator.
575   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
576                      getTriple().getArch() == llvm::Triple::x86_64))
577     Platform = IPhoneOSSimulator;
578
579   setTarget(Platform, Major, Minor, Micro);
580 }
581
582 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
583                                       ArgStringList &CmdArgs) const {
584   CXXStdlibType Type = GetCXXStdlibType(Args);
585
586   switch (Type) {
587   case ToolChain::CST_Libcxx:
588     CmdArgs.push_back("-lc++");
589     break;
590
591   case ToolChain::CST_Libstdcxx: {
592     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
593     // it was previously found in the gcc lib dir. However, for all the Darwin
594     // platforms we care about it was -lstdc++.6, so we search for that
595     // explicitly if we can't see an obvious -lstdc++ candidate.
596
597     // Check in the sysroot first.
598     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
599       SmallString<128> P(A->getValue());
600       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
601
602       if (!llvm::sys::fs::exists(P.str())) {
603         llvm::sys::path::remove_filename(P);
604         llvm::sys::path::append(P, "libstdc++.6.dylib");
605         if (llvm::sys::fs::exists(P.str())) {
606           CmdArgs.push_back(Args.MakeArgString(P.str()));
607           return;
608         }
609       }
610     }
611
612     // Otherwise, look in the root.
613     // FIXME: This should be removed someday when we don't have to care about
614     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
615     if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
616         llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
617       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
618       return;
619     }
620
621     // Otherwise, let the linker search.
622     CmdArgs.push_back("-lstdc++");
623     break;
624   }
625   }
626 }
627
628 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
629                                    ArgStringList &CmdArgs) const {
630
631   // For Darwin platforms, use the compiler-rt-based support library
632   // instead of the gcc-provided one (which is also incidentally
633   // only present in the gcc lib dir, which makes it hard to find).
634
635   SmallString<128> P(getDriver().ResourceDir);
636   llvm::sys::path::append(P, "lib", "darwin");
637
638   // Use the newer cc_kext for iOS ARM after 6.0.
639   if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
640       getTriple().getArch() == llvm::Triple::aarch64 ||
641       !isIPhoneOSVersionLT(6, 0)) {
642     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
643   } else {
644     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
645   }
646
647   // For now, allow missing resource libraries to support developers who may
648   // not have compiler-rt checked out or integrated into their build.
649   if (llvm::sys::fs::exists(P.str()))
650     CmdArgs.push_back(Args.MakeArgString(P.str()));
651 }
652
653 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
654                                      const char *BoundArch) const {
655   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
656   const OptTable &Opts = getDriver().getOpts();
657
658   // FIXME: We really want to get out of the tool chain level argument
659   // translation business, as it makes the driver functionality much
660   // more opaque. For now, we follow gcc closely solely for the
661   // purpose of easily achieving feature parity & testability. Once we
662   // have something that works, we should reevaluate each translation
663   // and try to push it down into tool specific logic.
664
665   for (Arg *A : Args) {
666     if (A->getOption().matches(options::OPT_Xarch__)) {
667       // Skip this argument unless the architecture matches either the toolchain
668       // triple arch, or the arch being bound.
669       llvm::Triple::ArchType XarchArch =
670         tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
671       if (!(XarchArch == getArch()  ||
672             (BoundArch && XarchArch ==
673              tools::darwin::getArchTypeForMachOArchName(BoundArch))))
674         continue;
675
676       Arg *OriginalArg = A;
677       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
678       unsigned Prev = Index;
679       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
680
681       // If the argument parsing failed or more than one argument was
682       // consumed, the -Xarch_ argument's parameter tried to consume
683       // extra arguments. Emit an error and ignore.
684       //
685       // We also want to disallow any options which would alter the
686       // driver behavior; that isn't going to work in our model. We
687       // use isDriverOption() as an approximation, although things
688       // like -O4 are going to slip through.
689       if (!XarchArg || Index > Prev + 1) {
690         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
691           << A->getAsString(Args);
692         continue;
693       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
694         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
695           << A->getAsString(Args);
696         continue;
697       }
698
699       XarchArg->setBaseArg(A);
700
701       A = XarchArg.release();
702       DAL->AddSynthesizedArg(A);
703
704       // Linker input arguments require custom handling. The problem is that we
705       // have already constructed the phase actions, so we can not treat them as
706       // "input arguments".
707       if (A->getOption().hasFlag(options::LinkerInput)) {
708         // Convert the argument into individual Zlinker_input_args.
709         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
710           DAL->AddSeparateArg(OriginalArg,
711                               Opts.getOption(options::OPT_Zlinker_input),
712                               A->getValue(i));
713
714         }
715         continue;
716       }
717     }
718
719     // Sob. These is strictly gcc compatible for the time being. Apple
720     // gcc translates options twice, which means that self-expanding
721     // options add duplicates.
722     switch ((options::ID) A->getOption().getID()) {
723     default:
724       DAL->append(A);
725       break;
726
727     case options::OPT_mkernel:
728     case options::OPT_fapple_kext:
729       DAL->append(A);
730       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
731       break;
732
733     case options::OPT_dependency_file:
734       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
735                           A->getValue());
736       break;
737
738     case options::OPT_gfull:
739       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
740       DAL->AddFlagArg(A,
741                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
742       break;
743
744     case options::OPT_gused:
745       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
746       DAL->AddFlagArg(A,
747              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
748       break;
749
750     case options::OPT_shared:
751       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
752       break;
753
754     case options::OPT_fconstant_cfstrings:
755       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
756       break;
757
758     case options::OPT_fno_constant_cfstrings:
759       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
760       break;
761
762     case options::OPT_Wnonportable_cfstrings:
763       DAL->AddFlagArg(A,
764                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
765       break;
766
767     case options::OPT_Wno_nonportable_cfstrings:
768       DAL->AddFlagArg(A,
769                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
770       break;
771
772     case options::OPT_fpascal_strings:
773       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
774       break;
775
776     case options::OPT_fno_pascal_strings:
777       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
778       break;
779     }
780   }
781
782   if (getTriple().getArch() == llvm::Triple::x86 ||
783       getTriple().getArch() == llvm::Triple::x86_64)
784     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
785       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
786                         "core2");
787
788   // Add the arch options based on the particular spelling of -arch, to match
789   // how the driver driver works.
790   if (BoundArch) {
791     StringRef Name = BoundArch;
792     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
793     const Option MArch = Opts.getOption(options::OPT_march_EQ);
794
795     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
796     // which defines the list of which architectures we accept.
797     if (Name == "ppc")
798       ;
799     else if (Name == "ppc601")
800       DAL->AddJoinedArg(nullptr, MCpu, "601");
801     else if (Name == "ppc603")
802       DAL->AddJoinedArg(nullptr, MCpu, "603");
803     else if (Name == "ppc604")
804       DAL->AddJoinedArg(nullptr, MCpu, "604");
805     else if (Name == "ppc604e")
806       DAL->AddJoinedArg(nullptr, MCpu, "604e");
807     else if (Name == "ppc750")
808       DAL->AddJoinedArg(nullptr, MCpu, "750");
809     else if (Name == "ppc7400")
810       DAL->AddJoinedArg(nullptr, MCpu, "7400");
811     else if (Name == "ppc7450")
812       DAL->AddJoinedArg(nullptr, MCpu, "7450");
813     else if (Name == "ppc970")
814       DAL->AddJoinedArg(nullptr, MCpu, "970");
815
816     else if (Name == "ppc64" || Name == "ppc64le")
817       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
818
819     else if (Name == "i386")
820       ;
821     else if (Name == "i486")
822       DAL->AddJoinedArg(nullptr, MArch, "i486");
823     else if (Name == "i586")
824       DAL->AddJoinedArg(nullptr, MArch, "i586");
825     else if (Name == "i686")
826       DAL->AddJoinedArg(nullptr, MArch, "i686");
827     else if (Name == "pentium")
828       DAL->AddJoinedArg(nullptr, MArch, "pentium");
829     else if (Name == "pentium2")
830       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
831     else if (Name == "pentpro")
832       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
833     else if (Name == "pentIIm3")
834       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
835
836     else if (Name == "x86_64")
837       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
838     else if (Name == "x86_64h") {
839       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
840       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
841     }
842
843     else if (Name == "arm")
844       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
845     else if (Name == "armv4t")
846       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
847     else if (Name == "armv5")
848       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
849     else if (Name == "xscale")
850       DAL->AddJoinedArg(nullptr, MArch, "xscale");
851     else if (Name == "armv6")
852       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
853     else if (Name == "armv6m")
854       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
855     else if (Name == "armv7")
856       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
857     else if (Name == "armv7em")
858       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
859     else if (Name == "armv7k")
860       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
861     else if (Name == "armv7m")
862       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
863     else if (Name == "armv7s")
864       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
865   }
866
867   return DAL;
868 }
869
870 void MachO::AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args,
871                                   llvm::opt::ArgStringList &CmdArgs) const {
872   // Embedded targets are simple at the moment, not supporting sanitizers and
873   // with different libraries for each member of the product { static, PIC } x
874   // { hard-float, soft-float }
875   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
876   CompilerRT +=
877       tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard"
878           ? "hard"
879           : "soft";
880   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
881
882   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
883 }
884
885
886 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
887                                       const char *BoundArch) const {
888   // First get the generic Apple args, before moving onto Darwin-specific ones.
889   DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
890   const OptTable &Opts = getDriver().getOpts();
891
892   // If no architecture is bound, none of the translations here are relevant.
893   if (!BoundArch)
894     return DAL;
895
896   // Add an explicit version min argument for the deployment target. We do this
897   // after argument translation because -Xarch_ arguments may add a version min
898   // argument.
899   AddDeploymentTarget(*DAL);
900
901   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
902   // FIXME: It would be far better to avoid inserting those -static arguments,
903   // but we can't check the deployment target in the translation code until
904   // it is set here.
905   if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
906     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
907       Arg *A = *it;
908       ++it;
909       if (A->getOption().getID() != options::OPT_mkernel &&
910           A->getOption().getID() != options::OPT_fapple_kext)
911         continue;
912       assert(it != ie && "unexpected argument translation");
913       A = *it;
914       assert(A->getOption().getID() == options::OPT_static &&
915              "missing expected -static argument");
916       it = DAL->getArgs().erase(it);
917     }
918   }
919
920   // Default to use libc++ on OS X 10.9+ and iOS 7+.
921   if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
922        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) &&
923       !Args.getLastArg(options::OPT_stdlib_EQ))
924     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
925                       "libc++");
926
927   // Validate the C++ standard library choice.
928   CXXStdlibType Type = GetCXXStdlibType(*DAL);
929   if (Type == ToolChain::CST_Libcxx) {
930     // Check whether the target provides libc++.
931     StringRef where;
932
933     // Complain about targeting iOS < 5.0 in any way.
934     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
935       where = "iOS 5.0";
936
937     if (where != StringRef()) {
938       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
939         << where;
940     }
941   }
942
943   return DAL;
944 }
945
946 bool MachO::IsUnwindTablesDefault() const {
947   return getArch() == llvm::Triple::x86_64;
948 }
949
950 bool MachO::UseDwarfDebugFlags() const {
951   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
952     return S[0] != '\0';
953   return false;
954 }
955
956 bool Darwin::UseSjLjExceptions() const {
957   // Darwin uses SjLj exceptions on ARM.
958   return (getTriple().getArch() == llvm::Triple::arm ||
959           getTriple().getArch() == llvm::Triple::thumb);
960 }
961
962 bool MachO::isPICDefault() const {
963   return true;
964 }
965
966 bool MachO::isPIEDefault() const {
967   return false;
968 }
969
970 bool MachO::isPICDefaultForced() const {
971   return (getArch() == llvm::Triple::x86_64 ||
972           getArch() == llvm::Triple::aarch64);
973 }
974
975 bool MachO::SupportsProfiling() const {
976   // Profiling instrumentation is only supported on x86.
977   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
978 }
979
980 void Darwin::addMinVersionArgs(const llvm::opt::ArgList &Args,
981                                llvm::opt::ArgStringList &CmdArgs) const {
982   VersionTuple TargetVersion = getTargetVersion();
983
984   if (isTargetIOSSimulator())
985     CmdArgs.push_back("-ios_simulator_version_min");
986   else if (isTargetIOSBased())
987     CmdArgs.push_back("-iphoneos_version_min");
988   else {
989     assert(isTargetMacOS() && "unexpected target");
990     CmdArgs.push_back("-macosx_version_min");
991   }
992
993   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
994 }
995
996 void Darwin::addStartObjectFileArgs(const llvm::opt::ArgList &Args,
997                                     llvm::opt::ArgStringList &CmdArgs) const {
998   // Derived from startfile spec.
999   if (Args.hasArg(options::OPT_dynamiclib)) {
1000     // Derived from darwin_dylib1 spec.
1001     if (isTargetIOSSimulator()) {
1002       ; // iOS simulator does not need dylib1.o.
1003     } else if (isTargetIPhoneOS()) {
1004       if (isIPhoneOSVersionLT(3, 1))
1005         CmdArgs.push_back("-ldylib1.o");
1006     } else {
1007       if (isMacosxVersionLT(10, 5))
1008         CmdArgs.push_back("-ldylib1.o");
1009       else if (isMacosxVersionLT(10, 6))
1010         CmdArgs.push_back("-ldylib1.10.5.o");
1011     }
1012   } else {
1013     if (Args.hasArg(options::OPT_bundle)) {
1014       if (!Args.hasArg(options::OPT_static)) {
1015         // Derived from darwin_bundle1 spec.
1016         if (isTargetIOSSimulator()) {
1017           ; // iOS simulator does not need bundle1.o.
1018         } else if (isTargetIPhoneOS()) {
1019           if (isIPhoneOSVersionLT(3, 1))
1020             CmdArgs.push_back("-lbundle1.o");
1021         } else {
1022           if (isMacosxVersionLT(10, 6))
1023             CmdArgs.push_back("-lbundle1.o");
1024         }
1025       }
1026     } else {
1027       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1028         if (Args.hasArg(options::OPT_static) ||
1029             Args.hasArg(options::OPT_object) ||
1030             Args.hasArg(options::OPT_preload)) {
1031           CmdArgs.push_back("-lgcrt0.o");
1032         } else {
1033           CmdArgs.push_back("-lgcrt1.o");
1034
1035           // darwin_crt2 spec is empty.
1036         }
1037         // By default on OS X 10.8 and later, we don't link with a crt1.o
1038         // file and the linker knows to use _main as the entry point.  But,
1039         // when compiling with -pg, we need to link with the gcrt1.o file,
1040         // so pass the -no_new_main option to tell the linker to use the
1041         // "start" symbol as the entry point.
1042         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1043           CmdArgs.push_back("-no_new_main");
1044       } else {
1045         if (Args.hasArg(options::OPT_static) ||
1046             Args.hasArg(options::OPT_object) ||
1047             Args.hasArg(options::OPT_preload)) {
1048           CmdArgs.push_back("-lcrt0.o");
1049         } else {
1050           // Derived from darwin_crt1 spec.
1051           if (isTargetIOSSimulator()) {
1052             ; // iOS simulator does not need crt1.o.
1053           } else if (isTargetIPhoneOS()) {
1054             if (getArch() == llvm::Triple::aarch64)
1055               ; // iOS does not need any crt1 files for arm64
1056             else if (isIPhoneOSVersionLT(3, 1))
1057               CmdArgs.push_back("-lcrt1.o");
1058             else if (isIPhoneOSVersionLT(6, 0))
1059               CmdArgs.push_back("-lcrt1.3.1.o");
1060           } else {
1061             if (isMacosxVersionLT(10, 5))
1062               CmdArgs.push_back("-lcrt1.o");
1063             else if (isMacosxVersionLT(10, 6))
1064               CmdArgs.push_back("-lcrt1.10.5.o");
1065             else if (isMacosxVersionLT(10, 8))
1066               CmdArgs.push_back("-lcrt1.10.6.o");
1067
1068             // darwin_crt2 spec is empty.
1069           }
1070         }
1071       }
1072     }
1073   }
1074
1075   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1076       isMacosxVersionLT(10, 5)) {
1077     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1078     CmdArgs.push_back(Str);
1079   }
1080 }
1081
1082 bool Darwin::SupportsObjCGC() const {
1083   return isTargetMacOS();
1084 }
1085
1086 void Darwin::CheckObjCARC() const {
1087   if (isTargetIOSBased()|| (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1088     return;
1089   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1090 }
1091
1092 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1093 /// all subcommands; this relies on gcc translating the majority of
1094 /// command line options.
1095
1096 /// \brief Parse a GCCVersion object out of a string of text.
1097 ///
1098 /// This is the primary means of forming GCCVersion objects.
1099 /*static*/
1100 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1101   const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
1102   std::pair<StringRef, StringRef> First = VersionText.split('.');
1103   std::pair<StringRef, StringRef> Second = First.second.split('.');
1104
1105   GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" };
1106   if (First.first.getAsInteger(10, GoodVersion.Major) ||
1107       GoodVersion.Major < 0)
1108     return BadVersion;
1109   GoodVersion.MajorStr = First.first.str();
1110   if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
1111       GoodVersion.Minor < 0)
1112     return BadVersion;
1113   GoodVersion.MinorStr = Second.first.str();
1114
1115   // First look for a number prefix and parse that if present. Otherwise just
1116   // stash the entire patch string in the suffix, and leave the number
1117   // unspecified. This covers versions strings such as:
1118   //   4.4
1119   //   4.4.0
1120   //   4.4.x
1121   //   4.4.2-rc4
1122   //   4.4.x-patched
1123   // And retains any patch number it finds.
1124   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1125   if (!PatchText.empty()) {
1126     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1127       // Try to parse the number and any suffix.
1128       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1129           GoodVersion.Patch < 0)
1130         return BadVersion;
1131       GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1132     }
1133   }
1134
1135   return GoodVersion;
1136 }
1137
1138 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1139 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1140                                           int RHSPatch,
1141                                           StringRef RHSPatchSuffix) const {
1142   if (Major != RHSMajor)
1143     return Major < RHSMajor;
1144   if (Minor != RHSMinor)
1145     return Minor < RHSMinor;
1146   if (Patch != RHSPatch) {
1147     // Note that versions without a specified patch sort higher than those with
1148     // a patch.
1149     if (RHSPatch == -1)
1150       return true;
1151     if (Patch == -1)
1152       return false;
1153
1154     // Otherwise just sort on the patch itself.
1155     return Patch < RHSPatch;
1156   }
1157   if (PatchSuffix != RHSPatchSuffix) {
1158     // Sort empty suffixes higher.
1159     if (RHSPatchSuffix.empty())
1160       return true;
1161     if (PatchSuffix.empty())
1162       return false;
1163
1164     // Provide a lexicographic sort to make this a total ordering.
1165     return PatchSuffix < RHSPatchSuffix;
1166   }
1167
1168   // The versions are equal.
1169   return false;
1170 }
1171
1172 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1173   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1174   if (A)
1175     return A->getValue();
1176   return GCC_INSTALL_PREFIX;
1177 }
1178
1179 /// \brief Initialize a GCCInstallationDetector from the driver.
1180 ///
1181 /// This performs all of the autodetection and sets up the various paths.
1182 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1183 ///
1184 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1185 /// should instead pull the target out of the driver. This is currently
1186 /// necessary because the driver doesn't store the final version of the target
1187 /// triple.
1188 void
1189 Generic_GCC::GCCInstallationDetector::init(
1190     const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) {
1191   llvm::Triple BiarchVariantTriple =
1192       TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1193                                  : TargetTriple.get32BitArchVariant();
1194   // The library directories which may contain GCC installations.
1195   SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1196   // The compatible GCC triples for this particular architecture.
1197   SmallVector<StringRef, 16> CandidateTripleAliases;
1198   SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1199   CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1200                            CandidateTripleAliases, CandidateBiarchLibDirs,
1201                            CandidateBiarchTripleAliases);
1202
1203   // Compute the set of prefixes for our search.
1204   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1205                                        D.PrefixDirs.end());
1206
1207   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1208   if (GCCToolchainDir != "") {
1209     if (GCCToolchainDir.back() == '/')
1210       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1211
1212     Prefixes.push_back(GCCToolchainDir);
1213   } else {
1214     // If we have a SysRoot, try that first.
1215     if (!D.SysRoot.empty()) {
1216       Prefixes.push_back(D.SysRoot);
1217       Prefixes.push_back(D.SysRoot + "/usr");
1218     }
1219
1220     // Then look for gcc installed alongside clang.
1221     Prefixes.push_back(D.InstalledDir + "/..");
1222
1223     // And finally in /usr.
1224     if (D.SysRoot.empty())
1225       Prefixes.push_back("/usr");
1226   }
1227
1228   // Loop over the various components which exist and select the best GCC
1229   // installation available. GCC installs are ranked by version number.
1230   Version = GCCVersion::Parse("0.0.0");
1231   for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1232     if (!llvm::sys::fs::exists(Prefixes[i]))
1233       continue;
1234     for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1235       const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1236       if (!llvm::sys::fs::exists(LibDir))
1237         continue;
1238       for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1239         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
1240                                CandidateTripleAliases[k]);
1241     }
1242     for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
1243       const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
1244       if (!llvm::sys::fs::exists(LibDir))
1245         continue;
1246       for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
1247            ++k)
1248         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir,
1249                                CandidateBiarchTripleAliases[k],
1250                                /*NeedsBiarchSuffix=*/ true);
1251     }
1252   }
1253 }
1254
1255 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1256   for (const auto &InstallPath : CandidateGCCInstallPaths)
1257     OS << "Found candidate GCC installation: " << InstallPath << "\n";
1258
1259   if (!GCCInstallPath.empty())
1260     OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1261
1262   for (const auto &Multilib : Multilibs)
1263     OS << "Candidate multilib: " << Multilib << "\n";
1264
1265   if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1266     OS << "Selected multilib: " << SelectedMultilib << "\n";
1267 }
1268
1269 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1270   if (BiarchSibling.hasValue()) {
1271     M = BiarchSibling.getValue();
1272     return true;
1273   }
1274   return false;
1275 }
1276
1277 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1278     const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1279     SmallVectorImpl<StringRef> &LibDirs,
1280     SmallVectorImpl<StringRef> &TripleAliases,
1281     SmallVectorImpl<StringRef> &BiarchLibDirs,
1282     SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1283   // Declare a bunch of static data sets that we'll select between below. These
1284   // are specifically designed to always refer to string literals to avoid any
1285   // lifetime or initialization issues.
1286   static const char *const AArch64LibDirs[] = { "/lib64", "/lib" };
1287   static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
1288                                                 "aarch64-linux-gnu",
1289                                                 "aarch64-linux-android",
1290                                                 "aarch64-redhat-linux" };
1291   static const char *const AArch64beLibDirs[] = { "/lib" };
1292   static const char *const AArch64beTriples[] = { "aarch64_be-none-linux-gnu",
1293                                                   "aarch64_be-linux-gnu" };
1294
1295   static const char *const ARMLibDirs[] = { "/lib" };
1296   static const char *const ARMTriples[] = { "arm-linux-gnueabi",
1297                                             "arm-linux-androideabi" };
1298   static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
1299                                               "armv7hl-redhat-linux-gnueabi" };
1300   static const char *const ARMebLibDirs[] = { "/lib" };
1301   static const char *const ARMebTriples[] = { "armeb-linux-gnueabi",
1302                                               "armeb-linux-androideabi" };
1303   static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf",
1304                                                 "armebv7hl-redhat-linux-gnueabi" };
1305
1306   static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1307   static const char *const X86_64Triples[] = {
1308     "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
1309     "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
1310     "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux",
1311     "x86_64-linux-android", "x86_64-unknown-linux"
1312   };
1313   static const char *const X32LibDirs[] = { "/libx32" };
1314   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1315   static const char *const X86Triples[] = {
1316     "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
1317     "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
1318     "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
1319     "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu"
1320   };
1321
1322   static const char *const MIPSLibDirs[] = { "/lib" };
1323   static const char *const MIPSTriples[] = { "mips-linux-gnu",
1324                                              "mips-mti-linux-gnu",
1325                                              "mips-img-linux-gnu" };
1326   static const char *const MIPSELLibDirs[] = { "/lib" };
1327   static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
1328                                                "mipsel-linux-android",
1329                                                "mips-img-linux-gnu" };
1330
1331   static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1332   static const char *const MIPS64Triples[] = { "mips64-linux-gnu",
1333                                                "mips-mti-linux-gnu",
1334                                                "mips-img-linux-gnu",
1335                                                "mips64-linux-gnuabi64" };
1336   static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1337   static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu",
1338                                                  "mips-mti-linux-gnu",
1339                                                  "mips-img-linux-gnu",
1340                                                  "mips64el-linux-android",
1341                                                  "mips64el-linux-gnuabi64" };
1342
1343   static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1344   static const char *const PPCTriples[] = {
1345     "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1346     "powerpc-suse-linux", "powerpc-montavista-linuxspe"
1347   };
1348   static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1349   static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
1350                                               "powerpc64-unknown-linux-gnu",
1351                                               "powerpc64-suse-linux",
1352                                               "ppc64-redhat-linux" };
1353   static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" };
1354   static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu",
1355                                                 "powerpc64le-unknown-linux-gnu",
1356                                                 "powerpc64le-suse-linux",
1357                                                 "ppc64le-redhat-linux" };
1358
1359   static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" };
1360   static const char *const SPARCv8Triples[] = { "sparc-linux-gnu",
1361                                                 "sparcv8-linux-gnu" };
1362   static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" };
1363   static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu",
1364                                                 "sparcv9-linux-gnu" };
1365
1366   static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
1367   static const char *const SystemZTriples[] = {
1368     "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1369     "s390x-suse-linux", "s390x-redhat-linux"
1370   };
1371
1372   using std::begin;
1373   using std::end;
1374
1375   switch (TargetTriple.getArch()) {
1376   case llvm::Triple::aarch64:
1377     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1378     TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1379     BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1380     BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1381     break;
1382   case llvm::Triple::aarch64_be:
1383     LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1384     TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1385     BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1386     BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1387     break;
1388   case llvm::Triple::arm:
1389   case llvm::Triple::thumb:
1390     LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1391     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1392       TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1393     } else {
1394       TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1395     }
1396     break;
1397   case llvm::Triple::armeb:
1398   case llvm::Triple::thumbeb:
1399     LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1400     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1401       TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1402     } else {
1403       TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1404     }
1405     break;
1406   case llvm::Triple::x86_64:
1407     LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1408     TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1409     // x32 is always available when x86_64 is available, so adding it as
1410     // secondary arch with x86_64 triples
1411     if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1412       BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1413       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1414     } else {
1415       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1416       BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1417     }
1418     break;
1419   case llvm::Triple::x86:
1420     LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1421     TripleAliases.append(begin(X86Triples), end(X86Triples));
1422     BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1423     BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1424     break;
1425   case llvm::Triple::mips:
1426     LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1427     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1428     BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1429     BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1430     break;
1431   case llvm::Triple::mipsel:
1432     LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1433     TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1434     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1435     BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1436     BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1437     break;
1438   case llvm::Triple::mips64:
1439     LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1440     TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1441     BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1442     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1443     break;
1444   case llvm::Triple::mips64el:
1445     LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1446     TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1447     BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1448     BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1449     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1450     break;
1451   case llvm::Triple::ppc:
1452     LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1453     TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1454     BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1455     BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1456     break;
1457   case llvm::Triple::ppc64:
1458     LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1459     TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1460     BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1461     BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1462     break;
1463   case llvm::Triple::ppc64le:
1464     LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1465     TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1466     break;
1467   case llvm::Triple::sparc:
1468     LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1469     TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1470     BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1471     BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1472     break;
1473   case llvm::Triple::sparcv9:
1474     LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1475     TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1476     BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1477     BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1478     break;
1479   case llvm::Triple::systemz:
1480     LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1481     TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1482     break;
1483
1484   default:
1485     // By default, just rely on the standard lib directories and the original
1486     // triple.
1487     break;
1488   }
1489
1490   // Always append the drivers target triple to the end, in case it doesn't
1491   // match any of our aliases.
1492   TripleAliases.push_back(TargetTriple.str());
1493
1494   // Also include the multiarch variant if it's different.
1495   if (TargetTriple.str() != BiarchTriple.str())
1496     BiarchTripleAliases.push_back(BiarchTriple.str());
1497 }
1498
1499 namespace {
1500 // Filter to remove Multilibs that don't exist as a suffix to Path
1501 class FilterNonExistent : public MultilibSet::FilterCallback {
1502   std::string Base;
1503 public:
1504   FilterNonExistent(std::string Base) : Base(Base) {}
1505   bool operator()(const Multilib &M) const override {
1506     return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o");
1507   }
1508 };
1509 } // end anonymous namespace
1510
1511 static void addMultilibFlag(bool Enabled, const char *const Flag,
1512                             std::vector<std::string> &Flags) {
1513   if (Enabled)
1514     Flags.push_back(std::string("+") + Flag);
1515   else
1516     Flags.push_back(std::string("-") + Flag);
1517 }
1518
1519 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1520   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1521          Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1522 }
1523
1524 static bool isMips32(llvm::Triple::ArchType Arch) {
1525   return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1526 }
1527
1528 static bool isMips64(llvm::Triple::ArchType Arch) {
1529   return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1530 }
1531
1532 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1533   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1534 }
1535
1536 static bool isMips16(const ArgList &Args) {
1537   Arg *A = Args.getLastArg(options::OPT_mips16,
1538                            options::OPT_mno_mips16);
1539   return A && A->getOption().matches(options::OPT_mips16);
1540 }
1541
1542 static bool isMicroMips(const ArgList &Args) {
1543   Arg *A = Args.getLastArg(options::OPT_mmicromips,
1544                            options::OPT_mno_micromips);
1545   return A && A->getOption().matches(options::OPT_mmicromips);
1546 }
1547
1548 struct DetectedMultilibs {
1549   /// The set of multilibs that the detected installation supports.
1550   MultilibSet Multilibs;
1551
1552   /// The primary multilib appropriate for the given flags.
1553   Multilib SelectedMultilib;
1554
1555   /// On Biarch systems, this corresponds to the default multilib when
1556   /// targeting the non-default multilib. Otherwise, it is empty.
1557   llvm::Optional<Multilib> BiarchSibling;
1558 };
1559
1560 static Multilib makeMultilib(StringRef commonSuffix) {
1561   return Multilib(commonSuffix, commonSuffix, commonSuffix);
1562 }
1563
1564 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path,
1565                               const llvm::opt::ArgList &Args,
1566                               DetectedMultilibs &Result) {
1567   // Some MIPS toolchains put libraries and object files compiled
1568   // using different options in to the sub-directoris which names
1569   // reflects the flags used for compilation. For example sysroot
1570   // directory might looks like the following examples:
1571   //
1572   // /usr
1573   //   /lib      <= crt*.o files compiled with '-mips32'
1574   // /mips16
1575   //   /usr
1576   //     /lib    <= crt*.o files compiled with '-mips16'
1577   //   /el
1578   //     /usr
1579   //       /lib  <= crt*.o files compiled with '-mips16 -EL'
1580   //
1581   // or
1582   //
1583   // /usr
1584   //   /lib      <= crt*.o files compiled with '-mips32r2'
1585   // /mips16
1586   //   /usr
1587   //     /lib    <= crt*.o files compiled with '-mips32r2 -mips16'
1588   // /mips32
1589   //     /usr
1590   //       /lib  <= crt*.o files compiled with '-mips32'
1591
1592   FilterNonExistent NonExistent(Path);
1593
1594   // Check for FSF toolchain multilibs
1595   MultilibSet FSFMipsMultilibs;
1596   {
1597     auto MArchMips32 = makeMultilib("/mips32")
1598       .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32");
1599
1600     auto MArchMicroMips = makeMultilib("/micromips")
1601       .flag("+m32").flag("-m64").flag("+mmicromips");
1602
1603     auto MArchMips64r2 = makeMultilib("/mips64r2")
1604       .flag("-m32").flag("+m64").flag("+march=mips64r2");
1605
1606     auto MArchMips64 = makeMultilib("/mips64")
1607       .flag("-m32").flag("+m64").flag("-march=mips64r2");
1608
1609     auto MArchDefault = makeMultilib("")
1610       .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32r2");
1611
1612     auto Mips16 = makeMultilib("/mips16")
1613       .flag("+mips16");
1614
1615     auto UCLibc = makeMultilib("/uclibc")
1616       .flag("+muclibc");
1617
1618     auto MAbi64 = makeMultilib("/64")
1619       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1620
1621     auto BigEndian = makeMultilib("")
1622       .flag("+EB").flag("-EL");
1623
1624     auto LittleEndian = makeMultilib("/el")
1625       .flag("+EL").flag("-EB");
1626
1627     auto SoftFloat = makeMultilib("/sof")
1628       .flag("+msoft-float");
1629
1630     auto Nan2008 = makeMultilib("/nan2008")
1631       .flag("+mnan=2008");
1632
1633     FSFMipsMultilibs = MultilibSet()
1634       .Either(MArchMips32, MArchMicroMips, 
1635               MArchMips64r2, MArchMips64, MArchDefault)
1636       .Maybe(UCLibc)
1637       .Maybe(Mips16)
1638       .FilterOut("/mips64/mips16")
1639       .FilterOut("/mips64r2/mips16")
1640       .FilterOut("/micromips/mips16")
1641       .Maybe(MAbi64)
1642       .FilterOut("/micromips/64")
1643       .FilterOut("/mips32/64")
1644       .FilterOut("^/64")
1645       .FilterOut("/mips16/64")
1646       .Either(BigEndian, LittleEndian)
1647       .Maybe(SoftFloat)
1648       .Maybe(Nan2008)
1649       .FilterOut(".*sof/nan2008")
1650       .FilterOut(NonExistent)
1651       .setIncludeDirsCallback([](
1652           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1653         std::vector<std::string> Dirs;
1654         Dirs.push_back((InstallDir + "/include").str());
1655         std::string SysRootInc = InstallDir.str() + "/../../../../sysroot";
1656         if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1657           Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1658         else
1659           Dirs.push_back(SysRootInc + "/usr/include");
1660         return Dirs;
1661       });
1662   }
1663
1664   // Check for Code Sourcery toolchain multilibs
1665   MultilibSet CSMipsMultilibs;
1666   {
1667     auto MArchMips16 = makeMultilib("/mips16")
1668       .flag("+m32").flag("+mips16");
1669
1670     auto MArchMicroMips = makeMultilib("/micromips")
1671       .flag("+m32").flag("+mmicromips");
1672
1673     auto MArchDefault = makeMultilib("")
1674       .flag("-mips16").flag("-mmicromips");
1675
1676     auto UCLibc = makeMultilib("/uclibc")
1677       .flag("+muclibc");
1678
1679     auto SoftFloat = makeMultilib("/soft-float")
1680       .flag("+msoft-float");
1681
1682     auto Nan2008 = makeMultilib("/nan2008")
1683       .flag("+mnan=2008");
1684
1685     auto DefaultFloat = makeMultilib("")
1686       .flag("-msoft-float").flag("-mnan=2008");
1687
1688     auto BigEndian = makeMultilib("")
1689       .flag("+EB").flag("-EL");
1690
1691     auto LittleEndian = makeMultilib("/el")
1692       .flag("+EL").flag("-EB");
1693
1694     // Note that this one's osSuffix is ""
1695     auto MAbi64 = makeMultilib("")
1696       .gccSuffix("/64")
1697       .includeSuffix("/64")
1698       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1699
1700     CSMipsMultilibs = MultilibSet()
1701       .Either(MArchMips16, MArchMicroMips, MArchDefault)
1702       .Maybe(UCLibc)
1703       .Either(SoftFloat, Nan2008, DefaultFloat)
1704       .FilterOut("/micromips/nan2008")
1705       .FilterOut("/mips16/nan2008")
1706       .Either(BigEndian, LittleEndian)
1707       .Maybe(MAbi64)
1708       .FilterOut("/mips16.*/64")
1709       .FilterOut("/micromips.*/64")
1710       .FilterOut(NonExistent)
1711       .setIncludeDirsCallback([](
1712           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1713         std::vector<std::string> Dirs;
1714         Dirs.push_back((InstallDir + "/include").str());
1715         std::string SysRootInc =
1716             InstallDir.str() + "/../../../../" + TripleStr.str();
1717         if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1718           Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1719         else
1720           Dirs.push_back(SysRootInc + "/libc/usr/include");
1721         return Dirs;
1722       });
1723   }
1724
1725   MultilibSet AndroidMipsMultilibs = MultilibSet()
1726     .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1727     .FilterOut(NonExistent);
1728
1729   MultilibSet DebianMipsMultilibs;
1730   {
1731     Multilib MAbiN32 = Multilib()
1732       .gccSuffix("/n32")
1733       .includeSuffix("/n32")
1734       .flag("+mabi=n32");
1735
1736     Multilib M64 = Multilib()
1737       .gccSuffix("/64")
1738       .includeSuffix("/64")
1739       .flag("+m64").flag("-m32").flag("-mabi=n32");
1740
1741     Multilib M32 = Multilib()
1742       .flag("-m64").flag("+m32").flag("-mabi=n32");
1743
1744     DebianMipsMultilibs = MultilibSet()
1745       .Either(M32, M64, MAbiN32)
1746       .FilterOut(NonExistent);
1747   }
1748
1749   MultilibSet ImgMultilibs;
1750   {
1751     auto Mips64r6 = makeMultilib("/mips64r6")
1752       .flag("+m64").flag("-m32");
1753
1754     auto LittleEndian = makeMultilib("/el")
1755       .flag("+EL").flag("-EB");
1756
1757     auto MAbi64 = makeMultilib("/64")
1758       .flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1759
1760     ImgMultilibs = MultilibSet()
1761       .Maybe(Mips64r6)
1762       .Maybe(MAbi64)
1763       .Maybe(LittleEndian)
1764       .FilterOut(NonExistent)
1765       .setIncludeDirsCallback([](
1766           StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1767         std::vector<std::string> Dirs;
1768         Dirs.push_back((InstallDir + "/include").str());
1769         Dirs.push_back((InstallDir + "/../../../../sysroot/usr/include").str());
1770         return Dirs;
1771       });
1772   }
1773
1774   StringRef CPUName;
1775   StringRef ABIName;
1776   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1777
1778   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1779
1780   Multilib::flags_list Flags;
1781   addMultilibFlag(isMips32(TargetArch), "m32", Flags);
1782   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
1783   addMultilibFlag(isMips16(Args), "mips16", Flags);
1784   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1785   addMultilibFlag(CPUName == "mips32r2", "march=mips32r2", Flags);
1786   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1787   addMultilibFlag(CPUName == "mips64r2" || CPUName == "octeon",
1788                   "march=mips64r2", Flags);
1789   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1790   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1791   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1792                   Flags);
1793   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1794   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1795   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1796   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1797   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1798   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1799
1800   if (TargetTriple.getEnvironment() == llvm::Triple::Android) {
1801     // Select Android toolchain. It's the only choice in that case.
1802     if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1803       Result.Multilibs = AndroidMipsMultilibs;
1804       return true;
1805     }
1806     return false;
1807   }
1808
1809   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1810       TargetTriple.getOS() == llvm::Triple::Linux &&
1811       TargetTriple.getEnvironment() == llvm::Triple::GNU) {
1812     // Select mips-img-linux-gnu toolchain.
1813     if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
1814       Result.Multilibs = ImgMultilibs;
1815       return true;
1816     }
1817     return false;
1818   }
1819
1820   // Sort candidates. Toolchain that best meets the directories goes first.
1821   // Then select the first toolchains matches command line flags.
1822   MultilibSet *candidates[] = { &DebianMipsMultilibs, &FSFMipsMultilibs,
1823                                 &CSMipsMultilibs };
1824   std::sort(
1825       std::begin(candidates), std::end(candidates),
1826       [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
1827   for (const auto &candidate : candidates) {
1828     if (candidate->select(Flags, Result.SelectedMultilib)) {
1829       if (candidate == &DebianMipsMultilibs)
1830         Result.BiarchSibling = Multilib();
1831       Result.Multilibs = *candidate;
1832       return true;
1833     }
1834   }
1835
1836   {
1837     // Fallback to the regular toolchain-tree structure.
1838     Multilib Default;
1839     Result.Multilibs.push_back(Default);
1840     Result.Multilibs.FilterOut(NonExistent);
1841
1842     if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1843       Result.BiarchSibling = Multilib();
1844       return true;
1845     }
1846   }
1847
1848   return false;
1849 }
1850
1851 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple,
1852                                 StringRef Path, const ArgList &Args,
1853                                 bool NeedsBiarchSuffix,
1854                                 DetectedMultilibs &Result) {
1855
1856   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1857   // in what would normally be GCCInstallPath and put the 64-bit
1858   // libs in a subdirectory named 64. The simple logic we follow is that
1859   // *if* there is a subdirectory of the right name with crtbegin.o in it,
1860   // we use that. If not, and if not a biarch triple alias, we look for
1861   // crtbegin.o without the subdirectory.
1862
1863   Multilib Default;
1864   Multilib Alt64 = Multilib()
1865     .gccSuffix("/64")
1866     .includeSuffix("/64")
1867     .flag("-m32").flag("+m64").flag("-mx32");
1868   Multilib Alt32 = Multilib()
1869     .gccSuffix("/32")
1870     .includeSuffix("/32")
1871     .flag("+m32").flag("-m64").flag("-mx32");
1872   Multilib Altx32 = Multilib()
1873     .gccSuffix("/x32")
1874     .includeSuffix("/x32")
1875     .flag("-m32").flag("-m64").flag("+mx32");
1876
1877   FilterNonExistent NonExistent(Path);
1878
1879   // Determine default multilib from: 32, 64, x32
1880   // Also handle cases such as 64 on 32, 32 on 64, etc.
1881   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1882   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1883   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1884     Want = WANT64;
1885   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1886     Want = WANT64;
1887   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1888     Want = WANT32;
1889   else {
1890     if (TargetTriple.isArch32Bit())
1891       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1892     else if (IsX32)
1893       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1894     else
1895       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1896   }
1897
1898   if (Want == WANT32)
1899     Default.flag("+m32").flag("-m64").flag("-mx32");
1900   else if (Want == WANT64)
1901     Default.flag("-m32").flag("+m64").flag("-mx32");
1902   else if (Want == WANTX32)
1903     Default.flag("-m32").flag("-m64").flag("+mx32");
1904   else
1905     return false;
1906
1907   Result.Multilibs.push_back(Default);
1908   Result.Multilibs.push_back(Alt64);
1909   Result.Multilibs.push_back(Alt32);
1910   Result.Multilibs.push_back(Altx32);
1911
1912   Result.Multilibs.FilterOut(NonExistent);
1913
1914   Multilib::flags_list Flags;
1915   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1916   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1917   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1918
1919   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1920     return false;
1921
1922   if (Result.SelectedMultilib == Alt64 ||
1923       Result.SelectedMultilib == Alt32 ||
1924       Result.SelectedMultilib == Altx32)
1925     Result.BiarchSibling = Default;
1926
1927   return true;
1928 }
1929
1930 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1931     const llvm::Triple &TargetTriple, const ArgList &Args,
1932     const std::string &LibDir, StringRef CandidateTriple,
1933     bool NeedsBiarchSuffix) {
1934   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1935   // There are various different suffixes involving the triple we
1936   // check for. We also record what is necessary to walk from each back
1937   // up to the lib directory.
1938   const std::string LibSuffixes[] = {
1939     "/gcc/" + CandidateTriple.str(),
1940     // Debian puts cross-compilers in gcc-cross
1941     "/gcc-cross/" + CandidateTriple.str(),
1942     "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1943
1944     // The Freescale PPC SDK has the gcc libraries in
1945     // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1946     "/" + CandidateTriple.str(),
1947
1948     // Ubuntu has a strange mis-matched pair of triples that this happens to
1949     // match.
1950     // FIXME: It may be worthwhile to generalize this and look for a second
1951     // triple.
1952     "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1953   };
1954   const std::string InstallSuffixes[] = {
1955     "/../../..",    // gcc/
1956     "/../../..",    // gcc-cross/
1957     "/../../../..", // <triple>/gcc/
1958     "/../..",       // <triple>/
1959     "/../../../.."  // i386-linux-gnu/gcc/<triple>/
1960   };
1961   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1962   const unsigned NumLibSuffixes =
1963       (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1964   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1965     StringRef LibSuffix = LibSuffixes[i];
1966     std::error_code EC;
1967     for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1968          !EC && LI != LE; LI = LI.increment(EC)) {
1969       StringRef VersionText = llvm::sys::path::filename(LI->path());
1970       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1971       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
1972         if (!CandidateGCCInstallPaths.insert(LI->path()).second)
1973           continue; // Saw this path before; no need to look at it again.
1974       if (CandidateVersion.isOlderThan(4, 1, 1))
1975         continue;
1976       if (CandidateVersion <= Version)
1977         continue;
1978
1979       DetectedMultilibs Detected;
1980
1981       // Debian mips multilibs behave more like the rest of the biarch ones,
1982       // so handle them there
1983       if (isMipsArch(TargetArch)) {
1984         if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected))
1985           continue;
1986       } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args,
1987                                       NeedsBiarchSuffix, Detected)) {
1988         continue;
1989       }
1990
1991       Multilibs = Detected.Multilibs;
1992       SelectedMultilib = Detected.SelectedMultilib;
1993       BiarchSibling = Detected.BiarchSibling;
1994       Version = CandidateVersion;
1995       GCCTriple.setTriple(CandidateTriple);
1996       // FIXME: We hack together the directory name here instead of
1997       // using LI to ensure stable path separators across Windows and
1998       // Linux.
1999       GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
2000       GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
2001       IsValid = true;
2002     }
2003   }
2004 }
2005
2006 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
2007                          const ArgList &Args)
2008   : ToolChain(D, Triple, Args), GCCInstallation() {
2009   getProgramPaths().push_back(getDriver().getInstalledDir());
2010   if (getDriver().getInstalledDir() != getDriver().Dir)
2011     getProgramPaths().push_back(getDriver().Dir);
2012 }
2013
2014 Generic_GCC::~Generic_GCC() {
2015 }
2016
2017 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2018   switch (AC) {
2019   case Action::PreprocessJobClass:
2020     if (!Preprocess)
2021       Preprocess.reset(new tools::gcc::Preprocess(*this));
2022     return Preprocess.get();
2023   case Action::CompileJobClass:
2024     if (!Compile)
2025       Compile.reset(new tools::gcc::Compile(*this));
2026     return Compile.get();
2027   default:
2028     return ToolChain::getTool(AC);
2029   }
2030 }
2031
2032 Tool *Generic_GCC::buildAssembler() const {
2033   return new tools::gnutools::Assemble(*this);
2034 }
2035
2036 Tool *Generic_GCC::buildLinker() const {
2037   return new tools::gcc::Link(*this);
2038 }
2039
2040 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2041   // Print the information about how we detected the GCC installation.
2042   GCCInstallation.print(OS);
2043 }
2044
2045 bool Generic_GCC::IsUnwindTablesDefault() const {
2046   return getArch() == llvm::Triple::x86_64;
2047 }
2048
2049 bool Generic_GCC::isPICDefault() const {
2050   return false;
2051 }
2052
2053 bool Generic_GCC::isPIEDefault() const {
2054   return false;
2055 }
2056
2057 bool Generic_GCC::isPICDefaultForced() const {
2058   return false;
2059 }
2060
2061 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2062   return getTriple().getArch() == llvm::Triple::x86 ||
2063          getTriple().getArch() == llvm::Triple::x86_64 ||
2064          getTriple().getArch() == llvm::Triple::aarch64 ||
2065          getTriple().getArch() == llvm::Triple::aarch64_be ||
2066          getTriple().getArch() == llvm::Triple::arm ||
2067          getTriple().getArch() == llvm::Triple::armeb ||
2068          getTriple().getArch() == llvm::Triple::thumb ||
2069          getTriple().getArch() == llvm::Triple::thumbeb ||
2070          getTriple().getArch() == llvm::Triple::ppc ||
2071          getTriple().getArch() == llvm::Triple::ppc64 ||
2072          getTriple().getArch() == llvm::Triple::ppc64le ||
2073          getTriple().getArch() == llvm::Triple::sparc ||
2074          getTriple().getArch() == llvm::Triple::sparcv9 ||
2075          getTriple().getArch() == llvm::Triple::systemz;
2076 }
2077
2078 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2079                                         ArgStringList &CC1Args) const {
2080   const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2081   bool UseInitArrayDefault =
2082       getTriple().getArch() == llvm::Triple::aarch64 ||
2083       getTriple().getArch() == llvm::Triple::aarch64_be ||
2084       (getTriple().getOS() == llvm::Triple::Linux &&
2085        (!V.isOlderThan(4, 7, 0) ||
2086         getTriple().getEnvironment() == llvm::Triple::Android));
2087
2088   if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2089                          options::OPT_fno_use_init_array,
2090                          UseInitArrayDefault))
2091     CC1Args.push_back("-fuse-init-array");
2092 }
2093
2094 /// Hexagon Toolchain
2095
2096 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir,
2097                                   const ArgList &Args) {
2098
2099   // Locate the rest of the toolchain ...
2100   std::string GccToolchain = getGCCToolchainDir(Args);
2101
2102   if (!GccToolchain.empty())
2103     return GccToolchain;
2104
2105   std::string InstallRelDir = InstalledDir + "/../../gnu";
2106   if (llvm::sys::fs::exists(InstallRelDir))
2107     return InstallRelDir;
2108
2109   std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
2110   if (llvm::sys::fs::exists(PrefixRelDir))
2111     return PrefixRelDir;
2112
2113   return InstallRelDir;
2114 }
2115
2116 static void GetHexagonLibraryPaths(
2117   const ArgList &Args,
2118   const std::string &Ver,
2119   const std::string &MarchString,
2120   const std::string &InstalledDir,
2121   ToolChain::path_list *LibPaths)
2122 {
2123   bool buildingLib = Args.hasArg(options::OPT_shared);
2124
2125   //----------------------------------------------------------------------------
2126   // -L Args
2127   //----------------------------------------------------------------------------
2128   for (arg_iterator
2129          it = Args.filtered_begin(options::OPT_L),
2130          ie = Args.filtered_end();
2131        it != ie;
2132        ++it) {
2133     for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
2134       LibPaths->push_back((*it)->getValue(i));
2135   }
2136
2137   //----------------------------------------------------------------------------
2138   // Other standard paths
2139   //----------------------------------------------------------------------------
2140   const std::string MarchSuffix = "/" + MarchString;
2141   const std::string G0Suffix = "/G0";
2142   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
2143   const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/";
2144
2145   // lib/gcc/hexagon/...
2146   std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
2147   if (buildingLib) {
2148     LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
2149     LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
2150   }
2151   LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
2152   LibPaths->push_back(LibGCCHexagonDir + Ver);
2153
2154   // lib/gcc/...
2155   LibPaths->push_back(RootDir + "lib/gcc");
2156
2157   // hexagon/lib/...
2158   std::string HexagonLibDir = RootDir + "hexagon/lib";
2159   if (buildingLib) {
2160     LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
2161     LibPaths->push_back(HexagonLibDir + G0Suffix);
2162   }
2163   LibPaths->push_back(HexagonLibDir + MarchSuffix);
2164   LibPaths->push_back(HexagonLibDir);
2165 }
2166
2167 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
2168                        const ArgList &Args)
2169   : Linux(D, Triple, Args) {
2170   const std::string InstalledDir(getDriver().getInstalledDir());
2171   const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args);
2172
2173   // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2174   // program paths
2175   const std::string BinDir(GnuDir + "/bin");
2176   if (llvm::sys::fs::exists(BinDir))
2177     getProgramPaths().push_back(BinDir);
2178
2179   // Determine version of GCC libraries and headers to use.
2180   const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
2181   std::error_code ec;
2182   GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
2183   for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
2184        !ec && di != de; di = di.increment(ec)) {
2185     GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
2186     if (MaxVersion < cv)
2187       MaxVersion = cv;
2188   }
2189   GCCLibAndIncVersion = MaxVersion;
2190
2191   ToolChain::path_list *LibPaths= &getFilePaths();
2192
2193   // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2194   // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2195   // support 'linux' we'll need to fix this up
2196   LibPaths->clear();
2197
2198   GetHexagonLibraryPaths(
2199     Args,
2200     GetGCCLibAndIncVersion(),
2201     GetTargetCPU(Args),
2202     InstalledDir,
2203     LibPaths);
2204 }
2205
2206 Hexagon_TC::~Hexagon_TC() {
2207 }
2208
2209 Tool *Hexagon_TC::buildAssembler() const {
2210   return new tools::hexagon::Assemble(*this);
2211 }
2212
2213 Tool *Hexagon_TC::buildLinker() const {
2214   return new tools::hexagon::Link(*this);
2215 }
2216
2217 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2218                                            ArgStringList &CC1Args) const {
2219   const Driver &D = getDriver();
2220
2221   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2222       DriverArgs.hasArg(options::OPT_nostdlibinc))
2223     return;
2224
2225   std::string Ver(GetGCCLibAndIncVersion());
2226   std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs);
2227   std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
2228   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
2229   addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
2230   addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
2231 }
2232
2233 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2234                                               ArgStringList &CC1Args) const {
2235
2236   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2237       DriverArgs.hasArg(options::OPT_nostdincxx))
2238     return;
2239
2240   const Driver &D = getDriver();
2241   std::string Ver(GetGCCLibAndIncVersion());
2242   SmallString<128> IncludeDir(
2243       Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs));
2244
2245   llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
2246   llvm::sys::path::append(IncludeDir, Ver);
2247   addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
2248 }
2249
2250 ToolChain::CXXStdlibType
2251 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
2252   Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2253   if (!A)
2254     return ToolChain::CST_Libstdcxx;
2255
2256   StringRef Value = A->getValue();
2257   if (Value != "libstdc++") {
2258     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2259       << A->getAsString(Args);
2260   }
2261
2262   return ToolChain::CST_Libstdcxx;
2263 }
2264
2265 static int getHexagonVersion(const ArgList &Args) {
2266   Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ);
2267   // Select the default CPU (v4) if none was given.
2268   if (!A)
2269     return 4;
2270
2271   // FIXME: produce errors if we cannot parse the version.
2272   StringRef WhichHexagon = A->getValue();
2273   if (WhichHexagon.startswith("hexagonv")) {
2274     int Val;
2275     if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val))
2276       return Val;
2277   }
2278   if (WhichHexagon.startswith("v")) {
2279     int Val;
2280     if (!WhichHexagon.substr(1).getAsInteger(10, Val))
2281       return Val;
2282   }
2283
2284   // FIXME: should probably be an error.
2285   return 4;
2286 }
2287
2288 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
2289 {
2290   int V = getHexagonVersion(Args);
2291   // FIXME: We don't support versions < 4. We should error on them.
2292   switch (V) {
2293   default:
2294     llvm_unreachable("Unexpected version");
2295   case 5:
2296     return "v5";
2297   case 4:
2298     return "v4";
2299   case 3:
2300     return "v3";
2301   case 2:
2302     return "v2";
2303   case 1:
2304     return "v1";
2305   }
2306 }
2307 // End Hexagon
2308
2309 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2310 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2311 /// Currently does not support anything else but compilation.
2312
2313 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
2314                            const ArgList &Args)
2315   : ToolChain(D, Triple, Args) {
2316   // Path mangling to find libexec
2317   std::string Path(getDriver().Dir);
2318
2319   Path += "/../libexec";
2320   getProgramPaths().push_back(Path);
2321 }
2322
2323 TCEToolChain::~TCEToolChain() {
2324 }
2325
2326 bool TCEToolChain::IsMathErrnoDefault() const {
2327   return true;
2328 }
2329
2330 bool TCEToolChain::isPICDefault() const {
2331   return false;
2332 }
2333
2334 bool TCEToolChain::isPIEDefault() const {
2335   return false;
2336 }
2337
2338 bool TCEToolChain::isPICDefaultForced() const {
2339   return false;
2340 }
2341
2342 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2343
2344 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2345   : Generic_ELF(D, Triple, Args) {
2346   getFilePaths().push_back(getDriver().Dir + "/../lib");
2347   getFilePaths().push_back("/usr/lib");
2348 }
2349
2350 Tool *OpenBSD::buildAssembler() const {
2351   return new tools::openbsd::Assemble(*this);
2352 }
2353
2354 Tool *OpenBSD::buildLinker() const {
2355   return new tools::openbsd::Link(*this);
2356 }
2357
2358 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2359
2360 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2361   : Generic_ELF(D, Triple, Args) {
2362   getFilePaths().push_back(getDriver().Dir + "/../lib");
2363   getFilePaths().push_back("/usr/lib");
2364 }
2365
2366 Tool *Bitrig::buildAssembler() const {
2367   return new tools::bitrig::Assemble(*this);
2368 }
2369
2370 Tool *Bitrig::buildLinker() const {
2371   return new tools::bitrig::Link(*this);
2372 }
2373
2374 ToolChain::CXXStdlibType
2375 Bitrig::GetCXXStdlibType(const ArgList &Args) const {
2376   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2377     StringRef Value = A->getValue();
2378     if (Value == "libstdc++")
2379       return ToolChain::CST_Libstdcxx;
2380     if (Value == "libc++")
2381       return ToolChain::CST_Libcxx;
2382
2383     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2384       << A->getAsString(Args);
2385   }
2386   return ToolChain::CST_Libcxx;
2387 }
2388
2389 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2390                                           ArgStringList &CC1Args) const {
2391   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2392       DriverArgs.hasArg(options::OPT_nostdincxx))
2393     return;
2394
2395   switch (GetCXXStdlibType(DriverArgs)) {
2396   case ToolChain::CST_Libcxx:
2397     addSystemInclude(DriverArgs, CC1Args,
2398                      getDriver().SysRoot + "/usr/include/c++/v1");
2399     break;
2400   case ToolChain::CST_Libstdcxx:
2401     addSystemInclude(DriverArgs, CC1Args,
2402                      getDriver().SysRoot + "/usr/include/c++/stdc++");
2403     addSystemInclude(DriverArgs, CC1Args,
2404                      getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
2405
2406     StringRef Triple = getTriple().str();
2407     if (Triple.startswith("amd64"))
2408       addSystemInclude(DriverArgs, CC1Args,
2409                        getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
2410                        Triple.substr(5));
2411     else
2412       addSystemInclude(DriverArgs, CC1Args,
2413                        getDriver().SysRoot + "/usr/include/c++/stdc++/" +
2414                        Triple);
2415     break;
2416   }
2417 }
2418
2419 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
2420                                  ArgStringList &CmdArgs) const {
2421   switch (GetCXXStdlibType(Args)) {
2422   case ToolChain::CST_Libcxx:
2423     CmdArgs.push_back("-lc++");
2424     CmdArgs.push_back("-lc++abi");
2425     CmdArgs.push_back("-lpthread");
2426     break;
2427   case ToolChain::CST_Libstdcxx:
2428     CmdArgs.push_back("-lstdc++");
2429     break;
2430   }
2431 }
2432
2433 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
2434
2435 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2436   : Generic_ELF(D, Triple, Args) {
2437
2438   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
2439   // back to '/usr/lib' if it doesn't exist.
2440   if ((Triple.getArch() == llvm::Triple::x86 ||
2441        Triple.getArch() == llvm::Triple::ppc) &&
2442       llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
2443     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
2444   else
2445     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
2446 }
2447
2448 ToolChain::CXXStdlibType
2449 FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
2450   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2451     StringRef Value = A->getValue();
2452     if (Value == "libstdc++")
2453       return ToolChain::CST_Libstdcxx;
2454     if (Value == "libc++")
2455       return ToolChain::CST_Libcxx;
2456
2457     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2458       << A->getAsString(Args);
2459   }
2460   if (getTriple().getOSMajorVersion() >= 10) 
2461     return ToolChain::CST_Libcxx;
2462   return ToolChain::CST_Libstdcxx;
2463 }
2464
2465 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2466                                            ArgStringList &CC1Args) const {
2467   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2468       DriverArgs.hasArg(options::OPT_nostdincxx))
2469     return;
2470
2471   switch (GetCXXStdlibType(DriverArgs)) {
2472   case ToolChain::CST_Libcxx:
2473     addSystemInclude(DriverArgs, CC1Args,
2474                      getDriver().SysRoot + "/usr/include/c++/v1");
2475     break;
2476   case ToolChain::CST_Libstdcxx:
2477     addSystemInclude(DriverArgs, CC1Args,
2478                      getDriver().SysRoot + "/usr/include/c++/4.2");
2479     addSystemInclude(DriverArgs, CC1Args,
2480                      getDriver().SysRoot + "/usr/include/c++/4.2/backward");
2481     break;
2482   }
2483 }
2484
2485 Tool *FreeBSD::buildAssembler() const {
2486   return new tools::freebsd::Assemble(*this);
2487 }
2488
2489 Tool *FreeBSD::buildLinker() const {
2490   return new tools::freebsd::Link(*this);
2491 }
2492
2493 bool FreeBSD::UseSjLjExceptions() const {
2494   // FreeBSD uses SjLj exceptions on ARM oabi.
2495   switch (getTriple().getEnvironment()) {
2496   case llvm::Triple::GNUEABIHF:
2497   case llvm::Triple::GNUEABI:
2498   case llvm::Triple::EABI:
2499     return false;
2500
2501   default:
2502     return (getTriple().getArch() == llvm::Triple::arm ||
2503             getTriple().getArch() == llvm::Triple::thumb);
2504   }
2505 }
2506
2507 bool FreeBSD::HasNativeLLVMSupport() const {
2508   return true;
2509 }
2510
2511 bool FreeBSD::isPIEDefault() const {
2512   return getSanitizerArgs().requiresPIE();
2513 }
2514
2515 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
2516
2517 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2518   : Generic_ELF(D, Triple, Args) {
2519
2520   if (getDriver().UseStdLib) {
2521     // When targeting a 32-bit platform, try the special directory used on
2522     // 64-bit hosts, and only fall back to the main library directory if that
2523     // doesn't work.
2524     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
2525     // what all logic is needed to emulate the '=' prefix here.
2526     switch (Triple.getArch()) {
2527     case llvm::Triple::x86:
2528       getFilePaths().push_back("=/usr/lib/i386");
2529       break;
2530     case llvm::Triple::arm:
2531     case llvm::Triple::armeb:
2532     case llvm::Triple::thumb:
2533     case llvm::Triple::thumbeb:
2534       switch (Triple.getEnvironment()) {
2535       case llvm::Triple::EABI:
2536       case llvm::Triple::GNUEABI:
2537         getFilePaths().push_back("=/usr/lib/eabi");
2538         break;
2539       case llvm::Triple::EABIHF:
2540       case llvm::Triple::GNUEABIHF:
2541         getFilePaths().push_back("=/usr/lib/eabihf");
2542         break;
2543       default:
2544         getFilePaths().push_back("=/usr/lib/oabi");
2545         break;
2546       }
2547       break;
2548     case llvm::Triple::mips64:
2549     case llvm::Triple::mips64el:
2550       if (tools::mips::hasMipsAbiArg(Args, "o32"))
2551         getFilePaths().push_back("=/usr/lib/o32");
2552       else if (tools::mips::hasMipsAbiArg(Args, "64"))
2553         getFilePaths().push_back("=/usr/lib/64");
2554       break;
2555     case llvm::Triple::ppc:
2556       getFilePaths().push_back("=/usr/lib/powerpc");
2557       break;
2558     case llvm::Triple::sparc:
2559       getFilePaths().push_back("=/usr/lib/sparc");
2560       break;
2561     default:
2562       break;
2563     }
2564
2565     getFilePaths().push_back("=/usr/lib");
2566   }
2567 }
2568
2569 Tool *NetBSD::buildAssembler() const {
2570   return new tools::netbsd::Assemble(*this);
2571 }
2572
2573 Tool *NetBSD::buildLinker() const {
2574   return new tools::netbsd::Link(*this);
2575 }
2576
2577 ToolChain::CXXStdlibType
2578 NetBSD::GetCXXStdlibType(const ArgList &Args) const {
2579   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2580     StringRef Value = A->getValue();
2581     if (Value == "libstdc++")
2582       return ToolChain::CST_Libstdcxx;
2583     if (Value == "libc++")
2584       return ToolChain::CST_Libcxx;
2585
2586     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2587       << A->getAsString(Args);
2588   }
2589
2590   unsigned Major, Minor, Micro;
2591   getTriple().getOSVersion(Major, Minor, Micro);
2592   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
2593     switch (getArch()) {
2594     case llvm::Triple::aarch64:
2595     case llvm::Triple::arm:
2596     case llvm::Triple::armeb:
2597     case llvm::Triple::thumb:
2598     case llvm::Triple::thumbeb:
2599     case llvm::Triple::ppc:
2600     case llvm::Triple::ppc64:
2601     case llvm::Triple::ppc64le:
2602     case llvm::Triple::x86:
2603     case llvm::Triple::x86_64:
2604       return ToolChain::CST_Libcxx;
2605     default:
2606       break;
2607     }
2608   }
2609   return ToolChain::CST_Libstdcxx;
2610 }
2611
2612 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2613                                           ArgStringList &CC1Args) const {
2614   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2615       DriverArgs.hasArg(options::OPT_nostdincxx))
2616     return;
2617
2618   switch (GetCXXStdlibType(DriverArgs)) {
2619   case ToolChain::CST_Libcxx:
2620     addSystemInclude(DriverArgs, CC1Args,
2621                      getDriver().SysRoot + "/usr/include/c++/");
2622     break;
2623   case ToolChain::CST_Libstdcxx:
2624     addSystemInclude(DriverArgs, CC1Args,
2625                      getDriver().SysRoot + "/usr/include/g++");
2626     addSystemInclude(DriverArgs, CC1Args,
2627                      getDriver().SysRoot + "/usr/include/g++/backward");
2628     break;
2629   }
2630 }
2631
2632 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
2633
2634 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2635   : Generic_ELF(D, Triple, Args) {
2636   getFilePaths().push_back(getDriver().Dir + "/../lib");
2637   getFilePaths().push_back("/usr/lib");
2638 }
2639
2640 Tool *Minix::buildAssembler() const {
2641   return new tools::minix::Assemble(*this);
2642 }
2643
2644 Tool *Minix::buildLinker() const {
2645   return new tools::minix::Link(*this);
2646 }
2647
2648 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2649
2650 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
2651                  const ArgList &Args)
2652   : Generic_GCC(D, Triple, Args) {
2653
2654   getProgramPaths().push_back(getDriver().getInstalledDir());
2655   if (getDriver().getInstalledDir() != getDriver().Dir)
2656     getProgramPaths().push_back(getDriver().Dir);
2657
2658   getFilePaths().push_back(getDriver().Dir + "/../lib");
2659   getFilePaths().push_back("/usr/lib");
2660 }
2661
2662 Tool *Solaris::buildAssembler() const {
2663   return new tools::solaris::Assemble(*this);
2664 }
2665
2666 Tool *Solaris::buildLinker() const {
2667   return new tools::solaris::Link(*this);
2668 }
2669
2670 /// Distribution (very bare-bones at the moment).
2671
2672 enum Distro {
2673   ArchLinux,
2674   DebianLenny,
2675   DebianSqueeze,
2676   DebianWheezy,
2677   DebianJessie,
2678   Exherbo,
2679   RHEL4,
2680   RHEL5,
2681   RHEL6,
2682   Fedora,
2683   OpenSUSE,
2684   UbuntuHardy,
2685   UbuntuIntrepid,
2686   UbuntuJaunty,
2687   UbuntuKarmic,
2688   UbuntuLucid,
2689   UbuntuMaverick,
2690   UbuntuNatty,
2691   UbuntuOneiric,
2692   UbuntuPrecise,
2693   UbuntuQuantal,
2694   UbuntuRaring,
2695   UbuntuSaucy,
2696   UbuntuTrusty,
2697   UnknownDistro
2698 };
2699
2700 static bool IsRedhat(enum Distro Distro) {
2701   return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL6);
2702 }
2703
2704 static bool IsOpenSUSE(enum Distro Distro) {
2705   return Distro == OpenSUSE;
2706 }
2707
2708 static bool IsDebian(enum Distro Distro) {
2709   return Distro >= DebianLenny && Distro <= DebianJessie;
2710 }
2711
2712 static bool IsUbuntu(enum Distro Distro) {
2713   return Distro >= UbuntuHardy && Distro <= UbuntuTrusty;
2714 }
2715
2716 static Distro DetectDistro(llvm::Triple::ArchType Arch) {
2717   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2718       llvm::MemoryBuffer::getFile("/etc/lsb-release");
2719   if (File) {
2720     StringRef Data = File.get()->getBuffer();
2721     SmallVector<StringRef, 16> Lines;
2722     Data.split(Lines, "\n");
2723     Distro Version = UnknownDistro;
2724     for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2725       if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2726         Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
2727           .Case("hardy", UbuntuHardy)
2728           .Case("intrepid", UbuntuIntrepid)
2729           .Case("jaunty", UbuntuJaunty)
2730           .Case("karmic", UbuntuKarmic)
2731           .Case("lucid", UbuntuLucid)
2732           .Case("maverick", UbuntuMaverick)
2733           .Case("natty", UbuntuNatty)
2734           .Case("oneiric", UbuntuOneiric)
2735           .Case("precise", UbuntuPrecise)
2736           .Case("quantal", UbuntuQuantal)
2737           .Case("raring", UbuntuRaring)
2738           .Case("saucy", UbuntuSaucy)
2739           .Case("trusty", UbuntuTrusty)
2740           .Default(UnknownDistro);
2741     return Version;
2742   }
2743
2744   File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
2745   if (File) {
2746     StringRef Data = File.get()->getBuffer();
2747     if (Data.startswith("Fedora release"))
2748       return Fedora;
2749     if (Data.startswith("Red Hat Enterprise Linux") ||
2750         Data.startswith("CentOS")) {
2751       if (Data.find("release 6") != StringRef::npos)
2752         return RHEL6;
2753       else if (Data.find("release 5") != StringRef::npos)
2754         return RHEL5;
2755       else if (Data.find("release 4") != StringRef::npos)
2756         return RHEL4;
2757     }
2758     return UnknownDistro;
2759   }
2760
2761   File = llvm::MemoryBuffer::getFile("/etc/debian_version");
2762   if (File) {
2763     StringRef Data = File.get()->getBuffer();
2764     if (Data[0] == '5')
2765       return DebianLenny;
2766     else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2767       return DebianSqueeze;
2768     else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
2769       return DebianWheezy;
2770     else if (Data.startswith("jessie/sid")  || Data[0] == '8')
2771       return DebianJessie;
2772     return UnknownDistro;
2773   }
2774
2775   if (llvm::sys::fs::exists("/etc/SuSE-release"))
2776     return OpenSUSE;
2777
2778   if (llvm::sys::fs::exists("/etc/exherbo-release"))
2779     return Exherbo;
2780
2781   if (llvm::sys::fs::exists("/etc/arch-release"))
2782     return ArchLinux;
2783
2784   return UnknownDistro;
2785 }
2786
2787 /// \brief Get our best guess at the multiarch triple for a target.
2788 ///
2789 /// Debian-based systems are starting to use a multiarch setup where they use
2790 /// a target-triple directory in the library and header search paths.
2791 /// Unfortunately, this triple does not align with the vanilla target triple,
2792 /// so we provide a rough mapping here.
2793 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple,
2794                                       StringRef SysRoot) {
2795   // For most architectures, just use whatever we have rather than trying to be
2796   // clever.
2797   switch (TargetTriple.getArch()) {
2798   default:
2799     return TargetTriple.str();
2800
2801     // We use the existence of '/lib/<triple>' as a directory to detect some
2802     // common linux triples that don't quite match the Clang triple for both
2803     // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2804     // regardless of what the actual target triple is.
2805   case llvm::Triple::arm:
2806   case llvm::Triple::thumb:
2807     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2808       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2809         return "arm-linux-gnueabihf";
2810     } else {
2811       if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2812         return "arm-linux-gnueabi";
2813     }
2814     return TargetTriple.str();
2815   case llvm::Triple::armeb:
2816   case llvm::Triple::thumbeb:
2817     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2818       if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
2819         return "armeb-linux-gnueabihf";
2820     } else {
2821       if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi"))
2822         return "armeb-linux-gnueabi";
2823     }
2824     return TargetTriple.str();
2825   case llvm::Triple::x86:
2826     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2827       return "i386-linux-gnu";
2828     return TargetTriple.str();
2829   case llvm::Triple::x86_64:
2830     // We don't want this for x32, otherwise it will match x86_64 libs
2831     if (TargetTriple.getEnvironment() != llvm::Triple::GNUX32 &&
2832         llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2833       return "x86_64-linux-gnu";
2834     return TargetTriple.str();
2835   case llvm::Triple::aarch64:
2836     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2837       return "aarch64-linux-gnu";
2838     return TargetTriple.str();
2839   case llvm::Triple::aarch64_be:
2840     if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
2841       return "aarch64_be-linux-gnu";
2842     return TargetTriple.str();
2843   case llvm::Triple::mips:
2844     if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2845       return "mips-linux-gnu";
2846     return TargetTriple.str();
2847   case llvm::Triple::mipsel:
2848     if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2849       return "mipsel-linux-gnu";
2850     return TargetTriple.str();
2851   case llvm::Triple::mips64:
2852     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu"))
2853       return "mips64-linux-gnu";
2854     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
2855       return "mips64-linux-gnuabi64";
2856     return TargetTriple.str();
2857   case llvm::Triple::mips64el:
2858     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu"))
2859       return "mips64el-linux-gnu";
2860     if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
2861       return "mips64el-linux-gnuabi64";
2862     return TargetTriple.str();
2863   case llvm::Triple::ppc:
2864     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2865       return "powerpc-linux-gnuspe";
2866     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2867       return "powerpc-linux-gnu";
2868     return TargetTriple.str();
2869   case llvm::Triple::ppc64:
2870     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2871       return "powerpc64-linux-gnu";
2872   case llvm::Triple::ppc64le:
2873     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
2874       return "powerpc64le-linux-gnu";
2875     return TargetTriple.str();
2876   }
2877 }
2878
2879 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2880   if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2881 }
2882
2883 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
2884   if (isMipsArch(Triple.getArch())) {
2885     // lib32 directory has a special meaning on MIPS targets.
2886     // It contains N32 ABI binaries. Use this folder if produce
2887     // code for N32 ABI only.
2888     if (tools::mips::hasMipsAbiArg(Args, "n32"))
2889       return "lib32";
2890     return Triple.isArch32Bit() ? "lib" : "lib64";
2891   }
2892
2893   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
2894   // using that variant while targeting other architectures causes problems
2895   // because the libraries are laid out in shared system roots that can't cope
2896   // with a 'lib32' library search path being considered. So we only enable
2897   // them when we know we may need it.
2898   //
2899   // FIXME: This is a bit of a hack. We should really unify this code for
2900   // reasoning about oslibdir spellings with the lib dir spellings in the
2901   // GCCInstallationDetector, but that is a more significant refactoring.
2902   if (Triple.getArch() == llvm::Triple::x86 ||
2903       Triple.getArch() == llvm::Triple::ppc)
2904     return "lib32";
2905
2906   if (Triple.getArch() == llvm::Triple::x86_64 &&
2907       Triple.getEnvironment() == llvm::Triple::GNUX32)
2908     return "libx32";
2909
2910   return Triple.isArch32Bit() ? "lib" : "lib64";
2911 }
2912
2913 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2914   : Generic_ELF(D, Triple, Args) {
2915   GCCInstallation.init(D, Triple, Args);
2916   Multilibs = GCCInstallation.getMultilibs();
2917   llvm::Triple::ArchType Arch = Triple.getArch();
2918   std::string SysRoot = computeSysRoot();
2919
2920   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2921   // least) put various tools in a triple-prefixed directory off of the parent
2922   // of the GCC installation. We use the GCC triple here to ensure that we end
2923   // up with tools that support the same amount of cross compiling as the
2924   // detected GCC installation. For example, if we find a GCC installation
2925   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2926   // used to target i386.
2927   // FIXME: This seems unlikely to be Linux-specific.
2928   ToolChain::path_list &PPaths = getProgramPaths();
2929   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2930                          GCCInstallation.getTriple().str() + "/bin").str());
2931
2932   Linker = GetLinkerPath();
2933
2934   Distro Distro = DetectDistro(Arch);
2935
2936   if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
2937     ExtraOpts.push_back("-z");
2938     ExtraOpts.push_back("relro");
2939   }
2940
2941   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2942     ExtraOpts.push_back("-X");
2943
2944   const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2945   const bool IsMips = isMipsArch(Arch);
2946
2947   if (IsMips && !SysRoot.empty())
2948     ExtraOpts.push_back("--sysroot=" + SysRoot);
2949
2950   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2951   // and the MIPS ABI require .dynsym to be sorted in different ways.
2952   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2953   // ABI requires a mapping between the GOT and the symbol table.
2954   // Android loader does not support .gnu.hash.
2955   if (!IsMips && !IsAndroid) {
2956     if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
2957         (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2958       ExtraOpts.push_back("--hash-style=gnu");
2959
2960     if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
2961         Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2962       ExtraOpts.push_back("--hash-style=both");
2963   }
2964
2965   if (IsRedhat(Distro))
2966     ExtraOpts.push_back("--no-add-needed");
2967
2968   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2969       Distro == DebianJessie || IsOpenSUSE(Distro) ||
2970       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2971       (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2972     ExtraOpts.push_back("--build-id");
2973
2974   if (IsOpenSUSE(Distro))
2975     ExtraOpts.push_back("--enable-new-dtags");
2976
2977   // The selection of paths to try here is designed to match the patterns which
2978   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2979   // This was determined by running GCC in a fake filesystem, creating all
2980   // possible permutations of these directories, and seeing which ones it added
2981   // to the link paths.
2982   path_list &Paths = getFilePaths();
2983
2984   const std::string OSLibDir = getOSLibDir(Triple, Args);
2985   const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2986
2987   // Add the multilib suffixed paths where they are available.
2988   if (GCCInstallation.isValid()) {
2989     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2990     const std::string &LibPath = GCCInstallation.getParentLibPath();
2991     const Multilib &Multilib = GCCInstallation.getMultilib();
2992
2993     // Sourcery CodeBench MIPS toolchain holds some libraries under
2994     // a biarch-like suffix of the GCC installation.
2995     addPathIfExists((GCCInstallation.getInstallPath() +
2996                      Multilib.gccSuffix()),
2997                     Paths);
2998
2999     // GCC cross compiling toolchains will install target libraries which ship
3000     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3001     // any part of the GCC installation in
3002     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3003     // debatable, but is the reality today. We need to search this tree even
3004     // when we have a sysroot somewhere else. It is the responsibility of
3005     // whomever is doing the cross build targeting a sysroot using a GCC
3006     // installation that is *not* within the system root to ensure two things:
3007     //
3008     //  1) Any DSOs that are linked in from this tree or from the install path
3009     //     above must be present on the system root and found via an
3010     //     appropriate rpath.
3011     //  2) There must not be libraries installed into
3012     //     <prefix>/<triple>/<libdir> unless they should be preferred over
3013     //     those within the system root.
3014     //
3015     // Note that this matches the GCC behavior. See the below comment for where
3016     // Clang diverges from GCC's behavior.
3017     addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3018                     Multilib.osSuffix(),
3019                     Paths);
3020
3021     // If the GCC installation we found is inside of the sysroot, we want to
3022     // prefer libraries installed in the parent prefix of the GCC installation.
3023     // It is important to *not* use these paths when the GCC installation is
3024     // outside of the system root as that can pick up unintended libraries.
3025     // This usually happens when there is an external cross compiler on the
3026     // host system, and a more minimal sysroot available that is the target of
3027     // the cross. Note that GCC does include some of these directories in some
3028     // configurations but this seems somewhere between questionable and simply
3029     // a bug.
3030     if (StringRef(LibPath).startswith(SysRoot)) {
3031       addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
3032       addPathIfExists(LibPath + "/../" + OSLibDir, Paths);
3033     }
3034   }
3035
3036   // Similar to the logic for GCC above, if we currently running Clang inside
3037   // of the requested system root, add its parent library paths to
3038   // those searched.
3039   // FIXME: It's not clear whether we should use the driver's installed
3040   // directory ('Dir' below) or the ResourceDir.
3041   if (StringRef(D.Dir).startswith(SysRoot)) {
3042     addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths);
3043     addPathIfExists(D.Dir + "/../" + OSLibDir, Paths);
3044   }
3045
3046   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
3047   addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths);
3048   addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3049   addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3050
3051   // Try walking via the GCC triple path in case of biarch or multiarch GCC
3052   // installations with strange symlinks.
3053   if (GCCInstallation.isValid()) {
3054     addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3055                     "/../../" + OSLibDir, Paths);
3056
3057     // Add the 'other' biarch variant path
3058     Multilib BiarchSibling;
3059     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3060       addPathIfExists(GCCInstallation.getInstallPath() +
3061                       BiarchSibling.gccSuffix(), Paths);
3062     }
3063
3064     // See comments above on the multilib variant for details of why this is
3065     // included even from outside the sysroot.
3066     const std::string &LibPath = GCCInstallation.getParentLibPath();
3067     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3068     const Multilib &Multilib = GCCInstallation.getMultilib();
3069     addPathIfExists(LibPath + "/../" + GCCTriple.str() +
3070                     "/lib" + Multilib.osSuffix(), Paths);
3071
3072     // See comments above on the multilib variant for details of why this is
3073     // only included from within the sysroot.
3074     if (StringRef(LibPath).startswith(SysRoot))
3075       addPathIfExists(LibPath, Paths);
3076   }
3077
3078   // Similar to the logic for GCC above, if we are currently running Clang
3079   // inside of the requested system root, add its parent library path to those
3080   // searched.
3081   // FIXME: It's not clear whether we should use the driver's installed
3082   // directory ('Dir' below) or the ResourceDir.
3083   if (StringRef(D.Dir).startswith(SysRoot))
3084     addPathIfExists(D.Dir + "/../lib", Paths);
3085
3086   addPathIfExists(SysRoot + "/lib", Paths);
3087   addPathIfExists(SysRoot + "/usr/lib", Paths);
3088 }
3089
3090 bool Linux::HasNativeLLVMSupport() const {
3091   return true;
3092 }
3093
3094 Tool *Linux::buildLinker() const {
3095   return new tools::gnutools::Link(*this);
3096 }
3097
3098 Tool *Linux::buildAssembler() const {
3099   return new tools::gnutools::Assemble(*this);
3100 }
3101
3102 std::string Linux::computeSysRoot() const {
3103   if (!getDriver().SysRoot.empty())
3104     return getDriver().SysRoot;
3105
3106   if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3107     return std::string();
3108
3109   // Standalone MIPS toolchains use different names for sysroot folder
3110   // and put it into different places. Here we try to check some known
3111   // variants.
3112
3113   const StringRef InstallDir = GCCInstallation.getInstallPath();
3114   const StringRef TripleStr = GCCInstallation.getTriple().str();
3115   const Multilib &Multilib = GCCInstallation.getMultilib();
3116
3117   std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" +
3118                       Multilib.osSuffix()).str();
3119
3120   if (llvm::sys::fs::exists(Path))
3121     return Path;
3122
3123   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3124
3125   if (llvm::sys::fs::exists(Path))
3126     return Path;
3127
3128   return std::string();
3129 }
3130
3131 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3132                                       ArgStringList &CC1Args) const {
3133   const Driver &D = getDriver();
3134   std::string SysRoot = computeSysRoot();
3135
3136   if (DriverArgs.hasArg(options::OPT_nostdinc))
3137     return;
3138
3139   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3140     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3141
3142   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3143     SmallString<128> P(D.ResourceDir);
3144     llvm::sys::path::append(P, "include");
3145     addSystemInclude(DriverArgs, CC1Args, P.str());
3146   }
3147
3148   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3149     return;
3150
3151   // Check for configure-time C include directories.
3152   StringRef CIncludeDirs(C_INCLUDE_DIRS);
3153   if (CIncludeDirs != "") {
3154     SmallVector<StringRef, 5> dirs;
3155     CIncludeDirs.split(dirs, ":");
3156     for (StringRef dir : dirs) {
3157       StringRef Prefix =
3158           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3159       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3160     }
3161     return;
3162   }
3163
3164   // Lacking those, try to detect the correct set of system includes for the
3165   // target triple.
3166
3167   // Add include directories specific to the selected multilib set and multilib.
3168   if (GCCInstallation.isValid()) {
3169     auto Callback = Multilibs.includeDirsCallback();
3170     if (Callback) {
3171       const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3172                                          GCCInstallation.getTriple().str(),
3173                                          GCCInstallation.getMultilib());
3174       for (const auto &Path : IncludePaths)
3175         addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3176     }
3177   }
3178
3179   // Implement generic Debian multiarch support.
3180   const StringRef X86_64MultiarchIncludeDirs[] = {
3181     "/usr/include/x86_64-linux-gnu",
3182
3183     // FIXME: These are older forms of multiarch. It's not clear that they're
3184     // in use in any released version of Debian, so we should consider
3185     // removing them.
3186     "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
3187   };
3188   const StringRef X86MultiarchIncludeDirs[] = {
3189     "/usr/include/i386-linux-gnu",
3190
3191     // FIXME: These are older forms of multiarch. It's not clear that they're
3192     // in use in any released version of Debian, so we should consider
3193     // removing them.
3194     "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3195     "/usr/include/i486-linux-gnu"
3196   };
3197   const StringRef AArch64MultiarchIncludeDirs[] = {
3198     "/usr/include/aarch64-linux-gnu"
3199   };
3200   const StringRef ARMMultiarchIncludeDirs[] = {
3201     "/usr/include/arm-linux-gnueabi"
3202   };
3203   const StringRef ARMHFMultiarchIncludeDirs[] = {
3204     "/usr/include/arm-linux-gnueabihf"
3205   };
3206   const StringRef MIPSMultiarchIncludeDirs[] = {
3207     "/usr/include/mips-linux-gnu"
3208   };
3209   const StringRef MIPSELMultiarchIncludeDirs[] = {
3210     "/usr/include/mipsel-linux-gnu"
3211   };
3212   const StringRef MIPS64MultiarchIncludeDirs[] = {
3213     "/usr/include/mips64-linux-gnu",
3214     "/usr/include/mips64-linux-gnuabi64"
3215   };
3216   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3217     "/usr/include/mips64el-linux-gnu",
3218     "/usr/include/mips64el-linux-gnuabi64"
3219   };
3220   const StringRef PPCMultiarchIncludeDirs[] = {
3221     "/usr/include/powerpc-linux-gnu"
3222   };
3223   const StringRef PPC64MultiarchIncludeDirs[] = {
3224     "/usr/include/powerpc64-linux-gnu"
3225   };
3226   const StringRef PPC64LEMultiarchIncludeDirs[] = {
3227     "/usr/include/powerpc64le-linux-gnu"
3228   };
3229   ArrayRef<StringRef> MultiarchIncludeDirs;
3230   if (getTriple().getArch() == llvm::Triple::x86_64) {
3231     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3232   } else if (getTriple().getArch() == llvm::Triple::x86) {
3233     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3234   } else if (getTriple().getArch() == llvm::Triple::aarch64 ||
3235              getTriple().getArch() == llvm::Triple::aarch64_be) {
3236     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3237   } else if (getTriple().getArch() == llvm::Triple::arm) {
3238     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3239       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3240     else
3241       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3242   } else if (getTriple().getArch() == llvm::Triple::mips) {
3243     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3244   } else if (getTriple().getArch() == llvm::Triple::mipsel) {
3245     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3246   } else if (getTriple().getArch() == llvm::Triple::mips64) {
3247     MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3248   } else if (getTriple().getArch() == llvm::Triple::mips64el) {
3249     MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3250   } else if (getTriple().getArch() == llvm::Triple::ppc) {
3251     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3252   } else if (getTriple().getArch() == llvm::Triple::ppc64) {
3253     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3254   } else if (getTriple().getArch() == llvm::Triple::ppc64le) {
3255     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
3256   }
3257   for (StringRef Dir : MultiarchIncludeDirs) {
3258     if (llvm::sys::fs::exists(SysRoot + Dir)) {
3259       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
3260       break;
3261     }
3262   }
3263
3264   if (getTriple().getOS() == llvm::Triple::RTEMS)
3265     return;
3266
3267   // Add an include of '/include' directly. This isn't provided by default by
3268   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
3269   // add even when Clang is acting as-if it were a system compiler.
3270   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
3271
3272   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
3273 }
3274
3275 /// \brief Helper to add the variant paths of a libstdc++ installation.
3276 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
3277                                                 StringRef GCCTriple,
3278                                                 StringRef GCCMultiarchTriple,
3279                                                 StringRef TargetMultiarchTriple,
3280                                                 Twine IncludeSuffix,
3281                                                 const ArgList &DriverArgs,
3282                                                 ArgStringList &CC1Args) {
3283   if (!llvm::sys::fs::exists(Base + Suffix))
3284     return false;
3285
3286   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
3287
3288   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
3289   // that path exists or we have neither a GCC nor target multiarch triple, use
3290   // this vanilla search path.
3291   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
3292       llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
3293     addSystemInclude(DriverArgs, CC1Args,
3294                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
3295   } else {
3296     // Otherwise try to use multiarch naming schemes which have normalized the
3297     // triples and put the triple before the suffix.
3298     //
3299     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
3300     // the target triple, so we support that here.
3301     addSystemInclude(DriverArgs, CC1Args,
3302                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
3303     addSystemInclude(DriverArgs, CC1Args,
3304                      Base + "/" + TargetMultiarchTriple + Suffix);
3305   }
3306
3307   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
3308   return true;
3309 }
3310
3311 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3312                                          ArgStringList &CC1Args) const {
3313   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3314       DriverArgs.hasArg(options::OPT_nostdincxx))
3315     return;
3316
3317   // Check if libc++ has been enabled and provide its include paths if so.
3318   if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
3319     const std::string LibCXXIncludePathCandidates[] = {
3320       // The primary location is within the Clang installation.
3321       // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to
3322       // newer ABI versions.
3323       getDriver().Dir + "/../include/c++/v1",
3324
3325       // We also check the system as for a long time this is the only place Clang looked.
3326       // FIXME: We should really remove this. It doesn't make any sense.
3327       getDriver().SysRoot + "/usr/include/c++/v1"
3328     };
3329     for (const auto &IncludePath : LibCXXIncludePathCandidates) {
3330       if (!llvm::sys::fs::exists(IncludePath))
3331         continue;
3332       // Add the first candidate that exists.
3333       addSystemInclude(DriverArgs, CC1Args, IncludePath);
3334       break;
3335     }
3336     return;
3337   }
3338
3339   // We need a detected GCC installation on Linux to provide libstdc++'s
3340   // headers. We handled the libc++ case above.
3341   if (!GCCInstallation.isValid())
3342     return;
3343
3344   // By default, look for the C++ headers in an include directory adjacent to
3345   // the lib directory of the GCC installation. Note that this is expect to be
3346   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3347   StringRef LibDir = GCCInstallation.getParentLibPath();
3348   StringRef InstallDir = GCCInstallation.getInstallPath();
3349   StringRef TripleStr = GCCInstallation.getTriple().str();
3350   const Multilib &Multilib = GCCInstallation.getMultilib();
3351   const std::string GCCMultiarchTriple =
3352       getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot);
3353   const std::string TargetMultiarchTriple =
3354       getMultiarchTriple(getTriple(), getDriver().SysRoot);
3355   const GCCVersion &Version = GCCInstallation.getVersion();
3356
3357   // The primary search for libstdc++ supports multiarch variants.
3358   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
3359                                "/c++/" + Version.Text, TripleStr, GCCMultiarchTriple,
3360                                TargetMultiarchTriple,
3361                                Multilib.includeSuffix(), DriverArgs, CC1Args))
3362     return;
3363
3364   // Otherwise, fall back on a bunch of options which don't use multiarch
3365   // layouts for simplicity.
3366   const std::string LibStdCXXIncludePathCandidates[] = {
3367     // Gentoo is weird and places its headers inside the GCC install, so if the
3368     // first attempt to find the headers fails, try these patterns.
3369     InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3370         Version.MinorStr,
3371     InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3372     // Android standalone toolchain has C++ headers in yet another place.
3373     LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
3374     // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
3375     // without a subdirectory corresponding to the gcc version.
3376     LibDir.str() + "/../include/c++",
3377   };
3378
3379   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3380     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
3381                                  /*GCCMultiarchTriple*/ "",
3382                                  /*TargetMultiarchTriple*/ "",
3383                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
3384       break;
3385   }
3386 }
3387
3388 bool Linux::isPIEDefault() const {
3389   return getSanitizerArgs().requiresPIE();
3390 }
3391
3392 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
3393
3394 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
3395   : Generic_ELF(D, Triple, Args) {
3396
3397   // Path mangling to find libexec
3398   getProgramPaths().push_back(getDriver().getInstalledDir());
3399   if (getDriver().getInstalledDir() != getDriver().Dir)
3400     getProgramPaths().push_back(getDriver().Dir);
3401
3402   getFilePaths().push_back(getDriver().Dir + "/../lib");
3403   getFilePaths().push_back("/usr/lib");
3404   if (llvm::sys::fs::exists("/usr/lib/gcc47"))
3405     getFilePaths().push_back("/usr/lib/gcc47");
3406   else
3407     getFilePaths().push_back("/usr/lib/gcc44");
3408 }
3409
3410 Tool *DragonFly::buildAssembler() const {
3411   return new tools::dragonfly::Assemble(*this);
3412 }
3413
3414 Tool *DragonFly::buildLinker() const {
3415   return new tools::dragonfly::Link(*this);
3416 }
3417
3418
3419 /// XCore tool chain
3420 XCore::XCore(const Driver &D, const llvm::Triple &Triple,
3421              const ArgList &Args) : ToolChain(D, Triple, Args) {
3422   // ProgramPaths are found via 'PATH' environment variable.
3423 }
3424
3425 Tool *XCore::buildAssembler() const {
3426   return new tools::XCore::Assemble(*this);
3427 }
3428
3429 Tool *XCore::buildLinker() const {
3430   return new tools::XCore::Link(*this);
3431 }
3432
3433 bool XCore::isPICDefault() const {
3434   return false;
3435 }
3436
3437 bool XCore::isPIEDefault() const {
3438   return false;
3439 }
3440
3441 bool XCore::isPICDefaultForced() const {
3442   return false;
3443 }
3444
3445 bool XCore::SupportsProfiling() const {
3446   return false;
3447 }
3448
3449 bool XCore::hasBlocksRuntime() const {
3450   return false;
3451 }
3452
3453 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3454                                       ArgStringList &CC1Args) const {
3455   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3456       DriverArgs.hasArg(options::OPT_nostdlibinc))
3457     return;
3458   if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
3459     SmallVector<StringRef, 4> Dirs;
3460     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
3461     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3462     ArrayRef<StringRef> DirVec(Dirs);
3463     addSystemIncludes(DriverArgs, CC1Args, DirVec);
3464   }
3465 }
3466
3467 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3468                                      llvm::opt::ArgStringList &CC1Args) const {
3469   CC1Args.push_back("-nostdsysteminc");
3470 }
3471
3472 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3473                                          ArgStringList &CC1Args) const {
3474   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
3475       DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3476       DriverArgs.hasArg(options::OPT_nostdincxx))
3477     return;
3478   if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
3479     SmallVector<StringRef, 4> Dirs;
3480     const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'};
3481     StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
3482     ArrayRef<StringRef> DirVec(Dirs);
3483     addSystemIncludes(DriverArgs, CC1Args, DirVec);
3484   }
3485 }
3486
3487 void XCore::AddCXXStdlibLibArgs(const ArgList &Args,
3488                                 ArgStringList &CmdArgs) const {
3489   // We don't output any lib args. This is handled by xcc.
3490 }