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