ToolChains.cpp revision 003e1dcafcdb757a893b031431620313ee7ecbbf
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 "SanitizerArgs.h"
12#include "clang/Basic/ObjCRuntime.h"
13#include "clang/Basic/Version.h"
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 "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/Option/Arg.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Option/OptTable.h"
25#include "llvm/Option/Option.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/system_error.h"
32
33// FIXME: This needs to be listed last until we fix the broken include guards
34// in these files and the LLVM config.h files.
35#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
36
37#include <cstdlib> // ::getenv
38
39using namespace clang::driver;
40using namespace clang::driver::toolchains;
41using namespace clang;
42using namespace llvm::opt;
43
44/// Darwin - Darwin tool chain for i386 and x86_64.
45
46Darwin::Darwin(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
47  : ToolChain(D, Triple, Args), TargetInitialized(false)
48{
49  // Compute the initial Darwin version from the triple
50  unsigned Major, Minor, Micro;
51  if (!Triple.getMacOSXVersion(Major, Minor, Micro))
52    getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
53      Triple.getOSName();
54  llvm::raw_string_ostream(MacosxVersionMin)
55    << Major << '.' << Minor << '.' << Micro;
56
57  // FIXME: DarwinVersion is only used to find GCC's libexec directory.
58  // It should be removed when we stop supporting that.
59  DarwinVersion[0] = Minor + 4;
60  DarwinVersion[1] = Micro;
61  DarwinVersion[2] = 0;
62
63  // Compute the initial iOS version from the triple
64  Triple.getiOSVersion(Major, Minor, Micro);
65  llvm::raw_string_ostream(iOSVersionMin)
66    << Major << '.' << Minor << '.' << Micro;
67}
68
69types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
70  types::ID Ty = types::lookupTypeForExtension(Ext);
71
72  // Darwin always preprocesses assembly files (unless -x is used explicitly).
73  if (Ty == types::TY_PP_Asm)
74    return types::TY_Asm;
75
76  return Ty;
77}
78
79bool Darwin::HasNativeLLVMSupport() const {
80  return true;
81}
82
83/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
84ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
85  if (isTargetIPhoneOS())
86    return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
87  if (isNonFragile)
88    return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
89  return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
90}
91
92/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
93bool Darwin::hasBlocksRuntime() const {
94  if (isTargetIPhoneOS())
95    return !isIPhoneOSVersionLT(3, 2);
96  else
97    return !isMacosxVersionLT(10, 6);
98}
99
100static const char *GetArmArchForMArch(StringRef Value) {
101  return llvm::StringSwitch<const char*>(Value)
102    .Case("armv6k", "armv6")
103    .Case("armv6m", "armv6m")
104    .Case("armv5tej", "armv5")
105    .Case("xscale", "xscale")
106    .Case("armv4t", "armv4t")
107    .Case("armv7", "armv7")
108    .Cases("armv7a", "armv7-a", "armv7")
109    .Cases("armv7r", "armv7-r", "armv7")
110    .Cases("armv7em", "armv7e-m", "armv7em")
111    .Cases("armv7f", "armv7-f", "armv7f")
112    .Cases("armv7k", "armv7-k", "armv7k")
113    .Cases("armv7m", "armv7-m", "armv7m")
114    .Cases("armv7s", "armv7-s", "armv7s")
115    .Cases("armv8", "armv8a", "armv8-a", "armv8")
116    .Default(0);
117}
118
119static const char *GetArmArchForMCpu(StringRef Value) {
120  return llvm::StringSwitch<const char *>(Value)
121    .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
122    .Cases("arm10e", "arm10tdmi", "armv5")
123    .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
124    .Case("xscale", "xscale")
125    .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
126    .Case("cortex-m0", "armv6m")
127    .Cases("cortex-a8", "cortex-r4", "cortex-a9", "cortex-a15", "armv7")
128    .Case("cortex-a9-mp", "armv7f")
129    .Case("cortex-m3", "armv7m")
130    .Case("cortex-m4", "armv7em")
131    .Case("swift", "armv7s")
132    .Default(0);
133}
134
135StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
136  switch (getTriple().getArch()) {
137  default:
138    return getArchName();
139
140  case llvm::Triple::thumb:
141  case llvm::Triple::arm: {
142    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
143      if (const char *Arch = GetArmArchForMArch(A->getValue()))
144        return Arch;
145
146    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
147      if (const char *Arch = GetArmArchForMCpu(A->getValue()))
148        return Arch;
149
150    return "arm";
151  }
152  }
153}
154
155Darwin::~Darwin() {
156}
157
158std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
159                                                types::ID InputType) const {
160  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
161
162  // If the target isn't initialized (e.g., an unknown Darwin platform, return
163  // the default triple).
164  if (!isTargetInitialized())
165    return Triple.getTriple();
166
167  SmallString<16> Str;
168  Str += isTargetIPhoneOS() ? "ios" : "macosx";
169  Str += getTargetVersion().getAsString();
170  Triple.setOSName(Str);
171
172  return Triple.getTriple();
173}
174
175void Generic_ELF::anchor() {}
176
177Tool *Darwin::getTool(Action::ActionClass AC) const {
178  switch (AC) {
179  case Action::LipoJobClass:
180    if (!Lipo)
181      Lipo.reset(new tools::darwin::Lipo(*this));
182    return Lipo.get();
183  case Action::DsymutilJobClass:
184    if (!Dsymutil)
185      Dsymutil.reset(new tools::darwin::Dsymutil(*this));
186    return Dsymutil.get();
187  case Action::VerifyJobClass:
188    if (!VerifyDebug)
189      VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
190    return VerifyDebug.get();
191  default:
192    return ToolChain::getTool(AC);
193  }
194}
195
196Tool *Darwin::buildLinker() const {
197  return new tools::darwin::Link(*this);
198}
199
200Tool *Darwin::buildAssembler() const {
201  return new tools::darwin::Assemble(*this);
202}
203
204DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple,
205                         const ArgList &Args)
206  : Darwin(D, Triple, Args)
207{
208  getProgramPaths().push_back(getDriver().getInstalledDir());
209  if (getDriver().getInstalledDir() != getDriver().Dir)
210    getProgramPaths().push_back(getDriver().Dir);
211
212  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
213  getProgramPaths().push_back(getDriver().getInstalledDir());
214  if (getDriver().getInstalledDir() != getDriver().Dir)
215    getProgramPaths().push_back(getDriver().Dir);
216}
217
218void DarwinClang::AddLinkARCArgs(const ArgList &Args,
219                                 ArgStringList &CmdArgs) const {
220
221  CmdArgs.push_back("-force_load");
222  SmallString<128> P(getDriver().ClangExecutable);
223  llvm::sys::path::remove_filename(P); // 'clang'
224  llvm::sys::path::remove_filename(P); // 'bin'
225  llvm::sys::path::append(P, "lib", "arc", "libarclite_");
226  // Mash in the platform.
227  if (isTargetIOSSimulator())
228    P += "iphonesimulator";
229  else if (isTargetIPhoneOS())
230    P += "iphoneos";
231  else
232    P += "macosx";
233  P += ".a";
234
235  CmdArgs.push_back(Args.MakeArgString(P));
236}
237
238void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
239                                    ArgStringList &CmdArgs,
240                                    const char *DarwinStaticLib,
241                                    bool AlwaysLink) const {
242  SmallString<128> P(getDriver().ResourceDir);
243  llvm::sys::path::append(P, "lib", "darwin", DarwinStaticLib);
244
245  // For now, allow missing resource libraries to support developers who may
246  // not have compiler-rt checked out or integrated into their build (unless
247  // we explicitly force linking with this library).
248  if (AlwaysLink || llvm::sys::fs::exists(P.str()))
249    CmdArgs.push_back(Args.MakeArgString(P.str()));
250}
251
252void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
253                                        ArgStringList &CmdArgs) const {
254  // Darwin only supports the compiler-rt based runtime libraries.
255  switch (GetRuntimeLibType(Args)) {
256  case ToolChain::RLT_CompilerRT:
257    break;
258  default:
259    getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
260      << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
261    return;
262  }
263
264  // Darwin doesn't support real static executables, don't link any runtime
265  // libraries with -static.
266  if (Args.hasArg(options::OPT_static) ||
267      Args.hasArg(options::OPT_fapple_kext) ||
268      Args.hasArg(options::OPT_mkernel))
269    return;
270
271  // Reject -static-libgcc for now, we can deal with this when and if someone
272  // cares. This is useful in situations where someone wants to statically link
273  // something like libstdc++, and needs its runtime support routines.
274  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
275    getDriver().Diag(diag::err_drv_unsupported_opt)
276      << A->getAsString(Args);
277    return;
278  }
279
280  // If we are building profile support, link that library in.
281  if (Args.hasArg(options::OPT_fprofile_arcs) ||
282      Args.hasArg(options::OPT_fprofile_generate) ||
283      Args.hasArg(options::OPT_fcreate_profile) ||
284      Args.hasArg(options::OPT_coverage)) {
285    // Select the appropriate runtime library for the target.
286    if (isTargetIPhoneOS()) {
287      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
288    } else {
289      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
290    }
291  }
292
293  SanitizerArgs Sanitize(*this, Args);
294
295  // Add Ubsan runtime library, if required.
296  if (Sanitize.needsUbsanRt()) {
297    if (isTargetIPhoneOS()) {
298      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
299        << "-fsanitize=undefined";
300    } else {
301      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
302
303      // The Ubsan runtime library requires C++.
304      AddCXXStdlibLibArgs(Args, CmdArgs);
305    }
306  }
307
308  // Add ASAN runtime library, if required. Dynamic libraries and bundles
309  // should not be linked with the runtime library.
310  if (Sanitize.needsAsanRt()) {
311    if (isTargetIPhoneOS() && !isTargetIOSSimulator()) {
312      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
313        << "-fsanitize=address";
314    } else {
315      if (Args.hasArg(options::OPT_dynamiclib) ||
316          Args.hasArg(options::OPT_bundle)) {
317        // Assume the binary will provide the ASan runtime.
318      } else {
319        AddLinkRuntimeLib(Args, CmdArgs,
320                          "libclang_rt.asan_osx_dynamic.dylib", true);
321        // The ASAN runtime library requires C++.
322        AddCXXStdlibLibArgs(Args, CmdArgs);
323      }
324    }
325  }
326
327  // Otherwise link libSystem, then the dynamic runtime library, and finally any
328  // target specific static runtime library.
329  CmdArgs.push_back("-lSystem");
330
331  // Select the dynamic runtime library and the target specific static library.
332  if (isTargetIPhoneOS()) {
333    // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
334    // it never went into the SDK.
335    // Linking against libgcc_s.1 isn't needed for iOS 5.0+
336    if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
337      CmdArgs.push_back("-lgcc_s.1");
338
339    // We currently always need a static runtime library for iOS.
340    AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
341  } else {
342    // The dynamic runtime library was merged with libSystem for 10.6 and
343    // beyond; only 10.4 and 10.5 need an additional runtime library.
344    if (isMacosxVersionLT(10, 5))
345      CmdArgs.push_back("-lgcc_s.10.4");
346    else if (isMacosxVersionLT(10, 6))
347      CmdArgs.push_back("-lgcc_s.10.5");
348
349    // For OS X, we thought we would only need a static runtime library when
350    // targeting 10.4, to provide versions of the static functions which were
351    // omitted from 10.4.dylib.
352    //
353    // Unfortunately, that turned out to not be true, because Darwin system
354    // headers can still use eprintf on i386, and it is not exported from
355    // libSystem. Therefore, we still must provide a runtime library just for
356    // the tiny tiny handful of projects that *might* use that symbol.
357    if (isMacosxVersionLT(10, 5)) {
358      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
359    } else {
360      if (getTriple().getArch() == llvm::Triple::x86)
361        AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
362      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
363    }
364  }
365}
366
367void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
368  const OptTable &Opts = getDriver().getOpts();
369
370  // Support allowing the SDKROOT environment variable used by xcrun and other
371  // Xcode tools to define the default sysroot, by making it the default for
372  // isysroot.
373  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
374    // Warn if the path does not exist.
375    if (!llvm::sys::fs::exists(A->getValue()))
376      getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
377  } else {
378    if (char *env = ::getenv("SDKROOT")) {
379      // We only use this value as the default if it is an absolute path,
380      // exists, and it is not the root path.
381      if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
382          StringRef(env) != "/") {
383        Args.append(Args.MakeSeparateArg(
384                      0, Opts.getOption(options::OPT_isysroot), env));
385      }
386    }
387  }
388
389  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
390  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
391  Arg *iOSSimVersion = Args.getLastArg(
392    options::OPT_mios_simulator_version_min_EQ);
393
394  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
395    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
396          << OSXVersion->getAsString(Args)
397          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
398    iOSVersion = iOSSimVersion = 0;
399  } else if (iOSVersion && iOSSimVersion) {
400    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
401          << iOSVersion->getAsString(Args)
402          << iOSSimVersion->getAsString(Args);
403    iOSSimVersion = 0;
404  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
405    // If no deployment target was specified on the command line, check for
406    // environment defines.
407    StringRef OSXTarget;
408    StringRef iOSTarget;
409    StringRef iOSSimTarget;
410    if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
411      OSXTarget = env;
412    if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
413      iOSTarget = env;
414    if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
415      iOSSimTarget = env;
416
417    // If no '-miphoneos-version-min' specified on the command line and
418    // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
419    // based on -isysroot.
420    if (iOSTarget.empty()) {
421      if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
422        StringRef first, second;
423        StringRef isysroot = A->getValue();
424        llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
425        if (second != "")
426          iOSTarget = second.substr(0,3);
427      }
428    }
429
430    // If no OSX or iOS target has been specified and we're compiling for armv7,
431    // go ahead as assume we're targeting iOS.
432    if (OSXTarget.empty() && iOSTarget.empty() &&
433        (getDarwinArchName(Args) == "armv7" ||
434         getDarwinArchName(Args) == "armv7s"))
435        iOSTarget = iOSVersionMin;
436
437    // Handle conflicting deployment targets
438    //
439    // FIXME: Don't hardcode default here.
440
441    // Do not allow conflicts with the iOS simulator target.
442    if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
443      getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
444        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
445        << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
446            "IPHONEOS_DEPLOYMENT_TARGET");
447    }
448
449    // Allow conflicts among OSX and iOS for historical reasons, but choose the
450    // default platform.
451    if (!OSXTarget.empty() && !iOSTarget.empty()) {
452      if (getTriple().getArch() == llvm::Triple::arm ||
453          getTriple().getArch() == llvm::Triple::thumb)
454        OSXTarget = "";
455      else
456        iOSTarget = "";
457    }
458
459    if (!OSXTarget.empty()) {
460      const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
461      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
462      Args.append(OSXVersion);
463    } else if (!iOSTarget.empty()) {
464      const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
465      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
466      Args.append(iOSVersion);
467    } else if (!iOSSimTarget.empty()) {
468      const Option O = Opts.getOption(
469        options::OPT_mios_simulator_version_min_EQ);
470      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
471      Args.append(iOSSimVersion);
472    } else {
473      // Otherwise, assume we are targeting OS X.
474      const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
475      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
476      Args.append(OSXVersion);
477    }
478  }
479
480  // Reject invalid architecture combinations.
481  if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
482                        getTriple().getArch() != llvm::Triple::x86_64)) {
483    getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
484      << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
485  }
486
487  // Set the tool chain target information.
488  unsigned Major, Minor, Micro;
489  bool HadExtra;
490  if (OSXVersion) {
491    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
492    if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
493                                   Micro, HadExtra) || HadExtra ||
494        Major != 10 || Minor >= 100 || Micro >= 100)
495      getDriver().Diag(diag::err_drv_invalid_version_number)
496        << OSXVersion->getAsString(Args);
497  } else {
498    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
499    assert(Version && "Unknown target platform!");
500    if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
501                                   Micro, HadExtra) || HadExtra ||
502        Major >= 10 || Minor >= 100 || Micro >= 100)
503      getDriver().Diag(diag::err_drv_invalid_version_number)
504        << Version->getAsString(Args);
505  }
506
507  bool IsIOSSim = bool(iOSSimVersion);
508
509  // In GCC, the simulator historically was treated as being OS X in some
510  // contexts, like determining the link logic, despite generally being called
511  // with an iOS deployment target. For compatibility, we detect the
512  // simulator as iOS + x86, and treat it differently in a few contexts.
513  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
514                     getTriple().getArch() == llvm::Triple::x86_64))
515    IsIOSSim = true;
516
517  setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
518}
519
520void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
521                                      ArgStringList &CmdArgs) const {
522  CXXStdlibType Type = GetCXXStdlibType(Args);
523
524  switch (Type) {
525  case ToolChain::CST_Libcxx:
526    CmdArgs.push_back("-lc++");
527    break;
528
529  case ToolChain::CST_Libstdcxx: {
530    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
531    // it was previously found in the gcc lib dir. However, for all the Darwin
532    // platforms we care about it was -lstdc++.6, so we search for that
533    // explicitly if we can't see an obvious -lstdc++ candidate.
534
535    // Check in the sysroot first.
536    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
537      SmallString<128> P(A->getValue());
538      llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
539
540      if (!llvm::sys::fs::exists(P.str())) {
541        llvm::sys::path::remove_filename(P);
542        llvm::sys::path::append(P, "libstdc++.6.dylib");
543        if (llvm::sys::fs::exists(P.str())) {
544          CmdArgs.push_back(Args.MakeArgString(P.str()));
545          return;
546        }
547      }
548    }
549
550    // Otherwise, look in the root.
551    // FIXME: This should be removed someday when we don't have to care about
552    // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
553    if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") &&
554        llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) {
555      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
556      return;
557    }
558
559    // Otherwise, let the linker search.
560    CmdArgs.push_back("-lstdc++");
561    break;
562  }
563  }
564}
565
566void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
567                                   ArgStringList &CmdArgs) const {
568
569  // For Darwin platforms, use the compiler-rt-based support library
570  // instead of the gcc-provided one (which is also incidentally
571  // only present in the gcc lib dir, which makes it hard to find).
572
573  SmallString<128> P(getDriver().ResourceDir);
574  llvm::sys::path::append(P, "lib", "darwin");
575
576  // Use the newer cc_kext for iOS ARM after 6.0.
577  if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
578      !isIPhoneOSVersionLT(6, 0)) {
579    llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
580  } else {
581    llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a");
582  }
583
584  // For now, allow missing resource libraries to support developers who may
585  // not have compiler-rt checked out or integrated into their build.
586  if (llvm::sys::fs::exists(P.str()))
587    CmdArgs.push_back(Args.MakeArgString(P.str()));
588}
589
590DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
591                                      const char *BoundArch) const {
592  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
593  const OptTable &Opts = getDriver().getOpts();
594
595  // FIXME: We really want to get out of the tool chain level argument
596  // translation business, as it makes the driver functionality much
597  // more opaque. For now, we follow gcc closely solely for the
598  // purpose of easily achieving feature parity & testability. Once we
599  // have something that works, we should reevaluate each translation
600  // and try to push it down into tool specific logic.
601
602  for (ArgList::const_iterator it = Args.begin(),
603         ie = Args.end(); it != ie; ++it) {
604    Arg *A = *it;
605
606    if (A->getOption().matches(options::OPT_Xarch__)) {
607      // Skip this argument unless the architecture matches either the toolchain
608      // triple arch, or the arch being bound.
609      llvm::Triple::ArchType XarchArch =
610        tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
611      if (!(XarchArch == getArch()  ||
612            (BoundArch && XarchArch ==
613             tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
614        continue;
615
616      Arg *OriginalArg = A;
617      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
618      unsigned Prev = Index;
619      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
620
621      // If the argument parsing failed or more than one argument was
622      // consumed, the -Xarch_ argument's parameter tried to consume
623      // extra arguments. Emit an error and ignore.
624      //
625      // We also want to disallow any options which would alter the
626      // driver behavior; that isn't going to work in our model. We
627      // use isDriverOption() as an approximation, although things
628      // like -O4 are going to slip through.
629      if (!XarchArg || Index > Prev + 1) {
630        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
631          << A->getAsString(Args);
632        continue;
633      } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
634        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
635          << A->getAsString(Args);
636        continue;
637      }
638
639      XarchArg->setBaseArg(A);
640      A = XarchArg;
641
642      DAL->AddSynthesizedArg(A);
643
644      // Linker input arguments require custom handling. The problem is that we
645      // have already constructed the phase actions, so we can not treat them as
646      // "input arguments".
647      if (A->getOption().hasFlag(options::LinkerInput)) {
648        // Convert the argument into individual Zlinker_input_args.
649        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
650          DAL->AddSeparateArg(OriginalArg,
651                              Opts.getOption(options::OPT_Zlinker_input),
652                              A->getValue(i));
653
654        }
655        continue;
656      }
657    }
658
659    // Sob. These is strictly gcc compatible for the time being. Apple
660    // gcc translates options twice, which means that self-expanding
661    // options add duplicates.
662    switch ((options::ID) A->getOption().getID()) {
663    default:
664      DAL->append(A);
665      break;
666
667    case options::OPT_mkernel:
668    case options::OPT_fapple_kext:
669      DAL->append(A);
670      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
671      break;
672
673    case options::OPT_dependency_file:
674      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
675                          A->getValue());
676      break;
677
678    case options::OPT_gfull:
679      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
680      DAL->AddFlagArg(A,
681               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
682      break;
683
684    case options::OPT_gused:
685      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
686      DAL->AddFlagArg(A,
687             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
688      break;
689
690    case options::OPT_shared:
691      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
692      break;
693
694    case options::OPT_fconstant_cfstrings:
695      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
696      break;
697
698    case options::OPT_fno_constant_cfstrings:
699      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
700      break;
701
702    case options::OPT_Wnonportable_cfstrings:
703      DAL->AddFlagArg(A,
704                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
705      break;
706
707    case options::OPT_Wno_nonportable_cfstrings:
708      DAL->AddFlagArg(A,
709                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
710      break;
711
712    case options::OPT_fpascal_strings:
713      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
714      break;
715
716    case options::OPT_fno_pascal_strings:
717      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
718      break;
719    }
720  }
721
722  if (getTriple().getArch() == llvm::Triple::x86 ||
723      getTriple().getArch() == llvm::Triple::x86_64)
724    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
725      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
726
727  // Add the arch options based on the particular spelling of -arch, to match
728  // how the driver driver works.
729  if (BoundArch) {
730    StringRef Name = BoundArch;
731    const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
732    const Option MArch = Opts.getOption(options::OPT_march_EQ);
733
734    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
735    // which defines the list of which architectures we accept.
736    if (Name == "ppc")
737      ;
738    else if (Name == "ppc601")
739      DAL->AddJoinedArg(0, MCpu, "601");
740    else if (Name == "ppc603")
741      DAL->AddJoinedArg(0, MCpu, "603");
742    else if (Name == "ppc604")
743      DAL->AddJoinedArg(0, MCpu, "604");
744    else if (Name == "ppc604e")
745      DAL->AddJoinedArg(0, MCpu, "604e");
746    else if (Name == "ppc750")
747      DAL->AddJoinedArg(0, MCpu, "750");
748    else if (Name == "ppc7400")
749      DAL->AddJoinedArg(0, MCpu, "7400");
750    else if (Name == "ppc7450")
751      DAL->AddJoinedArg(0, MCpu, "7450");
752    else if (Name == "ppc970")
753      DAL->AddJoinedArg(0, MCpu, "970");
754
755    else if (Name == "ppc64")
756      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
757
758    else if (Name == "i386")
759      ;
760    else if (Name == "i486")
761      DAL->AddJoinedArg(0, MArch, "i486");
762    else if (Name == "i586")
763      DAL->AddJoinedArg(0, MArch, "i586");
764    else if (Name == "i686")
765      DAL->AddJoinedArg(0, MArch, "i686");
766    else if (Name == "pentium")
767      DAL->AddJoinedArg(0, MArch, "pentium");
768    else if (Name == "pentium2")
769      DAL->AddJoinedArg(0, MArch, "pentium2");
770    else if (Name == "pentpro")
771      DAL->AddJoinedArg(0, MArch, "pentiumpro");
772    else if (Name == "pentIIm3")
773      DAL->AddJoinedArg(0, MArch, "pentium2");
774
775    else if (Name == "x86_64")
776      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
777
778    else if (Name == "arm")
779      DAL->AddJoinedArg(0, MArch, "armv4t");
780    else if (Name == "armv4t")
781      DAL->AddJoinedArg(0, MArch, "armv4t");
782    else if (Name == "armv5")
783      DAL->AddJoinedArg(0, MArch, "armv5tej");
784    else if (Name == "xscale")
785      DAL->AddJoinedArg(0, MArch, "xscale");
786    else if (Name == "armv6")
787      DAL->AddJoinedArg(0, MArch, "armv6k");
788    else if (Name == "armv6m")
789      DAL->AddJoinedArg(0, MArch, "armv6m");
790    else if (Name == "armv7")
791      DAL->AddJoinedArg(0, MArch, "armv7a");
792    else if (Name == "armv7em")
793      DAL->AddJoinedArg(0, MArch, "armv7em");
794    else if (Name == "armv7f")
795      DAL->AddJoinedArg(0, MArch, "armv7f");
796    else if (Name == "armv7k")
797      DAL->AddJoinedArg(0, MArch, "armv7k");
798    else if (Name == "armv7m")
799      DAL->AddJoinedArg(0, MArch, "armv7m");
800    else if (Name == "armv7s")
801      DAL->AddJoinedArg(0, MArch, "armv7s");
802
803    else
804      llvm_unreachable("invalid Darwin arch");
805  }
806
807  // Add an explicit version min argument for the deployment target. We do this
808  // after argument translation because -Xarch_ arguments may add a version min
809  // argument.
810  if (BoundArch)
811    AddDeploymentTarget(*DAL);
812
813  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
814  // FIXME: It would be far better to avoid inserting those -static arguments,
815  // but we can't check the deployment target in the translation code until
816  // it is set here.
817  if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
818    for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
819      Arg *A = *it;
820      ++it;
821      if (A->getOption().getID() != options::OPT_mkernel &&
822          A->getOption().getID() != options::OPT_fapple_kext)
823        continue;
824      assert(it != ie && "unexpected argument translation");
825      A = *it;
826      assert(A->getOption().getID() == options::OPT_static &&
827             "missing expected -static argument");
828      it = DAL->getArgs().erase(it);
829    }
830  }
831
832  // Validate the C++ standard library choice.
833  CXXStdlibType Type = GetCXXStdlibType(*DAL);
834  if (Type == ToolChain::CST_Libcxx) {
835    // Check whether the target provides libc++.
836    StringRef where;
837
838    // Complain about targetting iOS < 5.0 in any way.
839    if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
840      where = "iOS 5.0";
841
842    if (where != StringRef()) {
843      getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
844        << where;
845    }
846  }
847
848  return DAL;
849}
850
851bool Darwin::IsUnwindTablesDefault() const {
852  return getArch() == llvm::Triple::x86_64;
853}
854
855bool Darwin::UseDwarfDebugFlags() const {
856  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
857    return S[0] != '\0';
858  return false;
859}
860
861bool Darwin::UseSjLjExceptions() const {
862  // Darwin uses SjLj exceptions on ARM.
863  return (getTriple().getArch() == llvm::Triple::arm ||
864          getTriple().getArch() == llvm::Triple::thumb);
865}
866
867bool Darwin::isPICDefault() const {
868  return true;
869}
870
871bool Darwin::isPIEDefault() const {
872  return false;
873}
874
875bool Darwin::isPICDefaultForced() const {
876  return getArch() == llvm::Triple::x86_64;
877}
878
879bool Darwin::SupportsProfiling() const {
880  // Profiling instrumentation is only supported on x86.
881  return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
882}
883
884bool Darwin::SupportsObjCGC() const {
885  // Garbage collection is supported everywhere except on iPhone OS.
886  return !isTargetIPhoneOS();
887}
888
889void Darwin::CheckObjCARC() const {
890  if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
891    return;
892  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
893}
894
895std::string
896Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
897                                                types::ID InputType) const {
898  return ComputeLLVMTriple(Args, InputType);
899}
900
901/// Generic_GCC - A tool chain using the 'gcc' command to perform
902/// all subcommands; this relies on gcc translating the majority of
903/// command line options.
904
905/// \brief Parse a GCCVersion object out of a string of text.
906///
907/// This is the primary means of forming GCCVersion objects.
908/*static*/
909Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
910  const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
911  std::pair<StringRef, StringRef> First = VersionText.split('.');
912  std::pair<StringRef, StringRef> Second = First.second.split('.');
913
914  GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
915  if (First.first.getAsInteger(10, GoodVersion.Major) ||
916      GoodVersion.Major < 0)
917    return BadVersion;
918  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
919      GoodVersion.Minor < 0)
920    return BadVersion;
921
922  // First look for a number prefix and parse that if present. Otherwise just
923  // stash the entire patch string in the suffix, and leave the number
924  // unspecified. This covers versions strings such as:
925  //   4.4
926  //   4.4.0
927  //   4.4.x
928  //   4.4.2-rc4
929  //   4.4.x-patched
930  // And retains any patch number it finds.
931  StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
932  if (!PatchText.empty()) {
933    if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
934      // Try to parse the number and any suffix.
935      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
936          GoodVersion.Patch < 0)
937        return BadVersion;
938      GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
939    }
940  }
941
942  return GoodVersion;
943}
944
945/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
946bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
947  if (Major != RHS.Major)
948    return Major < RHS.Major;
949  if (Minor != RHS.Minor)
950    return Minor < RHS.Minor;
951  if (Patch != RHS.Patch) {
952    // Note that versions without a specified patch sort higher than those with
953    // a patch.
954    if (RHS.Patch == -1)
955      return true;
956    if (Patch == -1)
957      return false;
958
959    // Otherwise just sort on the patch itself.
960    return Patch < RHS.Patch;
961  }
962  if (PatchSuffix != RHS.PatchSuffix) {
963    // Sort empty suffixes higher.
964    if (RHS.PatchSuffix.empty())
965      return true;
966    if (PatchSuffix.empty())
967      return false;
968
969    // Provide a lexicographic sort to make this a total ordering.
970    return PatchSuffix < RHS.PatchSuffix;
971  }
972
973  // The versions are equal.
974  return false;
975}
976
977static StringRef getGCCToolchainDir(const ArgList &Args) {
978  const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
979  if (A)
980    return A->getValue();
981  return GCC_INSTALL_PREFIX;
982}
983
984/// \brief Construct a GCCInstallationDetector from the driver.
985///
986/// This performs all of the autodetection and sets up the various paths.
987/// Once constructed, a GCCInstallationDetector is essentially immutable.
988///
989/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
990/// should instead pull the target out of the driver. This is currently
991/// necessary because the driver doesn't store the final version of the target
992/// triple.
993Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
994    const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args)
995    : IsValid(false) {
996  llvm::Triple BiarchVariantTriple =
997      TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
998                                 : TargetTriple.get32BitArchVariant();
999  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1000  // The library directories which may contain GCC installations.
1001  SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1002  // The compatible GCC triples for this particular architecture.
1003  SmallVector<StringRef, 10> CandidateTripleAliases;
1004  SmallVector<StringRef, 10> CandidateBiarchTripleAliases;
1005  CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1006                           CandidateTripleAliases, CandidateBiarchLibDirs,
1007                           CandidateBiarchTripleAliases);
1008
1009  // Compute the set of prefixes for our search.
1010  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1011                                       D.PrefixDirs.end());
1012
1013  StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1014  if (GCCToolchainDir != "") {
1015    if (GCCToolchainDir.back() == '/')
1016      GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1017
1018    Prefixes.push_back(GCCToolchainDir);
1019  } else {
1020    Prefixes.push_back(D.SysRoot);
1021    Prefixes.push_back(D.SysRoot + "/usr");
1022    Prefixes.push_back(D.InstalledDir + "/..");
1023  }
1024
1025  // Loop over the various components which exist and select the best GCC
1026  // installation available. GCC installs are ranked by version number.
1027  Version = GCCVersion::Parse("0.0.0");
1028  for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1029    if (!llvm::sys::fs::exists(Prefixes[i]))
1030      continue;
1031    for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1032      const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1033      if (!llvm::sys::fs::exists(LibDir))
1034        continue;
1035      for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1036        ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1037                               CandidateTripleAliases[k]);
1038    }
1039    for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) {
1040      const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str();
1041      if (!llvm::sys::fs::exists(LibDir))
1042        continue;
1043      for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke;
1044           ++k)
1045        ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1046                               CandidateBiarchTripleAliases[k],
1047                               /*NeedsBiarchSuffix=*/ true);
1048    }
1049  }
1050}
1051
1052/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1053    const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1054    SmallVectorImpl<StringRef> &LibDirs,
1055    SmallVectorImpl<StringRef> &TripleAliases,
1056    SmallVectorImpl<StringRef> &BiarchLibDirs,
1057    SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1058  // Declare a bunch of static data sets that we'll select between below. These
1059  // are specifically designed to always refer to string literals to avoid any
1060  // lifetime or initialization issues.
1061  static const char *const AArch64LibDirs[] = { "/lib" };
1062  static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu",
1063                                                "aarch64-linux-gnu" };
1064
1065  static const char *const ARMLibDirs[] = { "/lib" };
1066  static const char *const ARMTriples[] = { "arm-linux-gnueabi",
1067                                            "arm-linux-androideabi" };
1068  static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf",
1069                                              "armv7hl-redhat-linux-gnueabi" };
1070
1071  static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1072  static const char *const X86_64Triples[] = {
1073    "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
1074    "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux",
1075    "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux"
1076  };
1077  static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1078  static const char *const X86Triples[] = {
1079    "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu",
1080    "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux",
1081    "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux",
1082    "i686-montavista-linux"
1083  };
1084
1085  static const char *const MIPSLibDirs[] = { "/lib" };
1086  static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1087  static const char *const MIPSELLibDirs[] = { "/lib" };
1088  static const char *const MIPSELTriples[] = { "mipsel-linux-gnu",
1089                                               "mipsel-linux-android",
1090                                               "mips-linux-gnu" };
1091
1092  static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1093  static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1094  static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1095  static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1096
1097  static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1098  static const char *const PPCTriples[] = {
1099    "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1100    "powerpc-suse-linux", "powerpc-montavista-linuxspe"
1101  };
1102  static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1103  static const char *const PPC64Triples[] = { "powerpc64-linux-gnu",
1104                                              "powerpc64-unknown-linux-gnu",
1105                                              "powerpc64-suse-linux",
1106                                              "ppc64-redhat-linux" };
1107
1108  static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
1109  static const char *const SystemZTriples[] = {
1110    "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1111    "s390x-suse-linux", "s390x-redhat-linux"
1112  };
1113
1114  switch (TargetTriple.getArch()) {
1115  case llvm::Triple::aarch64:
1116    LibDirs.append(AArch64LibDirs,
1117                   AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1118    TripleAliases.append(AArch64Triples,
1119                         AArch64Triples + llvm::array_lengthof(AArch64Triples));
1120    BiarchLibDirs.append(AArch64LibDirs,
1121                         AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1122    BiarchTripleAliases.append(
1123        AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1124    break;
1125  case llvm::Triple::arm:
1126  case llvm::Triple::thumb:
1127    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1128    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1129      TripleAliases.append(ARMHFTriples,
1130                           ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1131    } else {
1132      TripleAliases.append(ARMTriples,
1133                           ARMTriples + llvm::array_lengthof(ARMTriples));
1134    }
1135    break;
1136  case llvm::Triple::x86_64:
1137    LibDirs.append(X86_64LibDirs,
1138                   X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1139    TripleAliases.append(X86_64Triples,
1140                         X86_64Triples + llvm::array_lengthof(X86_64Triples));
1141    BiarchLibDirs.append(X86LibDirs,
1142                         X86LibDirs + llvm::array_lengthof(X86LibDirs));
1143    BiarchTripleAliases.append(X86Triples,
1144                               X86Triples + llvm::array_lengthof(X86Triples));
1145    break;
1146  case llvm::Triple::x86:
1147    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1148    TripleAliases.append(X86Triples,
1149                         X86Triples + llvm::array_lengthof(X86Triples));
1150    BiarchLibDirs.append(X86_64LibDirs,
1151                         X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1152    BiarchTripleAliases.append(
1153        X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1154    break;
1155  case llvm::Triple::mips:
1156    LibDirs.append(MIPSLibDirs,
1157                   MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1158    TripleAliases.append(MIPSTriples,
1159                         MIPSTriples + llvm::array_lengthof(MIPSTriples));
1160    BiarchLibDirs.append(MIPS64LibDirs,
1161                         MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1162    BiarchTripleAliases.append(
1163        MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1164    break;
1165  case llvm::Triple::mipsel:
1166    LibDirs.append(MIPSELLibDirs,
1167                   MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1168    TripleAliases.append(MIPSELTriples,
1169                         MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1170    BiarchLibDirs.append(
1171        MIPS64ELLibDirs,
1172        MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1173    BiarchTripleAliases.append(
1174        MIPS64ELTriples,
1175        MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1176    break;
1177  case llvm::Triple::mips64:
1178    LibDirs.append(MIPS64LibDirs,
1179                   MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1180    TripleAliases.append(MIPS64Triples,
1181                         MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1182    BiarchLibDirs.append(MIPSLibDirs,
1183                         MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1184    BiarchTripleAliases.append(MIPSTriples,
1185                               MIPSTriples + llvm::array_lengthof(MIPSTriples));
1186    break;
1187  case llvm::Triple::mips64el:
1188    LibDirs.append(MIPS64ELLibDirs,
1189                   MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1190    TripleAliases.append(
1191        MIPS64ELTriples,
1192        MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1193    BiarchLibDirs.append(MIPSELLibDirs,
1194                         MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1195    BiarchTripleAliases.append(
1196        MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1197    break;
1198  case llvm::Triple::ppc:
1199    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1200    TripleAliases.append(PPCTriples,
1201                         PPCTriples + llvm::array_lengthof(PPCTriples));
1202    BiarchLibDirs.append(PPC64LibDirs,
1203                         PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1204    BiarchTripleAliases.append(
1205        PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1206    break;
1207  case llvm::Triple::ppc64:
1208    LibDirs.append(PPC64LibDirs,
1209                   PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1210    TripleAliases.append(PPC64Triples,
1211                         PPC64Triples + llvm::array_lengthof(PPC64Triples));
1212    BiarchLibDirs.append(PPCLibDirs,
1213                         PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1214    BiarchTripleAliases.append(PPCTriples,
1215                               PPCTriples + llvm::array_lengthof(PPCTriples));
1216    break;
1217  case llvm::Triple::systemz:
1218    LibDirs.append(SystemZLibDirs,
1219                   SystemZLibDirs + llvm::array_lengthof(SystemZLibDirs));
1220    TripleAliases.append(SystemZTriples,
1221                         SystemZTriples + llvm::array_lengthof(SystemZTriples));
1222    break;
1223
1224  default:
1225    // By default, just rely on the standard lib directories and the original
1226    // triple.
1227    break;
1228  }
1229
1230  // Always append the drivers target triple to the end, in case it doesn't
1231  // match any of our aliases.
1232  TripleAliases.push_back(TargetTriple.str());
1233
1234  // Also include the multiarch variant if it's different.
1235  if (TargetTriple.str() != BiarchTriple.str())
1236    BiarchTripleAliases.push_back(BiarchTriple.str());
1237}
1238
1239static bool isSoftFloatABI(const ArgList &Args) {
1240  Arg *A = Args.getLastArg(options::OPT_msoft_float,
1241                           options::OPT_mhard_float,
1242                           options::OPT_mfloat_abi_EQ);
1243  if (!A) return false;
1244
1245  return A->getOption().matches(options::OPT_msoft_float) ||
1246         (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1247          A->getValue() == StringRef("soft"));
1248}
1249
1250static bool isMipsArch(llvm::Triple::ArchType Arch) {
1251  return Arch == llvm::Triple::mips ||
1252         Arch == llvm::Triple::mipsel ||
1253         Arch == llvm::Triple::mips64 ||
1254         Arch == llvm::Triple::mips64el;
1255}
1256
1257static bool isMips16(const ArgList &Args) {
1258  Arg *A = Args.getLastArg(options::OPT_mips16,
1259                           options::OPT_mno_mips16);
1260  return A && A->getOption().matches(options::OPT_mips16);
1261}
1262
1263static bool isMicroMips(const ArgList &Args) {
1264  Arg *A = Args.getLastArg(options::OPT_mmicromips,
1265                           options::OPT_mno_micromips);
1266  return A && A->getOption().matches(options::OPT_mmicromips);
1267}
1268
1269// FIXME: There is the same routine in the Tools.cpp.
1270static bool hasMipsN32ABIArg(const ArgList &Args) {
1271  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1272  return A && (A->getValue() == StringRef("n32"));
1273}
1274
1275static void appendMipsTargetSuffix(std::string &Path,
1276                                   llvm::Triple::ArchType TargetArch,
1277                                   const ArgList &Args) {
1278  if (isMips16(Args))
1279    Path += "/mips16";
1280  else if (isMicroMips(Args))
1281    Path += "/micromips";
1282
1283  if (isSoftFloatABI(Args))
1284    Path += "/soft-float";
1285
1286  if (TargetArch == llvm::Triple::mipsel ||
1287      TargetArch == llvm::Triple::mips64el)
1288    Path += "/el";
1289}
1290
1291static StringRef getMipsTargetABISuffix(llvm::Triple::ArchType TargetArch,
1292                                        const ArgList &Args) {
1293  if (TargetArch == llvm::Triple::mips64 ||
1294      TargetArch == llvm::Triple::mips64el)
1295    return hasMipsN32ABIArg(Args) ? "/n32" : "/64";
1296
1297  return "/32";
1298}
1299
1300static bool findTargetBiarchSuffix(std::string &Suffix, StringRef Path,
1301                                   llvm::Triple::ArchType TargetArch,
1302                                   const ArgList &Args) {
1303  // FIXME: This routine was only intended to model bi-arch toolchains which
1304  // use -m32 and -m64 to swap between variants of a target. It shouldn't be
1305  // doing ABI-based builtin location for MIPS.
1306  if (isMipsArch(TargetArch)) {
1307    StringRef ABISuffix = getMipsTargetABISuffix(TargetArch, Args);
1308
1309    // First build and check a complex path to crtbegin.o
1310    // depends on command line options (-mips16, -msoft-float, ...)
1311    // like mips-linux-gnu/4.7/mips16/soft-float/el/crtbegin.o
1312    appendMipsTargetSuffix(Suffix, TargetArch, Args);
1313
1314    if (TargetArch == llvm::Triple::mips64 ||
1315        TargetArch == llvm::Triple::mips64el)
1316      Suffix += ABISuffix;
1317
1318    if (llvm::sys::fs::exists(Path + Suffix + "/crtbegin.o"))
1319      return true;
1320
1321    // Then fall back and probe a simple case like
1322    // mips-linux-gnu/4.7/32/crtbegin.o
1323    Suffix = ABISuffix;
1324    return llvm::sys::fs::exists(Path + Suffix + "/crtbegin.o");
1325  }
1326
1327  if (TargetArch == llvm::Triple::x86_64 ||
1328      TargetArch == llvm::Triple::ppc64 ||
1329      TargetArch == llvm::Triple::systemz)
1330    Suffix = "/64";
1331  else
1332    Suffix = "/32";
1333
1334  return llvm::sys::fs::exists(Path + Suffix + "/crtbegin.o");
1335}
1336
1337void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1338    llvm::Triple::ArchType TargetArch, const ArgList &Args,
1339    const std::string &LibDir, StringRef CandidateTriple,
1340    bool NeedsBiarchSuffix) {
1341  // There are various different suffixes involving the triple we
1342  // check for. We also record what is necessary to walk from each back
1343  // up to the lib directory.
1344  const std::string LibSuffixes[] = {
1345    "/gcc/" + CandidateTriple.str(),
1346    // Debian puts cross-compilers in gcc-cross
1347    "/gcc-cross/" + CandidateTriple.str(),
1348    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1349
1350    // The Freescale PPC SDK has the gcc libraries in
1351    // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1352    "/" + CandidateTriple.str(),
1353
1354    // Ubuntu has a strange mis-matched pair of triples that this happens to
1355    // match.
1356    // FIXME: It may be worthwhile to generalize this and look for a second
1357    // triple.
1358    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1359  };
1360  const std::string InstallSuffixes[] = {
1361    "/../../..",    // gcc/
1362    "/../../..",    // gcc-cross/
1363    "/../../../..", // <triple>/gcc/
1364    "/../..",       // <triple>/
1365    "/../../../.."  // i386-linux-gnu/gcc/<triple>/
1366  };
1367  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1368  const unsigned NumLibSuffixes =
1369      (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86));
1370  for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1371    StringRef LibSuffix = LibSuffixes[i];
1372    llvm::error_code EC;
1373    for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1374         !EC && LI != LE; LI = LI.increment(EC)) {
1375      StringRef VersionText = llvm::sys::path::filename(LI->path());
1376      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1377      static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1378      if (CandidateVersion < MinVersion)
1379        continue;
1380      if (CandidateVersion <= Version)
1381        continue;
1382
1383      // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1384      // in what would normally be GCCInstallPath and put the 64-bit
1385      // libs in a subdirectory named 64. The simple logic we follow is that
1386      // *if* there is a subdirectory of the right name with crtbegin.o in it,
1387      // we use that. If not, and if not a biarch triple alias, we look for
1388      // crtbegin.o without the subdirectory.
1389
1390      std::string BiarchSuffix;
1391      if (findTargetBiarchSuffix(BiarchSuffix, LI->path(), TargetArch, Args)) {
1392        GCCBiarchSuffix = BiarchSuffix;
1393      } else {
1394        if (NeedsBiarchSuffix ||
1395            !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1396          continue;
1397        GCCBiarchSuffix.clear();
1398      }
1399
1400      Version = CandidateVersion;
1401      GCCTriple.setTriple(CandidateTriple);
1402      // FIXME: We hack together the directory name here instead of
1403      // using LI to ensure stable path separators across Windows and
1404      // Linux.
1405      GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1406      GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1407      IsValid = true;
1408    }
1409  }
1410}
1411
1412Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1413                         const ArgList &Args)
1414  : ToolChain(D, Triple, Args), GCCInstallation(getDriver(), Triple, Args) {
1415  getProgramPaths().push_back(getDriver().getInstalledDir());
1416  if (getDriver().getInstalledDir() != getDriver().Dir)
1417    getProgramPaths().push_back(getDriver().Dir);
1418}
1419
1420Generic_GCC::~Generic_GCC() {
1421}
1422
1423Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
1424  switch (AC) {
1425  case Action::PreprocessJobClass:
1426    if (!Preprocess)
1427      Preprocess.reset(new tools::gcc::Preprocess(*this));
1428    return Preprocess.get();
1429  case Action::PrecompileJobClass:
1430    if (!Precompile)
1431      Precompile.reset(new tools::gcc::Precompile(*this));
1432    return Precompile.get();
1433  case Action::CompileJobClass:
1434    if (!Compile)
1435      Compile.reset(new tools::gcc::Compile(*this));
1436    return Compile.get();
1437  default:
1438    return ToolChain::getTool(AC);
1439  }
1440}
1441
1442Tool *Generic_GCC::buildAssembler() const {
1443  return new tools::gcc::Assemble(*this);
1444}
1445
1446Tool *Generic_GCC::buildLinker() const {
1447  return new tools::gcc::Link(*this);
1448}
1449
1450bool Generic_GCC::IsUnwindTablesDefault() const {
1451  return getArch() == llvm::Triple::x86_64;
1452}
1453
1454bool Generic_GCC::isPICDefault() const {
1455  return false;
1456}
1457
1458bool Generic_GCC::isPIEDefault() const {
1459  return false;
1460}
1461
1462bool Generic_GCC::isPICDefaultForced() const {
1463  return false;
1464}
1465
1466/// Hexagon Toolchain
1467
1468std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir) {
1469
1470  // Locate the rest of the toolchain ...
1471  if (strlen(GCC_INSTALL_PREFIX))
1472    return std::string(GCC_INSTALL_PREFIX);
1473
1474  std::string InstallRelDir = InstalledDir + "/../../gnu";
1475  if (llvm::sys::fs::exists(InstallRelDir))
1476    return InstallRelDir;
1477
1478  std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
1479  if (llvm::sys::fs::exists(PrefixRelDir))
1480    return PrefixRelDir;
1481
1482  return InstallRelDir;
1483}
1484
1485static void GetHexagonLibraryPaths(
1486  const ArgList &Args,
1487  const std::string Ver,
1488  const std::string MarchString,
1489  const std::string &InstalledDir,
1490  ToolChain::path_list *LibPaths)
1491{
1492  bool buildingLib = Args.hasArg(options::OPT_shared);
1493
1494  //----------------------------------------------------------------------------
1495  // -L Args
1496  //----------------------------------------------------------------------------
1497  for (arg_iterator
1498         it = Args.filtered_begin(options::OPT_L),
1499         ie = Args.filtered_end();
1500       it != ie;
1501       ++it) {
1502    for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
1503      LibPaths->push_back((*it)->getValue(i));
1504  }
1505
1506  //----------------------------------------------------------------------------
1507  // Other standard paths
1508  //----------------------------------------------------------------------------
1509  const std::string MarchSuffix = "/" + MarchString;
1510  const std::string G0Suffix = "/G0";
1511  const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
1512  const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir) + "/";
1513
1514  // lib/gcc/hexagon/...
1515  std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
1516  if (buildingLib) {
1517    LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
1518    LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
1519  }
1520  LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
1521  LibPaths->push_back(LibGCCHexagonDir + Ver);
1522
1523  // lib/gcc/...
1524  LibPaths->push_back(RootDir + "lib/gcc");
1525
1526  // hexagon/lib/...
1527  std::string HexagonLibDir = RootDir + "hexagon/lib";
1528  if (buildingLib) {
1529    LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
1530    LibPaths->push_back(HexagonLibDir + G0Suffix);
1531  }
1532  LibPaths->push_back(HexagonLibDir + MarchSuffix);
1533  LibPaths->push_back(HexagonLibDir);
1534}
1535
1536Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
1537                       const ArgList &Args)
1538  : Linux(D, Triple, Args) {
1539  const std::string InstalledDir(getDriver().getInstalledDir());
1540  const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir);
1541
1542  // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
1543  // program paths
1544  const std::string BinDir(GnuDir + "/bin");
1545  if (llvm::sys::fs::exists(BinDir))
1546    getProgramPaths().push_back(BinDir);
1547
1548  // Determine version of GCC libraries and headers to use.
1549  const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
1550  llvm::error_code ec;
1551  GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
1552  for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
1553       !ec && di != de; di = di.increment(ec)) {
1554    GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
1555    if (MaxVersion < cv)
1556      MaxVersion = cv;
1557  }
1558  GCCLibAndIncVersion = MaxVersion;
1559
1560  ToolChain::path_list *LibPaths= &getFilePaths();
1561
1562  // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
1563  // 'elf' OS type, so the Linux paths are not appropriate. When we actually
1564  // support 'linux' we'll need to fix this up
1565  LibPaths->clear();
1566
1567  GetHexagonLibraryPaths(
1568    Args,
1569    GetGCCLibAndIncVersion(),
1570    GetTargetCPU(Args),
1571    InstalledDir,
1572    LibPaths);
1573}
1574
1575Hexagon_TC::~Hexagon_TC() {
1576}
1577
1578Tool *Hexagon_TC::buildAssembler() const {
1579  return new tools::hexagon::Assemble(*this);
1580}
1581
1582Tool *Hexagon_TC::buildLinker() const {
1583  return new tools::hexagon::Link(*this);
1584}
1585
1586void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1587                                           ArgStringList &CC1Args) const {
1588  const Driver &D = getDriver();
1589
1590  if (DriverArgs.hasArg(options::OPT_nostdinc) ||
1591      DriverArgs.hasArg(options::OPT_nostdlibinc))
1592    return;
1593
1594  std::string Ver(GetGCCLibAndIncVersion());
1595  std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir);
1596  std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
1597  addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
1598  addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
1599  addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
1600}
1601
1602void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1603                                              ArgStringList &CC1Args) const {
1604
1605  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1606      DriverArgs.hasArg(options::OPT_nostdincxx))
1607    return;
1608
1609  const Driver &D = getDriver();
1610  std::string Ver(GetGCCLibAndIncVersion());
1611  SmallString<128> IncludeDir(Hexagon_TC::GetGnuDir(D.InstalledDir));
1612
1613  llvm::sys::path::append(IncludeDir, "hexagon/include/c++/");
1614  llvm::sys::path::append(IncludeDir, Ver);
1615  addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
1616}
1617
1618ToolChain::CXXStdlibType
1619Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
1620  Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1621  if (!A)
1622    return ToolChain::CST_Libstdcxx;
1623
1624  StringRef Value = A->getValue();
1625  if (Value != "libstdc++") {
1626    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1627      << A->getAsString(Args);
1628  }
1629
1630  return ToolChain::CST_Libstdcxx;
1631}
1632
1633static Arg *GetLastHexagonArchArg(const ArgList &Args)
1634{
1635  Arg *A = NULL;
1636
1637  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
1638       it != ie; ++it) {
1639    if ((*it)->getOption().matches(options::OPT_march_EQ) ||
1640        (*it)->getOption().matches(options::OPT_mcpu_EQ)) {
1641      A = *it;
1642      A->claim();
1643    } else if ((*it)->getOption().matches(options::OPT_m_Joined)) {
1644      StringRef Value = (*it)->getValue(0);
1645      if (Value.startswith("v")) {
1646        A = *it;
1647        A->claim();
1648      }
1649    }
1650  }
1651  return A;
1652}
1653
1654StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
1655{
1656  // Select the default CPU (v4) if none was given or detection failed.
1657  Arg *A = GetLastHexagonArchArg (Args);
1658  if (A) {
1659    StringRef WhichHexagon = A->getValue();
1660    if (WhichHexagon.startswith("hexagon"))
1661      return WhichHexagon.substr(sizeof("hexagon") - 1);
1662    if (WhichHexagon != "")
1663      return WhichHexagon;
1664  }
1665
1666  return "v4";
1667}
1668// End Hexagon
1669
1670/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1671/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1672/// Currently does not support anything else but compilation.
1673
1674TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple,
1675                           const ArgList &Args)
1676  : ToolChain(D, Triple, Args) {
1677  // Path mangling to find libexec
1678  std::string Path(getDriver().Dir);
1679
1680  Path += "/../libexec";
1681  getProgramPaths().push_back(Path);
1682}
1683
1684TCEToolChain::~TCEToolChain() {
1685}
1686
1687bool TCEToolChain::IsMathErrnoDefault() const {
1688  return true;
1689}
1690
1691bool TCEToolChain::isPICDefault() const {
1692  return false;
1693}
1694
1695bool TCEToolChain::isPIEDefault() const {
1696  return false;
1697}
1698
1699bool TCEToolChain::isPICDefaultForced() const {
1700  return false;
1701}
1702
1703/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1704
1705OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1706  : Generic_ELF(D, Triple, Args) {
1707  getFilePaths().push_back(getDriver().Dir + "/../lib");
1708  getFilePaths().push_back("/usr/lib");
1709}
1710
1711Tool *OpenBSD::buildAssembler() const {
1712  return new tools::openbsd::Assemble(*this);
1713}
1714
1715Tool *OpenBSD::buildLinker() const {
1716  return new tools::openbsd::Link(*this);
1717}
1718
1719/// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1720
1721Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1722  : Generic_ELF(D, Triple, Args) {
1723  getFilePaths().push_back(getDriver().Dir + "/../lib");
1724  getFilePaths().push_back("/usr/lib");
1725}
1726
1727Tool *Bitrig::buildAssembler() const {
1728  return new tools::bitrig::Assemble(*this);
1729}
1730
1731Tool *Bitrig::buildLinker() const {
1732  return new tools::bitrig::Link(*this);
1733}
1734
1735void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1736                                          ArgStringList &CC1Args) const {
1737  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1738      DriverArgs.hasArg(options::OPT_nostdincxx))
1739    return;
1740
1741  switch (GetCXXStdlibType(DriverArgs)) {
1742  case ToolChain::CST_Libcxx:
1743    addSystemInclude(DriverArgs, CC1Args,
1744                     getDriver().SysRoot + "/usr/include/c++/");
1745    break;
1746  case ToolChain::CST_Libstdcxx:
1747    addSystemInclude(DriverArgs, CC1Args,
1748                     getDriver().SysRoot + "/usr/include/c++/stdc++");
1749    addSystemInclude(DriverArgs, CC1Args,
1750                     getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1751
1752    StringRef Triple = getTriple().str();
1753    if (Triple.startswith("amd64"))
1754      addSystemInclude(DriverArgs, CC1Args,
1755                       getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1756                       Triple.substr(5));
1757    else
1758      addSystemInclude(DriverArgs, CC1Args,
1759                       getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1760                       Triple);
1761    break;
1762  }
1763}
1764
1765void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1766                                 ArgStringList &CmdArgs) const {
1767  switch (GetCXXStdlibType(Args)) {
1768  case ToolChain::CST_Libcxx:
1769    CmdArgs.push_back("-lc++");
1770    CmdArgs.push_back("-lcxxrt");
1771    // Include supc++ to provide Unwind until provided by libcxx.
1772    CmdArgs.push_back("-lgcc");
1773    break;
1774  case ToolChain::CST_Libstdcxx:
1775    CmdArgs.push_back("-lstdc++");
1776    break;
1777  }
1778}
1779
1780/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1781
1782FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1783  : Generic_ELF(D, Triple, Args) {
1784
1785  // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1786  // back to '/usr/lib' if it doesn't exist.
1787  if ((Triple.getArch() == llvm::Triple::x86 ||
1788       Triple.getArch() == llvm::Triple::ppc) &&
1789      llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1790    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1791  else
1792    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1793}
1794
1795Tool *FreeBSD::buildAssembler() const {
1796  return new tools::freebsd::Assemble(*this);
1797}
1798
1799Tool *FreeBSD::buildLinker() const {
1800  return new tools::freebsd::Link(*this);
1801}
1802
1803bool FreeBSD::UseSjLjExceptions() const {
1804  // FreeBSD uses SjLj exceptions on ARM oabi.
1805  switch (getTriple().getEnvironment()) {
1806  case llvm::Triple::GNUEABI:
1807  case llvm::Triple::EABI:
1808    return false;
1809
1810  default:
1811    return (getTriple().getArch() == llvm::Triple::arm ||
1812            getTriple().getArch() == llvm::Triple::thumb);
1813  }
1814}
1815
1816/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1817
1818NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1819  : Generic_ELF(D, Triple, Args) {
1820
1821  if (getDriver().UseStdLib) {
1822    // When targeting a 32-bit platform, try the special directory used on
1823    // 64-bit hosts, and only fall back to the main library directory if that
1824    // doesn't work.
1825    // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1826    // what all logic is needed to emulate the '=' prefix here.
1827    if (Triple.getArch() == llvm::Triple::x86)
1828      getFilePaths().push_back("=/usr/lib/i386");
1829
1830    getFilePaths().push_back("=/usr/lib");
1831  }
1832}
1833
1834Tool *NetBSD::buildAssembler() const {
1835  return new tools::netbsd::Assemble(*this);
1836}
1837
1838Tool *NetBSD::buildLinker() const {
1839  return new tools::netbsd::Link(*this);
1840}
1841
1842ToolChain::CXXStdlibType
1843NetBSD::GetCXXStdlibType(const ArgList &Args) const {
1844  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
1845    StringRef Value = A->getValue();
1846    if (Value == "libstdc++")
1847      return ToolChain::CST_Libstdcxx;
1848    if (Value == "libc++")
1849      return ToolChain::CST_Libcxx;
1850
1851    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1852      << A->getAsString(Args);
1853  }
1854
1855  return ToolChain::CST_Libstdcxx;
1856}
1857
1858void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1859                                          ArgStringList &CC1Args) const {
1860  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1861      DriverArgs.hasArg(options::OPT_nostdincxx))
1862    return;
1863
1864  switch (GetCXXStdlibType(DriverArgs)) {
1865  case ToolChain::CST_Libcxx:
1866    addSystemInclude(DriverArgs, CC1Args,
1867                     getDriver().SysRoot + "/usr/include/c++/");
1868    break;
1869  case ToolChain::CST_Libstdcxx:
1870    addSystemInclude(DriverArgs, CC1Args,
1871                     getDriver().SysRoot + "/usr/include/g++");
1872    addSystemInclude(DriverArgs, CC1Args,
1873                     getDriver().SysRoot + "/usr/include/g++/backward");
1874    break;
1875  }
1876}
1877
1878/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1879
1880Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1881  : Generic_ELF(D, Triple, Args) {
1882  getFilePaths().push_back(getDriver().Dir + "/../lib");
1883  getFilePaths().push_back("/usr/lib");
1884}
1885
1886Tool *Minix::buildAssembler() const {
1887  return new tools::minix::Assemble(*this);
1888}
1889
1890Tool *Minix::buildLinker() const {
1891  return new tools::minix::Link(*this);
1892}
1893
1894/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1895
1896AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1897                   const ArgList &Args)
1898  : Generic_GCC(D, Triple, Args) {
1899
1900  getProgramPaths().push_back(getDriver().getInstalledDir());
1901  if (getDriver().getInstalledDir() != getDriver().Dir)
1902    getProgramPaths().push_back(getDriver().Dir);
1903
1904  getFilePaths().push_back(getDriver().Dir + "/../lib");
1905  getFilePaths().push_back("/usr/lib");
1906  getFilePaths().push_back("/usr/sfw/lib");
1907  getFilePaths().push_back("/opt/gcc4/lib");
1908  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1909
1910}
1911
1912Tool *AuroraUX::buildAssembler() const {
1913  return new tools::auroraux::Assemble(*this);
1914}
1915
1916Tool *AuroraUX::buildLinker() const {
1917  return new tools::auroraux::Link(*this);
1918}
1919
1920/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
1921
1922Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
1923                 const ArgList &Args)
1924  : Generic_GCC(D, Triple, Args) {
1925
1926  getProgramPaths().push_back(getDriver().getInstalledDir());
1927  if (getDriver().getInstalledDir() != getDriver().Dir)
1928    getProgramPaths().push_back(getDriver().Dir);
1929
1930  getFilePaths().push_back(getDriver().Dir + "/../lib");
1931  getFilePaths().push_back("/usr/lib");
1932}
1933
1934Tool *Solaris::buildAssembler() const {
1935  return new tools::solaris::Assemble(*this);
1936}
1937
1938Tool *Solaris::buildLinker() const {
1939  return new tools::solaris::Link(*this);
1940}
1941
1942/// Distribution (very bare-bones at the moment).
1943
1944enum Distro {
1945  ArchLinux,
1946  DebianLenny,
1947  DebianSqueeze,
1948  DebianWheezy,
1949  DebianJessie,
1950  Exherbo,
1951  RHEL4,
1952  RHEL5,
1953  RHEL6,
1954  Fedora13,
1955  Fedora14,
1956  Fedora15,
1957  Fedora16,
1958  FedoraRawhide,
1959  OpenSUSE,
1960  UbuntuHardy,
1961  UbuntuIntrepid,
1962  UbuntuJaunty,
1963  UbuntuKarmic,
1964  UbuntuLucid,
1965  UbuntuMaverick,
1966  UbuntuNatty,
1967  UbuntuOneiric,
1968  UbuntuPrecise,
1969  UbuntuQuantal,
1970  UbuntuRaring,
1971  UbuntuSaucy,
1972  UnknownDistro
1973};
1974
1975static bool IsRedhat(enum Distro Distro) {
1976  return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
1977         (Distro >= RHEL4    && Distro <= RHEL6);
1978}
1979
1980static bool IsOpenSUSE(enum Distro Distro) {
1981  return Distro == OpenSUSE;
1982}
1983
1984static bool IsDebian(enum Distro Distro) {
1985  return Distro >= DebianLenny && Distro <= DebianJessie;
1986}
1987
1988static bool IsUbuntu(enum Distro Distro) {
1989  return Distro >= UbuntuHardy && Distro <= UbuntuSaucy;
1990}
1991
1992static Distro DetectDistro(llvm::Triple::ArchType Arch) {
1993  OwningPtr<llvm::MemoryBuffer> File;
1994  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1995    StringRef Data = File.get()->getBuffer();
1996    SmallVector<StringRef, 8> Lines;
1997    Data.split(Lines, "\n");
1998    Distro Version = UnknownDistro;
1999    for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2000      if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2001        Version = llvm::StringSwitch<Distro>(Lines[i].substr(17))
2002          .Case("hardy", UbuntuHardy)
2003          .Case("intrepid", UbuntuIntrepid)
2004          .Case("jaunty", UbuntuJaunty)
2005          .Case("karmic", UbuntuKarmic)
2006          .Case("lucid", UbuntuLucid)
2007          .Case("maverick", UbuntuMaverick)
2008          .Case("natty", UbuntuNatty)
2009          .Case("oneiric", UbuntuOneiric)
2010          .Case("precise", UbuntuPrecise)
2011          .Case("quantal", UbuntuQuantal)
2012          .Case("raring", UbuntuRaring)
2013          .Case("saucy", UbuntuSaucy)
2014          .Default(UnknownDistro);
2015    return Version;
2016  }
2017
2018  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
2019    StringRef Data = File.get()->getBuffer();
2020    if (Data.startswith("Fedora release 16"))
2021      return Fedora16;
2022    else if (Data.startswith("Fedora release 15"))
2023      return Fedora15;
2024    else if (Data.startswith("Fedora release 14"))
2025      return Fedora14;
2026    else if (Data.startswith("Fedora release 13"))
2027      return Fedora13;
2028    else if (Data.startswith("Fedora release") &&
2029             Data.find("Rawhide") != StringRef::npos)
2030      return FedoraRawhide;
2031    else if (Data.startswith("Red Hat Enterprise Linux") &&
2032             Data.find("release 6") != StringRef::npos)
2033      return RHEL6;
2034    else if ((Data.startswith("Red Hat Enterprise Linux") ||
2035              Data.startswith("CentOS")) &&
2036             Data.find("release 5") != StringRef::npos)
2037      return RHEL5;
2038    else if ((Data.startswith("Red Hat Enterprise Linux") ||
2039              Data.startswith("CentOS")) &&
2040             Data.find("release 4") != StringRef::npos)
2041      return RHEL4;
2042    return UnknownDistro;
2043  }
2044
2045  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
2046    StringRef Data = File.get()->getBuffer();
2047    if (Data[0] == '5')
2048      return DebianLenny;
2049    else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2050      return DebianSqueeze;
2051    else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
2052      return DebianWheezy;
2053    else if (Data.startswith("jessie/sid")  || Data[0] == '8')
2054      return DebianJessie;
2055    return UnknownDistro;
2056  }
2057
2058  if (llvm::sys::fs::exists("/etc/SuSE-release"))
2059    return OpenSUSE;
2060
2061  if (llvm::sys::fs::exists("/etc/exherbo-release"))
2062    return Exherbo;
2063
2064  if (llvm::sys::fs::exists("/etc/arch-release"))
2065    return ArchLinux;
2066
2067  return UnknownDistro;
2068}
2069
2070/// \brief Get our best guess at the multiarch triple for a target.
2071///
2072/// Debian-based systems are starting to use a multiarch setup where they use
2073/// a target-triple directory in the library and header search paths.
2074/// Unfortunately, this triple does not align with the vanilla target triple,
2075/// so we provide a rough mapping here.
2076static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2077                                      StringRef SysRoot) {
2078  // For most architectures, just use whatever we have rather than trying to be
2079  // clever.
2080  switch (TargetTriple.getArch()) {
2081  default:
2082    return TargetTriple.str();
2083
2084    // We use the existence of '/lib/<triple>' as a directory to detect some
2085    // common linux triples that don't quite match the Clang triple for both
2086    // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2087    // regardless of what the actual target triple is.
2088  case llvm::Triple::arm:
2089  case llvm::Triple::thumb:
2090    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2091      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2092        return "arm-linux-gnueabihf";
2093    } else {
2094      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2095        return "arm-linux-gnueabi";
2096    }
2097    return TargetTriple.str();
2098  case llvm::Triple::x86:
2099    if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2100      return "i386-linux-gnu";
2101    return TargetTriple.str();
2102  case llvm::Triple::x86_64:
2103    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2104      return "x86_64-linux-gnu";
2105    return TargetTriple.str();
2106  case llvm::Triple::aarch64:
2107    if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2108      return "aarch64-linux-gnu";
2109    return TargetTriple.str();
2110  case llvm::Triple::mips:
2111    if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2112      return "mips-linux-gnu";
2113    return TargetTriple.str();
2114  case llvm::Triple::mipsel:
2115    if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2116      return "mipsel-linux-gnu";
2117    return TargetTriple.str();
2118  case llvm::Triple::ppc:
2119    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2120      return "powerpc-linux-gnuspe";
2121    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2122      return "powerpc-linux-gnu";
2123    return TargetTriple.str();
2124  case llvm::Triple::ppc64:
2125    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2126      return "powerpc64-linux-gnu";
2127    return TargetTriple.str();
2128  }
2129}
2130
2131static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2132  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2133}
2134
2135static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
2136                         const ArgList &Args) {
2137  if (Arch != llvm::Triple::mips &&
2138      Arch != llvm::Triple::mipsel)
2139    return false;
2140
2141  Arg *A = Args.getLastArg(options::OPT_march_EQ,
2142                           options::OPT_mcpu_EQ,
2143                           options::OPT_mips_CPUs_Group);
2144
2145  if (!A)
2146    return false;
2147
2148  if (A->getOption().matches(options::OPT_mips_CPUs_Group))
2149    return A->getOption().matches(options::OPT_mips32r2);
2150
2151  return A->getValue() == StringRef("mips32r2");
2152}
2153
2154static StringRef getMultilibDir(const llvm::Triple &Triple,
2155                                const ArgList &Args) {
2156  if (!isMipsArch(Triple.getArch()))
2157    return Triple.isArch32Bit() ? "lib32" : "lib64";
2158
2159  // lib32 directory has a special meaning on MIPS targets.
2160  // It contains N32 ABI binaries. Use this folder if produce
2161  // code for N32 ABI only.
2162  if (hasMipsN32ABIArg(Args))
2163    return "lib32";
2164
2165  return Triple.isArch32Bit() ? "lib" : "lib64";
2166}
2167
2168Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2169  : Generic_ELF(D, Triple, Args) {
2170  llvm::Triple::ArchType Arch = Triple.getArch();
2171  std::string SysRoot = computeSysRoot(Args);
2172
2173  // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
2174  // least) put various tools in a triple-prefixed directory off of the parent
2175  // of the GCC installation. We use the GCC triple here to ensure that we end
2176  // up with tools that support the same amount of cross compiling as the
2177  // detected GCC installation. For example, if we find a GCC installation
2178  // targeting x86_64, but it is a bi-arch GCC installation, it can also be
2179  // used to target i386.
2180  // FIXME: This seems unlikely to be Linux-specific.
2181  ToolChain::path_list &PPaths = getProgramPaths();
2182  PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2183                         GCCInstallation.getTriple().str() + "/bin").str());
2184
2185  Linker = GetProgramPath("ld");
2186
2187  Distro Distro = DetectDistro(Arch);
2188
2189  if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
2190    ExtraOpts.push_back("-z");
2191    ExtraOpts.push_back("relro");
2192  }
2193
2194  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2195    ExtraOpts.push_back("-X");
2196
2197  const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2198  const bool IsMips = isMipsArch(Arch);
2199
2200  if (IsMips && !SysRoot.empty())
2201    ExtraOpts.push_back("--sysroot=" + SysRoot);
2202
2203  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2204  // and the MIPS ABI require .dynsym to be sorted in different ways.
2205  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2206  // ABI requires a mapping between the GOT and the symbol table.
2207  // Android loader does not support .gnu.hash.
2208  if (!IsMips && !IsAndroid) {
2209    if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
2210        (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2211      ExtraOpts.push_back("--hash-style=gnu");
2212
2213    if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
2214        Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2215      ExtraOpts.push_back("--hash-style=both");
2216  }
2217
2218  if (IsRedhat(Distro))
2219    ExtraOpts.push_back("--no-add-needed");
2220
2221  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2222      Distro == DebianJessie || IsOpenSUSE(Distro) ||
2223      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2224      (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2225    ExtraOpts.push_back("--build-id");
2226
2227  if (IsOpenSUSE(Distro))
2228    ExtraOpts.push_back("--enable-new-dtags");
2229
2230  // The selection of paths to try here is designed to match the patterns which
2231  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2232  // This was determined by running GCC in a fake filesystem, creating all
2233  // possible permutations of these directories, and seeing which ones it added
2234  // to the link paths.
2235  path_list &Paths = getFilePaths();
2236
2237  const std::string Multilib = getMultilibDir(Triple, Args);
2238  const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2239
2240  // Add the multilib suffixed paths where they are available.
2241  if (GCCInstallation.isValid()) {
2242    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2243    const std::string &LibPath = GCCInstallation.getParentLibPath();
2244
2245    if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args))
2246      addPathIfExists(GCCInstallation.getInstallPath() +
2247                          GCCInstallation.getBiarchSuffix() + "/mips-r2",
2248                      Paths);
2249    else
2250      addPathIfExists((GCCInstallation.getInstallPath() +
2251                       GCCInstallation.getBiarchSuffix()),
2252                      Paths);
2253
2254    // If the GCC installation we found is inside of the sysroot, we want to
2255    // prefer libraries installed in the parent prefix of the GCC installation.
2256    // It is important to *not* use these paths when the GCC installation is
2257    // outside of the system root as that can pick up unintended libraries.
2258    // This usually happens when there is an external cross compiler on the
2259    // host system, and a more minimal sysroot available that is the target of
2260    // the cross.
2261    if (StringRef(LibPath).startswith(SysRoot)) {
2262      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2263                      Paths);
2264      addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2265      addPathIfExists(LibPath + "/../" + Multilib, Paths);
2266    }
2267    // On Android, libraries in the parent prefix of the GCC installation are
2268    // preferred to the ones under sysroot.
2269    if (IsAndroid) {
2270      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2271    }
2272    // Sourcery CodeBench MIPS toolchain holds some libraries under
2273    // the parent prefix of the GCC installation.
2274    if (IsMips) {
2275      std::string Suffix;
2276      appendMipsTargetSuffix(Suffix, Arch, Args);
2277      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" +
2278                      Multilib + Suffix,
2279                      Paths);
2280    }
2281  }
2282  addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2283  addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2284  addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2285  addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2286
2287  // Try walking via the GCC triple path in case of biarch or multiarch GCC
2288  // installations with strange symlinks.
2289  if (GCCInstallation.isValid())
2290    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2291                    "/../../" + Multilib, Paths);
2292
2293  // Add the non-multilib suffixed paths (if potentially different).
2294  if (GCCInstallation.isValid()) {
2295    const std::string &LibPath = GCCInstallation.getParentLibPath();
2296    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2297    if (!GCCInstallation.getBiarchSuffix().empty())
2298      addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2299
2300    if (StringRef(LibPath).startswith(SysRoot)) {
2301      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2302      addPathIfExists(LibPath, Paths);
2303    }
2304  }
2305  addPathIfExists(SysRoot + "/lib", Paths);
2306  addPathIfExists(SysRoot + "/usr/lib", Paths);
2307
2308  IsPIEDefault = SanitizerArgs(*this, Args).hasZeroBaseShadow();
2309}
2310
2311bool Linux::HasNativeLLVMSupport() const {
2312  return true;
2313}
2314
2315Tool *Linux::buildLinker() const {
2316  return new tools::gnutools::Link(*this);
2317}
2318
2319Tool *Linux::buildAssembler() const {
2320  return new tools::gnutools::Assemble(*this);
2321}
2322
2323void Linux::addClangTargetOptions(const ArgList &DriverArgs,
2324                                  ArgStringList &CC1Args) const {
2325  const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2326  bool UseInitArrayDefault
2327    = V >= Generic_GCC::GCCVersion::Parse("4.7.0") ||
2328      getTriple().getArch() == llvm::Triple::aarch64 ||
2329      getTriple().getEnvironment() == llvm::Triple::Android;
2330  if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2331                         options::OPT_fno_use_init_array,
2332                         UseInitArrayDefault))
2333    CC1Args.push_back("-fuse-init-array");
2334}
2335
2336std::string Linux::computeSysRoot(const ArgList &Args) const {
2337  if (!getDriver().SysRoot.empty())
2338    return getDriver().SysRoot;
2339
2340  if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
2341    return std::string();
2342
2343  std::string Path =
2344    (GCCInstallation.getInstallPath() +
2345     "/../../../../" + GCCInstallation.getTriple().str() + "/libc").str();
2346  appendMipsTargetSuffix(Path, getTriple().getArch(), Args);
2347
2348  return llvm::sys::fs::exists(Path) ? Path : "";
2349}
2350
2351void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2352                                      ArgStringList &CC1Args) const {
2353  const Driver &D = getDriver();
2354  std::string SysRoot = computeSysRoot(DriverArgs);
2355
2356  if (DriverArgs.hasArg(options::OPT_nostdinc))
2357    return;
2358
2359  if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2360    addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
2361
2362  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2363    SmallString<128> P(D.ResourceDir);
2364    llvm::sys::path::append(P, "include");
2365    addSystemInclude(DriverArgs, CC1Args, P.str());
2366  }
2367
2368  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2369    return;
2370
2371  // Check for configure-time C include directories.
2372  StringRef CIncludeDirs(C_INCLUDE_DIRS);
2373  if (CIncludeDirs != "") {
2374    SmallVector<StringRef, 5> dirs;
2375    CIncludeDirs.split(dirs, ":");
2376    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2377         I != E; ++I) {
2378      StringRef Prefix = llvm::sys::path::is_absolute(*I) ? SysRoot : "";
2379      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2380    }
2381    return;
2382  }
2383
2384  // Lacking those, try to detect the correct set of system includes for the
2385  // target triple.
2386
2387  // Sourcery CodeBench and modern FSF Mips toolchains put extern C
2388  // system includes under three additional directories.
2389  if (GCCInstallation.isValid() && isMipsArch(getTriple().getArch())) {
2390    addExternCSystemIncludeIfExists(
2391        DriverArgs, CC1Args, GCCInstallation.getInstallPath() + "/include");
2392
2393    addExternCSystemIncludeIfExists(
2394        DriverArgs, CC1Args,
2395        GCCInstallation.getInstallPath() + "/../../../../" +
2396            GCCInstallation.getTriple().str() + "/libc/usr/include");
2397  }
2398
2399  // Implement generic Debian multiarch support.
2400  const StringRef X86_64MultiarchIncludeDirs[] = {
2401    "/usr/include/x86_64-linux-gnu",
2402
2403    // FIXME: These are older forms of multiarch. It's not clear that they're
2404    // in use in any released version of Debian, so we should consider
2405    // removing them.
2406    "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"
2407  };
2408  const StringRef X86MultiarchIncludeDirs[] = {
2409    "/usr/include/i386-linux-gnu",
2410
2411    // FIXME: These are older forms of multiarch. It's not clear that they're
2412    // in use in any released version of Debian, so we should consider
2413    // removing them.
2414    "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
2415    "/usr/include/i486-linux-gnu"
2416  };
2417  const StringRef AArch64MultiarchIncludeDirs[] = {
2418    "/usr/include/aarch64-linux-gnu"
2419  };
2420  const StringRef ARMMultiarchIncludeDirs[] = {
2421    "/usr/include/arm-linux-gnueabi"
2422  };
2423  const StringRef ARMHFMultiarchIncludeDirs[] = {
2424    "/usr/include/arm-linux-gnueabihf"
2425  };
2426  const StringRef MIPSMultiarchIncludeDirs[] = {
2427    "/usr/include/mips-linux-gnu"
2428  };
2429  const StringRef MIPSELMultiarchIncludeDirs[] = {
2430    "/usr/include/mipsel-linux-gnu"
2431  };
2432  const StringRef PPCMultiarchIncludeDirs[] = {
2433    "/usr/include/powerpc-linux-gnu"
2434  };
2435  const StringRef PPC64MultiarchIncludeDirs[] = {
2436    "/usr/include/powerpc64-linux-gnu"
2437  };
2438  ArrayRef<StringRef> MultiarchIncludeDirs;
2439  if (getTriple().getArch() == llvm::Triple::x86_64) {
2440    MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2441  } else if (getTriple().getArch() == llvm::Triple::x86) {
2442    MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2443  } else if (getTriple().getArch() == llvm::Triple::aarch64) {
2444    MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
2445  } else if (getTriple().getArch() == llvm::Triple::arm) {
2446    if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2447      MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2448    else
2449      MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2450  } else if (getTriple().getArch() == llvm::Triple::mips) {
2451    MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2452  } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2453    MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2454  } else if (getTriple().getArch() == llvm::Triple::ppc) {
2455    MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2456  } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2457    MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2458  }
2459  for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2460                                     E = MultiarchIncludeDirs.end();
2461       I != E; ++I) {
2462    if (llvm::sys::fs::exists(SysRoot + *I)) {
2463      addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + *I);
2464      break;
2465    }
2466  }
2467
2468  if (getTriple().getOS() == llvm::Triple::RTEMS)
2469    return;
2470
2471  // Add an include of '/include' directly. This isn't provided by default by
2472  // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2473  // add even when Clang is acting as-if it were a system compiler.
2474  addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
2475
2476  addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
2477}
2478
2479/// \brief Helper to add the three variant paths for a libstdc++ installation.
2480/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2481                                                const ArgList &DriverArgs,
2482                                                ArgStringList &CC1Args) {
2483  if (!llvm::sys::fs::exists(Base))
2484    return false;
2485  addSystemInclude(DriverArgs, CC1Args, Base);
2486  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2487  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2488  return true;
2489}
2490
2491/// \brief Helper to add an extra variant path for an (Ubuntu) multilib
2492/// libstdc++ installation.
2493/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
2494                                                Twine TargetArchDir,
2495                                                Twine MultiLibSuffix,
2496                                                const ArgList &DriverArgs,
2497                                                ArgStringList &CC1Args) {
2498  if (!addLibStdCXXIncludePaths(Base+Suffix, TargetArchDir + MultiLibSuffix,
2499                                DriverArgs, CC1Args))
2500    return false;
2501
2502  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir + Suffix
2503                   + MultiLibSuffix);
2504  return true;
2505}
2506
2507void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2508                                         ArgStringList &CC1Args) const {
2509  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2510      DriverArgs.hasArg(options::OPT_nostdincxx))
2511    return;
2512
2513  // Check if libc++ has been enabled and provide its include paths if so.
2514  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2515    // libc++ is always installed at a fixed path on Linux currently.
2516    addSystemInclude(DriverArgs, CC1Args,
2517                     getDriver().SysRoot + "/usr/include/c++/v1");
2518    return;
2519  }
2520
2521  // We need a detected GCC installation on Linux to provide libstdc++'s
2522  // headers. We handled the libc++ case above.
2523  if (!GCCInstallation.isValid())
2524    return;
2525
2526  // By default, look for the C++ headers in an include directory adjacent to
2527  // the lib directory of the GCC installation. Note that this is expect to be
2528  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2529  StringRef LibDir = GCCInstallation.getParentLibPath();
2530  StringRef InstallDir = GCCInstallation.getInstallPath();
2531  StringRef Version = GCCInstallation.getVersion().Text;
2532  StringRef TripleStr = GCCInstallation.getTriple().str();
2533
2534  if (addLibStdCXXIncludePaths(
2535          LibDir.str() + "/../include", "/c++/" + Version.str(), TripleStr,
2536          GCCInstallation.getBiarchSuffix(), DriverArgs, CC1Args))
2537    return;
2538
2539  const std::string IncludePathCandidates[] = {
2540    // Gentoo is weird and places its headers inside the GCC install, so if the
2541    // first attempt to find the headers fails, try this pattern.
2542    InstallDir.str() + "/include/g++-v4",
2543    // Android standalone toolchain has C++ headers in yet another place.
2544    LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2545    // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2546    // without a subdirectory corresponding to the gcc version.
2547    LibDir.str() + "/../include/c++",
2548  };
2549
2550  for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2551    if (addLibStdCXXIncludePaths(
2552            IncludePathCandidates[i],
2553            (TripleStr + GCCInstallation.getBiarchSuffix()), DriverArgs,
2554            CC1Args))
2555      break;
2556  }
2557}
2558
2559bool Linux::isPIEDefault() const {
2560  return IsPIEDefault;
2561}
2562
2563/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2564
2565DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2566  : Generic_ELF(D, Triple, Args) {
2567
2568  // Path mangling to find libexec
2569  getProgramPaths().push_back(getDriver().getInstalledDir());
2570  if (getDriver().getInstalledDir() != getDriver().Dir)
2571    getProgramPaths().push_back(getDriver().Dir);
2572
2573  getFilePaths().push_back(getDriver().Dir + "/../lib");
2574  getFilePaths().push_back("/usr/lib");
2575  if (llvm::sys::fs::exists("/usr/lib/gcc47"))
2576    getFilePaths().push_back("/usr/lib/gcc47");
2577  else
2578    getFilePaths().push_back("/usr/lib/gcc44");
2579}
2580
2581Tool *DragonFly::buildAssembler() const {
2582  return new tools::dragonfly::Assemble(*this);
2583}
2584
2585Tool *DragonFly::buildLinker() const {
2586  return new tools::dragonfly::Link(*this);
2587}
2588