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