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