ToolChains.cpp revision 5f5c37b1234e6ebb6c17e084bc4e2cce92e31585
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/HostInfo.h"
18#include "clang/Driver/OptTable.h"
19#include "clang/Driver/Option.h"
20#include "clang/Driver/Options.h"
21#include "clang/Basic/Version.h"
22
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/system_error.h"
31
32#include <cstdlib> // ::getenv
33
34using namespace clang::driver;
35using namespace clang::driver::toolchains;
36
37/// Darwin - Darwin tool chain for i386 and x86_64.
38
39Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple)
40  : ToolChain(Host, Triple), TargetInitialized(false)
41{
42  // Compute the initial Darwin version based on the host.
43  bool HadExtra;
44  std::string OSName = Triple.getOSName();
45  if (!Driver::GetReleaseVersion(&OSName.c_str()[6],
46                                 DarwinVersion[0], DarwinVersion[1],
47                                 DarwinVersion[2], HadExtra))
48    getDriver().Diag(clang::diag::err_drv_invalid_darwin_version) << OSName;
49
50  llvm::raw_string_ostream(MacosxVersionMin)
51    << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.'
52    << DarwinVersion[1];
53}
54
55types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
56  types::ID Ty = types::lookupTypeForExtension(Ext);
57
58  // Darwin always preprocesses assembly files (unless -x is used explicitly).
59  if (Ty == types::TY_PP_Asm)
60    return types::TY_Asm;
61
62  return Ty;
63}
64
65bool Darwin::HasNativeLLVMSupport() const {
66  return true;
67}
68
69// FIXME: Can we tablegen this?
70static const char *GetArmArchForMArch(llvm::StringRef Value) {
71  if (Value == "armv6k")
72    return "armv6";
73
74  if (Value == "armv5tej")
75    return "armv5";
76
77  if (Value == "xscale")
78    return "xscale";
79
80  if (Value == "armv4t")
81    return "armv4t";
82
83  if (Value == "armv7" || Value == "armv7-a" || Value == "armv7-r" ||
84      Value == "armv7-m" || Value == "armv7a" || Value == "armv7r" ||
85      Value == "armv7m")
86    return "armv7";
87
88  return 0;
89}
90
91// FIXME: Can we tablegen this?
92static const char *GetArmArchForMCpu(llvm::StringRef Value) {
93  if (Value == "arm10tdmi" || Value == "arm1020t" || Value == "arm9e" ||
94      Value == "arm946e-s" || Value == "arm966e-s" ||
95      Value == "arm968e-s" || Value == "arm10e" ||
96      Value == "arm1020e" || Value == "arm1022e" || Value == "arm926ej-s" ||
97      Value == "arm1026ej-s")
98    return "armv5";
99
100  if (Value == "xscale")
101    return "xscale";
102
103  if (Value == "arm1136j-s" || Value == "arm1136jf-s" ||
104      Value == "arm1176jz-s" || Value == "arm1176jzf-s" ||
105      Value == "cortex-m0" )
106    return "armv6";
107
108  if (Value == "cortex-a8" || Value == "cortex-r4" || Value == "cortex-m3")
109    return "armv7";
110
111  return 0;
112}
113
114llvm::StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
115  switch (getTriple().getArch()) {
116  default:
117    return getArchName();
118
119  case llvm::Triple::thumb:
120  case llvm::Triple::arm: {
121    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
122      if (const char *Arch = GetArmArchForMArch(A->getValue(Args)))
123        return Arch;
124
125    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
126      if (const char *Arch = GetArmArchForMCpu(A->getValue(Args)))
127        return Arch;
128
129    return "arm";
130  }
131  }
132}
133
134Darwin::~Darwin() {
135  // Free tool implementations.
136  for (llvm::DenseMap<unsigned, Tool*>::iterator
137         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
138    delete it->second;
139}
140
141std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args) const {
142  llvm::Triple Triple(ComputeLLVMTriple(Args));
143
144  // If the target isn't initialized (e.g., an unknown Darwin platform, return
145  // the default triple).
146  if (!isTargetInitialized())
147    return Triple.getTriple();
148
149  unsigned Version[3];
150  getTargetVersion(Version);
151
152  llvm::SmallString<16> Str;
153  llvm::raw_svector_ostream(Str)
154    << (isTargetIPhoneOS() ? "ios" : "macosx")
155    << Version[0] << "." << Version[1] << "." << Version[2];
156  Triple.setOSName(Str.str());
157
158  return Triple.getTriple();
159}
160
161Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
162                         const ActionList &Inputs) const {
163  Action::ActionClass Key;
164
165  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
166    // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI.
167    if (Inputs.size() == 1 &&
168        types::isCXX(Inputs[0]->getType()) &&
169        getTriple().getOS() == llvm::Triple::Darwin &&
170        getTriple().getArch() == llvm::Triple::x86 &&
171        C.getArgs().getLastArg(options::OPT_fapple_kext))
172      Key = JA.getKind();
173    else
174      Key = Action::AnalyzeJobClass;
175  } else
176    Key = JA.getKind();
177
178  // FIXME: This doesn't belong here, but ideally we will support static soon
179  // anyway.
180  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
181                    C.getArgs().hasArg(options::OPT_static) ||
182                    C.getArgs().hasArg(options::OPT_fapple_kext));
183  bool IsIADefault = IsIntegratedAssemblerDefault() && !HasStatic;
184  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
185                                             options::OPT_no_integrated_as,
186                                             IsIADefault);
187
188  Tool *&T = Tools[Key];
189  if (!T) {
190    switch (Key) {
191    case Action::InputClass:
192    case Action::BindArchClass:
193      assert(0 && "Invalid tool kind.");
194    case Action::PreprocessJobClass:
195      T = new tools::darwin::Preprocess(*this); break;
196    case Action::AnalyzeJobClass:
197      T = new tools::Clang(*this); break;
198    case Action::PrecompileJobClass:
199    case Action::CompileJobClass:
200      T = new tools::darwin::Compile(*this); break;
201    case Action::AssembleJobClass: {
202      if (UseIntegratedAs)
203        T = new tools::ClangAs(*this);
204      else
205        T = new tools::darwin::Assemble(*this);
206      break;
207    }
208    case Action::LinkJobClass:
209      T = new tools::darwin::Link(*this); break;
210    case Action::LipoJobClass:
211      T = new tools::darwin::Lipo(*this); break;
212    case Action::DsymutilJobClass:
213      T = new tools::darwin::Dsymutil(*this); break;
214    }
215  }
216
217  return *T;
218}
219
220
221DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple)
222  : Darwin(Host, Triple)
223{
224  std::string UsrPrefix = "llvm-gcc-4.2/";
225
226  getProgramPaths().push_back(getDriver().getInstalledDir());
227  if (getDriver().getInstalledDir() != getDriver().Dir)
228    getProgramPaths().push_back(getDriver().Dir);
229
230  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
231  getProgramPaths().push_back(getDriver().getInstalledDir());
232  if (getDriver().getInstalledDir() != getDriver().Dir)
233    getProgramPaths().push_back(getDriver().Dir);
234
235  // For fallback, we need to know how to find the GCC cc1 executables, so we
236  // also add the GCC libexec paths. This is legacy code that can be removed
237  // once fallback is no longer useful.
238  std::string ToolChainDir = "i686-apple-darwin";
239  ToolChainDir += llvm::utostr(DarwinVersion[0]);
240  ToolChainDir += "/4.2.1";
241
242  std::string Path = getDriver().Dir;
243  Path += "/../" + UsrPrefix + "libexec/gcc/";
244  Path += ToolChainDir;
245  getProgramPaths().push_back(Path);
246
247  Path = "/usr/" + UsrPrefix + "libexec/gcc/";
248  Path += ToolChainDir;
249  getProgramPaths().push_back(Path);
250}
251
252void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args,
253                                       ArgStringList &CmdArgs) const {
254  // The Clang toolchain uses explicit paths for internal libraries.
255
256  // Unfortunately, we still might depend on a few of the libraries that are
257  // only available in the gcc library directory (in particular
258  // libstdc++.dylib). For now, hardcode the path to the known install location.
259  llvm::sys::Path P(getDriver().Dir);
260  P.eraseComponent(); // .../usr/bin -> ../usr
261  P.appendComponent("lib");
262  P.appendComponent("gcc");
263  switch (getTriple().getArch()) {
264  default:
265    assert(0 && "Invalid Darwin arch!");
266  case llvm::Triple::x86:
267  case llvm::Triple::x86_64:
268    P.appendComponent("i686-apple-darwin10");
269    break;
270  case llvm::Triple::arm:
271  case llvm::Triple::thumb:
272    P.appendComponent("arm-apple-darwin10");
273    break;
274  case llvm::Triple::ppc:
275  case llvm::Triple::ppc64:
276    P.appendComponent("powerpc-apple-darwin10");
277    break;
278  }
279  P.appendComponent("4.2.1");
280
281  // Determine the arch specific GCC subdirectory.
282  const char *ArchSpecificDir = 0;
283  switch (getTriple().getArch()) {
284  default:
285    break;
286  case llvm::Triple::arm:
287  case llvm::Triple::thumb: {
288    std::string Triple = ComputeLLVMTriple(Args);
289    llvm::StringRef TripleStr = Triple;
290    if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5"))
291      ArchSpecificDir = "v5";
292    else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6"))
293      ArchSpecificDir = "v6";
294    else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7"))
295      ArchSpecificDir = "v7";
296    break;
297  }
298  case llvm::Triple::ppc64:
299    ArchSpecificDir = "ppc64";
300    break;
301  case llvm::Triple::x86_64:
302    ArchSpecificDir = "x86_64";
303    break;
304  }
305
306  if (ArchSpecificDir) {
307    P.appendComponent(ArchSpecificDir);
308    bool Exists;
309    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
310      CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
311    P.eraseComponent();
312  }
313
314  bool Exists;
315  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
316    CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
317}
318
319void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
320                                        ArgStringList &CmdArgs) const {
321  // Darwin doesn't support real static executables, don't link any runtime
322  // libraries with -static.
323  if (Args.hasArg(options::OPT_static))
324    return;
325
326  // Reject -static-libgcc for now, we can deal with this when and if someone
327  // cares. This is useful in situations where someone wants to statically link
328  // something like libstdc++, and needs its runtime support routines.
329  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
330    getDriver().Diag(clang::diag::err_drv_unsupported_opt)
331      << A->getAsString(Args);
332    return;
333  }
334
335  // Otherwise link libSystem, then the dynamic runtime library, and finally any
336  // target specific static runtime library.
337  CmdArgs.push_back("-lSystem");
338
339  // Select the dynamic runtime library and the target specific static library.
340  const char *DarwinStaticLib = 0;
341  if (isTargetIPhoneOS()) {
342    CmdArgs.push_back("-lgcc_s.1");
343
344    // We currently always need a static runtime library for iOS.
345    DarwinStaticLib = "libclang_rt.ios.a";
346  } else {
347    // The dynamic runtime library was merged with libSystem for 10.6 and
348    // beyond; only 10.4 and 10.5 need an additional runtime library.
349    if (isMacosxVersionLT(10, 5))
350      CmdArgs.push_back("-lgcc_s.10.4");
351    else if (isMacosxVersionLT(10, 6))
352      CmdArgs.push_back("-lgcc_s.10.5");
353
354    // For OS X, we thought we would only need a static runtime library when
355    // targeting 10.4, to provide versions of the static functions which were
356    // omitted from 10.4.dylib.
357    //
358    // Unfortunately, that turned out to not be true, because Darwin system
359    // headers can still use eprintf on i386, and it is not exported from
360    // libSystem. Therefore, we still must provide a runtime library just for
361    // the tiny tiny handful of projects that *might* use that symbol.
362    if (isMacosxVersionLT(10, 5)) {
363      DarwinStaticLib = "libclang_rt.10.4.a";
364    } else {
365      if (getTriple().getArch() == llvm::Triple::x86)
366        DarwinStaticLib = "libclang_rt.eprintf.a";
367    }
368  }
369
370  /// Add the target specific static library, if needed.
371  if (DarwinStaticLib) {
372    llvm::sys::Path P(getDriver().ResourceDir);
373    P.appendComponent("lib");
374    P.appendComponent("darwin");
375    P.appendComponent(DarwinStaticLib);
376
377    // For now, allow missing resource libraries to support developers who may
378    // not have compiler-rt checked out or integrated into their build.
379    bool Exists;
380    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
381      CmdArgs.push_back(Args.MakeArgString(P.str()));
382  }
383}
384
385void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
386  const OptTable &Opts = getDriver().getOpts();
387
388  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
389  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
390  Arg *iOSSimVersion = Args.getLastArg(
391    options::OPT_mios_simulator_version_min_EQ);
392  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
393    getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with)
394          << OSXVersion->getAsString(Args)
395          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
396    iOSVersion = iOSSimVersion = 0;
397  } else if (iOSVersion && iOSSimVersion) {
398    getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with)
399          << iOSVersion->getAsString(Args)
400          << iOSSimVersion->getAsString(Args);
401    iOSSimVersion = 0;
402  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
403    // If not deployment target was specified on the command line, check for
404    // environment defines.
405    const char *OSXTarget = ::getenv("MACOSX_DEPLOYMENT_TARGET");
406    const char *iOSTarget = ::getenv("IPHONEOS_DEPLOYMENT_TARGET");
407    const char *iOSSimTarget = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET");
408
409    // Ignore empty strings.
410    if (OSXTarget && OSXTarget[0] == '\0')
411      OSXTarget = 0;
412    if (iOSTarget && iOSTarget[0] == '\0')
413      iOSTarget = 0;
414    if (iOSSimTarget && iOSSimTarget[0] == '\0')
415      iOSSimTarget = 0;
416
417    // Handle conflicting deployment targets
418    //
419    // FIXME: Don't hardcode default here.
420
421    // Do not allow conflicts with the iOS simulator target.
422    if (iOSSimTarget && (OSXTarget || iOSTarget)) {
423      getDriver().Diag(clang::diag::err_drv_conflicting_deployment_targets)
424        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
425        << (OSXTarget ? "MACOSX_DEPLOYMENT_TARGET" :
426            "IPHONEOS_DEPLOYMENT_TARGET");
427    }
428
429    // Allow conflicts among OSX and iOS for historical reasons, but choose the
430    // default platform.
431    if (OSXTarget && iOSTarget) {
432      if (getTriple().getArch() == llvm::Triple::arm ||
433          getTriple().getArch() == llvm::Triple::thumb)
434        OSXTarget = 0;
435      else
436        iOSTarget = 0;
437    }
438
439    if (OSXTarget) {
440      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
441      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
442      Args.append(OSXVersion);
443    } else if (iOSTarget) {
444      const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
445      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
446      Args.append(iOSVersion);
447    } else if (iOSSimTarget) {
448      const Option *O = Opts.getOption(
449        options::OPT_mios_simulator_version_min_EQ);
450      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
451      Args.append(iOSSimVersion);
452    } else {
453      // Otherwise, assume we are targeting OS X.
454      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
455      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
456      Args.append(OSXVersion);
457    }
458  }
459
460  // Set the tool chain target information.
461  unsigned Major, Minor, Micro;
462  bool HadExtra;
463  if (OSXVersion) {
464    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
465    if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor,
466                                   Micro, HadExtra) || HadExtra ||
467        Major != 10 || Minor >= 100 || Micro >= 100)
468      getDriver().Diag(clang::diag::err_drv_invalid_version_number)
469        << OSXVersion->getAsString(Args);
470  } else {
471    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
472    assert(Version && "Unknown target platform!");
473    if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor,
474                                   Micro, HadExtra) || HadExtra ||
475        Major >= 10 || Minor >= 100 || Micro >= 100)
476      getDriver().Diag(clang::diag::err_drv_invalid_version_number)
477        << Version->getAsString(Args);
478  }
479
480  bool IsIOSSim = bool(iOSSimVersion);
481
482  // In GCC, the simulator historically was treated as being OS X in some
483  // contexts, like determining the link logic, despite generally being called
484  // with an iOS deployment target. For compatibility, we detect the
485  // simulator as iOS + x86, and treat it differently in a few contexts.
486  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
487                     getTriple().getArch() == llvm::Triple::x86_64))
488    IsIOSSim = true;
489
490  setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
491}
492
493void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
494                                      ArgStringList &CmdArgs) const {
495  CXXStdlibType Type = GetCXXStdlibType(Args);
496
497  switch (Type) {
498  case ToolChain::CST_Libcxx:
499    CmdArgs.push_back("-lc++");
500    break;
501
502  case ToolChain::CST_Libstdcxx: {
503    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
504    // it was previously found in the gcc lib dir. However, for all the Darwin
505    // platforms we care about it was -lstdc++.6, so we search for that
506    // explicitly if we can't see an obvious -lstdc++ candidate.
507
508    // Check in the sysroot first.
509    bool Exists;
510    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
511      llvm::sys::Path P(A->getValue(Args));
512      P.appendComponent("usr");
513      P.appendComponent("lib");
514      P.appendComponent("libstdc++.dylib");
515
516      if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
517        P.eraseComponent();
518        P.appendComponent("libstdc++.6.dylib");
519        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
520          CmdArgs.push_back(Args.MakeArgString(P.str()));
521          return;
522        }
523      }
524    }
525
526    // Otherwise, look in the root.
527    if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
528      (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
529      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
530      return;
531    }
532
533    // Otherwise, let the linker search.
534    CmdArgs.push_back("-lstdc++");
535    break;
536  }
537  }
538}
539
540void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
541                                   ArgStringList &CmdArgs) const {
542
543  // For Darwin platforms, use the compiler-rt-based support library
544  // instead of the gcc-provided one (which is also incidentally
545  // only present in the gcc lib dir, which makes it hard to find).
546
547  llvm::sys::Path P(getDriver().ResourceDir);
548  P.appendComponent("lib");
549  P.appendComponent("darwin");
550  P.appendComponent("libclang_rt.cc_kext.a");
551
552  // For now, allow missing resource libraries to support developers who may
553  // not have compiler-rt checked out or integrated into their build.
554  bool Exists;
555  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
556    CmdArgs.push_back(Args.MakeArgString(P.str()));
557}
558
559DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
560                                      const char *BoundArch) const {
561  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
562  const OptTable &Opts = getDriver().getOpts();
563
564  // FIXME: We really want to get out of the tool chain level argument
565  // translation business, as it makes the driver functionality much
566  // more opaque. For now, we follow gcc closely solely for the
567  // purpose of easily achieving feature parity & testability. Once we
568  // have something that works, we should reevaluate each translation
569  // and try to push it down into tool specific logic.
570
571  for (ArgList::const_iterator it = Args.begin(),
572         ie = Args.end(); it != ie; ++it) {
573    Arg *A = *it;
574
575    if (A->getOption().matches(options::OPT_Xarch__)) {
576      // FIXME: Canonicalize name.
577      if (getArchName() != A->getValue(Args, 0))
578        continue;
579
580      Arg *OriginalArg = A;
581      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1));
582      unsigned Prev = Index;
583      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
584
585      // If the argument parsing failed or more than one argument was
586      // consumed, the -Xarch_ argument's parameter tried to consume
587      // extra arguments. Emit an error and ignore.
588      //
589      // We also want to disallow any options which would alter the
590      // driver behavior; that isn't going to work in our model. We
591      // use isDriverOption() as an approximation, although things
592      // like -O4 are going to slip through.
593      if (!XarchArg || Index > Prev + 1) {
594        getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument_with_args)
595          << A->getAsString(Args);
596        continue;
597      } else if (XarchArg->getOption().isDriverOption()) {
598        getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument_isdriver)
599          << A->getAsString(Args);
600        continue;
601      }
602
603      XarchArg->setBaseArg(A);
604      A = XarchArg;
605
606      DAL->AddSynthesizedArg(A);
607
608      // Linker input arguments require custom handling. The problem is that we
609      // have already constructed the phase actions, so we can not treat them as
610      // "input arguments".
611      if (A->getOption().isLinkerInput()) {
612        // Convert the argument into individual Zlinker_input_args.
613        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
614          DAL->AddSeparateArg(OriginalArg,
615                              Opts.getOption(options::OPT_Zlinker_input),
616                              A->getValue(Args, i));
617
618        }
619        continue;
620      }
621    }
622
623    // Sob. These is strictly gcc compatible for the time being. Apple
624    // gcc translates options twice, which means that self-expanding
625    // options add duplicates.
626    switch ((options::ID) A->getOption().getID()) {
627    default:
628      DAL->append(A);
629      break;
630
631    case options::OPT_mkernel:
632    case options::OPT_fapple_kext:
633      DAL->append(A);
634      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
635      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
636      break;
637
638    case options::OPT_dependency_file:
639      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
640                          A->getValue(Args));
641      break;
642
643    case options::OPT_gfull:
644      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
645      DAL->AddFlagArg(A,
646               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
647      break;
648
649    case options::OPT_gused:
650      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
651      DAL->AddFlagArg(A,
652             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
653      break;
654
655    case options::OPT_fterminated_vtables:
656    case options::OPT_findirect_virtual_calls:
657      DAL->AddFlagArg(A, Opts.getOption(options::OPT_fapple_kext));
658      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
659      break;
660
661    case options::OPT_shared:
662      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
663      break;
664
665    case options::OPT_fconstant_cfstrings:
666      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
667      break;
668
669    case options::OPT_fno_constant_cfstrings:
670      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
671      break;
672
673    case options::OPT_Wnonportable_cfstrings:
674      DAL->AddFlagArg(A,
675                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
676      break;
677
678    case options::OPT_Wno_nonportable_cfstrings:
679      DAL->AddFlagArg(A,
680                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
681      break;
682
683    case options::OPT_fpascal_strings:
684      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
685      break;
686
687    case options::OPT_fno_pascal_strings:
688      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
689      break;
690    }
691  }
692
693  if (getTriple().getArch() == llvm::Triple::x86 ||
694      getTriple().getArch() == llvm::Triple::x86_64)
695    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
696      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
697
698  // Add the arch options based on the particular spelling of -arch, to match
699  // how the driver driver works.
700  if (BoundArch) {
701    llvm::StringRef Name = BoundArch;
702    const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ);
703    const Option *MArch = Opts.getOption(options::OPT_march_EQ);
704
705    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
706    // which defines the list of which architectures we accept.
707    if (Name == "ppc")
708      ;
709    else if (Name == "ppc601")
710      DAL->AddJoinedArg(0, MCpu, "601");
711    else if (Name == "ppc603")
712      DAL->AddJoinedArg(0, MCpu, "603");
713    else if (Name == "ppc604")
714      DAL->AddJoinedArg(0, MCpu, "604");
715    else if (Name == "ppc604e")
716      DAL->AddJoinedArg(0, MCpu, "604e");
717    else if (Name == "ppc750")
718      DAL->AddJoinedArg(0, MCpu, "750");
719    else if (Name == "ppc7400")
720      DAL->AddJoinedArg(0, MCpu, "7400");
721    else if (Name == "ppc7450")
722      DAL->AddJoinedArg(0, MCpu, "7450");
723    else if (Name == "ppc970")
724      DAL->AddJoinedArg(0, MCpu, "970");
725
726    else if (Name == "ppc64")
727      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
728
729    else if (Name == "i386")
730      ;
731    else if (Name == "i486")
732      DAL->AddJoinedArg(0, MArch, "i486");
733    else if (Name == "i586")
734      DAL->AddJoinedArg(0, MArch, "i586");
735    else if (Name == "i686")
736      DAL->AddJoinedArg(0, MArch, "i686");
737    else if (Name == "pentium")
738      DAL->AddJoinedArg(0, MArch, "pentium");
739    else if (Name == "pentium2")
740      DAL->AddJoinedArg(0, MArch, "pentium2");
741    else if (Name == "pentpro")
742      DAL->AddJoinedArg(0, MArch, "pentiumpro");
743    else if (Name == "pentIIm3")
744      DAL->AddJoinedArg(0, MArch, "pentium2");
745
746    else if (Name == "x86_64")
747      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
748
749    else if (Name == "arm")
750      DAL->AddJoinedArg(0, MArch, "armv4t");
751    else if (Name == "armv4t")
752      DAL->AddJoinedArg(0, MArch, "armv4t");
753    else if (Name == "armv5")
754      DAL->AddJoinedArg(0, MArch, "armv5tej");
755    else if (Name == "xscale")
756      DAL->AddJoinedArg(0, MArch, "xscale");
757    else if (Name == "armv6")
758      DAL->AddJoinedArg(0, MArch, "armv6k");
759    else if (Name == "armv7")
760      DAL->AddJoinedArg(0, MArch, "armv7a");
761
762    else
763      llvm_unreachable("invalid Darwin arch");
764  }
765
766  // Add an explicit version min argument for the deployment target. We do this
767  // after argument translation because -Xarch_ arguments may add a version min
768  // argument.
769  AddDeploymentTarget(*DAL);
770
771  return DAL;
772}
773
774bool Darwin::IsUnwindTablesDefault() const {
775  // FIXME: Gross; we should probably have some separate target
776  // definition, possibly even reusing the one in clang.
777  return getArchName() == "x86_64";
778}
779
780bool Darwin::UseDwarfDebugFlags() const {
781  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
782    return S[0] != '\0';
783  return false;
784}
785
786bool Darwin::UseSjLjExceptions() const {
787  // Darwin uses SjLj exceptions on ARM.
788  return (getTriple().getArch() == llvm::Triple::arm ||
789          getTriple().getArch() == llvm::Triple::thumb);
790}
791
792const char *Darwin::GetDefaultRelocationModel() const {
793  return "pic";
794}
795
796const char *Darwin::GetForcedPicModel() const {
797  if (getArchName() == "x86_64")
798    return "pic";
799  return 0;
800}
801
802bool Darwin::SupportsProfiling() const {
803  // Profiling instrumentation is only supported on x86.
804  return getArchName() == "i386" || getArchName() == "x86_64";
805}
806
807bool Darwin::SupportsObjCGC() const {
808  // Garbage collection is supported everywhere except on iPhone OS.
809  return !isTargetIPhoneOS();
810}
811
812std::string
813Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args) const {
814  return ComputeLLVMTriple(Args);
815}
816
817/// Generic_GCC - A tool chain using the 'gcc' command to perform
818/// all subcommands; this relies on gcc translating the majority of
819/// command line options.
820
821Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
822  : ToolChain(Host, Triple) {
823  getProgramPaths().push_back(getDriver().getInstalledDir());
824  if (getDriver().getInstalledDir() != getDriver().Dir)
825    getProgramPaths().push_back(getDriver().Dir);
826}
827
828Generic_GCC::~Generic_GCC() {
829  // Free tool implementations.
830  for (llvm::DenseMap<unsigned, Tool*>::iterator
831         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
832    delete it->second;
833}
834
835Tool &Generic_GCC::SelectTool(const Compilation &C,
836                              const JobAction &JA,
837                              const ActionList &Inputs) const {
838  Action::ActionClass Key;
839  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
840    Key = Action::AnalyzeJobClass;
841  else
842    Key = JA.getKind();
843
844  Tool *&T = Tools[Key];
845  if (!T) {
846    switch (Key) {
847    case Action::InputClass:
848    case Action::BindArchClass:
849      assert(0 && "Invalid tool kind.");
850    case Action::PreprocessJobClass:
851      T = new tools::gcc::Preprocess(*this); break;
852    case Action::PrecompileJobClass:
853      T = new tools::gcc::Precompile(*this); break;
854    case Action::AnalyzeJobClass:
855      T = new tools::Clang(*this); break;
856    case Action::CompileJobClass:
857      T = new tools::gcc::Compile(*this); break;
858    case Action::AssembleJobClass:
859      T = new tools::gcc::Assemble(*this); break;
860    case Action::LinkJobClass:
861      T = new tools::gcc::Link(*this); break;
862
863      // This is a bit ungeneric, but the only platform using a driver
864      // driver is Darwin.
865    case Action::LipoJobClass:
866      T = new tools::darwin::Lipo(*this); break;
867    case Action::DsymutilJobClass:
868      T = new tools::darwin::Dsymutil(*this); break;
869    }
870  }
871
872  return *T;
873}
874
875bool Generic_GCC::IsUnwindTablesDefault() const {
876  // FIXME: Gross; we should probably have some separate target
877  // definition, possibly even reusing the one in clang.
878  return getArchName() == "x86_64";
879}
880
881const char *Generic_GCC::GetDefaultRelocationModel() const {
882  return "static";
883}
884
885const char *Generic_GCC::GetForcedPicModel() const {
886  return 0;
887}
888
889/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
890/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
891/// Currently does not support anything else but compilation.
892
893TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple)
894  : ToolChain(Host, Triple) {
895  // Path mangling to find libexec
896  std::string Path(getDriver().Dir);
897
898  Path += "/../libexec";
899  getProgramPaths().push_back(Path);
900}
901
902TCEToolChain::~TCEToolChain() {
903  for (llvm::DenseMap<unsigned, Tool*>::iterator
904           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
905      delete it->second;
906}
907
908bool TCEToolChain::IsMathErrnoDefault() const {
909  return true;
910}
911
912bool TCEToolChain::IsUnwindTablesDefault() const {
913  return false;
914}
915
916const char *TCEToolChain::GetDefaultRelocationModel() const {
917  return "static";
918}
919
920const char *TCEToolChain::GetForcedPicModel() const {
921  return 0;
922}
923
924Tool &TCEToolChain::SelectTool(const Compilation &C,
925                            const JobAction &JA,
926                               const ActionList &Inputs) const {
927  Action::ActionClass Key;
928  Key = Action::AnalyzeJobClass;
929
930  Tool *&T = Tools[Key];
931  if (!T) {
932    switch (Key) {
933    case Action::PreprocessJobClass:
934      T = new tools::gcc::Preprocess(*this); break;
935    case Action::AnalyzeJobClass:
936      T = new tools::Clang(*this); break;
937    default:
938     assert(false && "Unsupported action for TCE target.");
939    }
940  }
941  return *T;
942}
943
944/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
945
946OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple)
947  : Generic_ELF(Host, Triple) {
948  getFilePaths().push_back(getDriver().Dir + "/../lib");
949  getFilePaths().push_back("/usr/lib");
950}
951
952Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
953                          const ActionList &Inputs) const {
954  Action::ActionClass Key;
955  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
956    Key = Action::AnalyzeJobClass;
957  else
958    Key = JA.getKind();
959
960  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
961                                             options::OPT_no_integrated_as,
962                                             IsIntegratedAssemblerDefault());
963
964  Tool *&T = Tools[Key];
965  if (!T) {
966    switch (Key) {
967    case Action::AssembleJobClass: {
968      if (UseIntegratedAs)
969        T = new tools::ClangAs(*this);
970      else
971        T = new tools::openbsd::Assemble(*this);
972      break;
973    }
974    case Action::LinkJobClass:
975      T = new tools::openbsd::Link(*this); break;
976    default:
977      T = &Generic_GCC::SelectTool(C, JA, Inputs);
978    }
979  }
980
981  return *T;
982}
983
984/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
985
986FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple)
987  : Generic_ELF(Host, Triple) {
988
989  // Determine if we are compiling 32-bit code on an x86_64 platform.
990  bool Lib32 = false;
991  if (Triple.getArch() == llvm::Triple::x86 &&
992      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
993        llvm::Triple::x86_64)
994    Lib32 = true;
995
996  if (Lib32) {
997    getFilePaths().push_back("/usr/lib32");
998  } else {
999    getFilePaths().push_back("/usr/lib");
1000  }
1001}
1002
1003Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1004                          const ActionList &Inputs) const {
1005  Action::ActionClass Key;
1006  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1007    Key = Action::AnalyzeJobClass;
1008  else
1009    Key = JA.getKind();
1010
1011  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1012                                             options::OPT_no_integrated_as,
1013                                             IsIntegratedAssemblerDefault());
1014
1015  Tool *&T = Tools[Key];
1016  if (!T) {
1017    switch (Key) {
1018    case Action::AssembleJobClass:
1019      if (UseIntegratedAs)
1020        T = new tools::ClangAs(*this);
1021      else
1022        T = new tools::freebsd::Assemble(*this);
1023      break;
1024    case Action::LinkJobClass:
1025      T = new tools::freebsd::Link(*this); break;
1026    default:
1027      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1028    }
1029  }
1030
1031  return *T;
1032}
1033
1034/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1035
1036NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple)
1037  : Generic_ELF(Host, Triple) {
1038
1039  // Determine if we are compiling 32-bit code on an x86_64 platform.
1040  bool Lib32 = false;
1041  if (Triple.getArch() == llvm::Triple::x86 &&
1042      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1043        llvm::Triple::x86_64)
1044    Lib32 = true;
1045
1046  if (getDriver().UseStdLib) {
1047    if (Lib32)
1048      getFilePaths().push_back("=/usr/lib/i386");
1049    else
1050      getFilePaths().push_back("=/usr/lib");
1051  }
1052}
1053
1054Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1055                         const ActionList &Inputs) const {
1056  Action::ActionClass Key;
1057  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1058    Key = Action::AnalyzeJobClass;
1059  else
1060    Key = JA.getKind();
1061
1062  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1063                                             options::OPT_no_integrated_as,
1064                                             IsIntegratedAssemblerDefault());
1065
1066  Tool *&T = Tools[Key];
1067  if (!T) {
1068    switch (Key) {
1069    case Action::AssembleJobClass:
1070      if (UseIntegratedAs)
1071        T = new tools::ClangAs(*this);
1072      else
1073        T = new tools::netbsd::Assemble(*this);
1074      break;
1075    case Action::LinkJobClass:
1076      T = new tools::netbsd::Link(*this); break;
1077    default:
1078      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1079    }
1080  }
1081
1082  return *T;
1083}
1084
1085/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1086
1087Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
1088  : Generic_GCC(Host, Triple) {
1089  getFilePaths().push_back(getDriver().Dir + "/../lib");
1090  getFilePaths().push_back("/usr/lib");
1091  getFilePaths().push_back("/usr/gnu/lib");
1092  getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
1093}
1094
1095Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1096                        const ActionList &Inputs) const {
1097  Action::ActionClass Key;
1098  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1099    Key = Action::AnalyzeJobClass;
1100  else
1101    Key = JA.getKind();
1102
1103  Tool *&T = Tools[Key];
1104  if (!T) {
1105    switch (Key) {
1106    case Action::AssembleJobClass:
1107      T = new tools::minix::Assemble(*this); break;
1108    case Action::LinkJobClass:
1109      T = new tools::minix::Link(*this); break;
1110    default:
1111      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1112    }
1113  }
1114
1115  return *T;
1116}
1117
1118/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1119
1120AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
1121  : Generic_GCC(Host, Triple) {
1122
1123  getProgramPaths().push_back(getDriver().getInstalledDir());
1124  if (getDriver().getInstalledDir() != getDriver().Dir)
1125    getProgramPaths().push_back(getDriver().Dir);
1126
1127  getFilePaths().push_back(getDriver().Dir + "/../lib");
1128  getFilePaths().push_back("/usr/lib");
1129  getFilePaths().push_back("/usr/sfw/lib");
1130  getFilePaths().push_back("/opt/gcc4/lib");
1131  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1132
1133}
1134
1135Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1136                           const ActionList &Inputs) const {
1137  Action::ActionClass Key;
1138  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1139    Key = Action::AnalyzeJobClass;
1140  else
1141    Key = JA.getKind();
1142
1143  Tool *&T = Tools[Key];
1144  if (!T) {
1145    switch (Key) {
1146    case Action::AssembleJobClass:
1147      T = new tools::auroraux::Assemble(*this); break;
1148    case Action::LinkJobClass:
1149      T = new tools::auroraux::Link(*this); break;
1150    default:
1151      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1152    }
1153  }
1154
1155  return *T;
1156}
1157
1158
1159/// Linux toolchain (very bare-bones at the moment).
1160
1161enum LinuxDistro {
1162  ArchLinux,
1163  DebianLenny,
1164  DebianSqueeze,
1165  Exherbo,
1166  Fedora13,
1167  Fedora14,
1168  Fedora15,
1169  FedoraRawhide,
1170  OpenSuse11_3,
1171  UbuntuHardy,
1172  UbuntuIntrepid,
1173  UbuntuJaunty,
1174  UbuntuKarmic,
1175  UbuntuLucid,
1176  UbuntuMaverick,
1177  UbuntuNatty,
1178  UnknownDistro
1179};
1180
1181static bool IsFedora(enum LinuxDistro Distro) {
1182  return Distro == Fedora13 || Distro == Fedora14 ||
1183         Distro == Fedora15 || Distro == FedoraRawhide;
1184}
1185
1186static bool IsOpenSuse(enum LinuxDistro Distro) {
1187  return Distro == OpenSuse11_3;
1188}
1189
1190static bool IsDebian(enum LinuxDistro Distro) {
1191  return Distro == DebianLenny || Distro == DebianSqueeze;
1192}
1193
1194static bool IsUbuntu(enum LinuxDistro Distro) {
1195  return Distro == UbuntuHardy  || Distro == UbuntuIntrepid ||
1196         Distro == UbuntuLucid  || Distro == UbuntuMaverick ||
1197         Distro == UbuntuJaunty || Distro == UbuntuKarmic ||
1198         Distro == UbuntuNatty;
1199}
1200
1201static bool IsDebianBased(enum LinuxDistro Distro) {
1202  return IsDebian(Distro) || IsUbuntu(Distro);
1203}
1204
1205static bool HasMultilib(llvm::Triple::ArchType Arch, enum LinuxDistro Distro) {
1206  if (Arch == llvm::Triple::x86_64) {
1207    bool Exists;
1208    if (Distro == Exherbo &&
1209        (llvm::sys::fs::exists("/usr/lib32/libc.so", Exists) || !Exists))
1210      return false;
1211
1212    return true;
1213  }
1214  if (Arch == llvm::Triple::ppc64)
1215    return true;
1216  if ((Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc) && IsDebianBased(Distro))
1217    return true;
1218  return false;
1219}
1220
1221static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1222  llvm::OwningPtr<llvm::MemoryBuffer> File;
1223  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1224    llvm::StringRef Data = File.get()->getBuffer();
1225    llvm::SmallVector<llvm::StringRef, 8> Lines;
1226    Data.split(Lines, "\n");
1227    for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) {
1228      if (Lines[i] == "DISTRIB_CODENAME=hardy")
1229        return UbuntuHardy;
1230      else if (Lines[i] == "DISTRIB_CODENAME=intrepid")
1231        return UbuntuIntrepid;
1232      else if (Lines[i] == "DISTRIB_CODENAME=jaunty")
1233        return UbuntuJaunty;
1234      else if (Lines[i] == "DISTRIB_CODENAME=karmic")
1235        return UbuntuKarmic;
1236      else if (Lines[i] == "DISTRIB_CODENAME=lucid")
1237        return UbuntuLucid;
1238      else if (Lines[i] == "DISTRIB_CODENAME=maverick")
1239        return UbuntuMaverick;
1240      else if (Lines[i] == "DISTRIB_CODENAME=natty")
1241        return UbuntuNatty;
1242    }
1243    return UnknownDistro;
1244  }
1245
1246  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1247    llvm::StringRef Data = File.get()->getBuffer();
1248    if (Data.startswith("Fedora release 15"))
1249      return Fedora15;
1250    else if (Data.startswith("Fedora release 14"))
1251      return Fedora14;
1252    else if (Data.startswith("Fedora release 13"))
1253      return Fedora13;
1254    else if (Data.startswith("Fedora release") &&
1255             Data.find("Rawhide") != llvm::StringRef::npos)
1256      return FedoraRawhide;
1257    return UnknownDistro;
1258  }
1259
1260  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1261    llvm::StringRef Data = File.get()->getBuffer();
1262    if (Data[0] == '5')
1263      return DebianLenny;
1264    else if (Data.startswith("squeeze/sid"))
1265      return DebianSqueeze;
1266    return UnknownDistro;
1267  }
1268
1269  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
1270    llvm::StringRef Data = File.get()->getBuffer();
1271    if (Data.startswith("openSUSE 11.3"))
1272      return OpenSuse11_3;
1273    return UnknownDistro;
1274  }
1275
1276  bool Exists;
1277  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1278    return Exherbo;
1279
1280  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1281    return ArchLinux;
1282
1283  return UnknownDistro;
1284}
1285
1286Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
1287  : Generic_ELF(Host, Triple) {
1288  llvm::Triple::ArchType Arch =
1289    llvm::Triple(getDriver().DefaultHostTriple).getArch();
1290
1291  std::string Suffix32  = "";
1292  if (Arch == llvm::Triple::x86_64)
1293    Suffix32 = "/32";
1294
1295  std::string Suffix64  = "";
1296  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
1297    Suffix64 = "/64";
1298
1299  std::string Lib32 = "lib";
1300
1301  bool Exists;
1302  if (!llvm::sys::fs::exists("/lib32", Exists) && Exists)
1303    Lib32 = "lib32";
1304
1305  std::string Lib64 = "lib";
1306  bool Symlink;
1307  if (!llvm::sys::fs::exists("/lib64", Exists) && Exists &&
1308      (llvm::sys::fs::is_symlink("/lib64", Symlink) || !Symlink))
1309    Lib64 = "lib64";
1310
1311  std::string GccTriple = "";
1312  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
1313    if (!llvm::sys::fs::exists("/usr/lib/gcc/arm-linux-gnueabi", Exists) &&
1314        Exists)
1315      GccTriple = "arm-linux-gnueabi";
1316  } else if (Arch == llvm::Triple::x86_64) {
1317    if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-linux-gnu", Exists) &&
1318        Exists)
1319      GccTriple = "x86_64-linux-gnu";
1320    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-unknown-linux-gnu",
1321             Exists) && Exists)
1322      GccTriple = "x86_64-unknown-linux-gnu";
1323    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-pc-linux-gnu",
1324             Exists) && Exists)
1325      GccTriple = "x86_64-pc-linux-gnu";
1326    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-redhat-linux",
1327             Exists) && Exists)
1328      GccTriple = "x86_64-redhat-linux";
1329    else if (!llvm::sys::fs::exists("/usr/lib64/gcc/x86_64-suse-linux",
1330             Exists) && Exists)
1331      GccTriple = "x86_64-suse-linux";
1332    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-manbo-linux-gnu",
1333             Exists) && Exists)
1334      GccTriple = "x86_64-manbo-linux-gnu";
1335    else if (!llvm::sys::fs::exists("/usr/lib/x86_64-linux-gnu/gcc",
1336             Exists) && Exists)
1337      GccTriple = "x86_64-linux-gnu";
1338  } else if (Arch == llvm::Triple::x86) {
1339    if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-linux-gnu", Exists) && Exists)
1340      GccTriple = "i686-linux-gnu";
1341    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-pc-linux-gnu", Exists) &&
1342             Exists)
1343      GccTriple = "i686-pc-linux-gnu";
1344    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-linux-gnu", Exists) &&
1345             Exists)
1346      GccTriple = "i486-linux-gnu";
1347    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-redhat-linux", Exists) &&
1348             Exists)
1349      GccTriple = "i686-redhat-linux";
1350    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i586-suse-linux", Exists) &&
1351             Exists)
1352      GccTriple = "i586-suse-linux";
1353    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-slackware-linux", Exists)
1354            && Exists)
1355      GccTriple = "i486-slackware-linux";
1356  } else if (Arch == llvm::Triple::ppc) {
1357    if (!llvm::sys::fs::exists("/usr/lib/powerpc-linux-gnu", Exists) && Exists)
1358      GccTriple = "powerpc-linux-gnu";
1359    else if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc-unknown-linux-gnu", Exists) && Exists)
1360      GccTriple = "powerpc-unknown-linux-gnu";
1361  } else if (Arch == llvm::Triple::ppc64) {
1362    if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc64-unknown-linux-gnu", Exists) && Exists)
1363      GccTriple = "powerpc64-unknown-linux-gnu";
1364    else if (!llvm::sys::fs::exists("/usr/lib64/gcc/powerpc64-unknown-linux-gnu", Exists) && Exists)
1365      GccTriple = "powerpc64-unknown-linux-gnu";
1366  }
1367
1368  const char* GccVersions[] = {"4.6.0",
1369                               "4.5.2", "4.5.1", "4.5",
1370                               "4.4.5", "4.4.4", "4.4.3", "4.4",
1371                               "4.3.4", "4.3.3", "4.3.2", "4.3",
1372                               "4.2.4", "4.2.3", "4.2.2", "4.2.1", "4.2"};
1373  std::string Base = "";
1374  for (unsigned i = 0; i < sizeof(GccVersions)/sizeof(char*); ++i) {
1375    std::string Suffix = GccTriple + "/" + GccVersions[i];
1376    std::string t1 = "/usr/lib/gcc/" + Suffix;
1377    if (!llvm::sys::fs::exists(t1 + "/crtbegin.o", Exists) && Exists) {
1378      Base = t1;
1379      break;
1380    }
1381    std::string t2 = "/usr/lib64/gcc/" + Suffix;
1382    if (!llvm::sys::fs::exists(t2 + "/crtbegin.o", Exists) && Exists) {
1383      Base = t2;
1384      break;
1385    }
1386    std::string t3 = "/usr/lib/" + GccTriple + "/gcc/" + Suffix;
1387    if (!llvm::sys::fs::exists(t3 + "/crtbegin.o", Exists) && Exists) {
1388      Base = t3;
1389      break;
1390    }
1391  }
1392
1393  path_list &Paths = getFilePaths();
1394  bool Is32Bits = (getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::ppc);
1395
1396  std::string Suffix;
1397  std::string Lib;
1398
1399  if (Is32Bits) {
1400    Suffix = Suffix32;
1401    Lib = Lib32;
1402  } else {
1403    Suffix = Suffix64;
1404    Lib = Lib64;
1405  }
1406
1407  llvm::sys::Path LinkerPath(Base + "/../../../../" + GccTriple + "/bin/ld");
1408  if (!llvm::sys::fs::exists(LinkerPath.str(), Exists) && Exists)
1409    Linker = LinkerPath.str();
1410  else
1411    Linker = GetProgramPath("ld");
1412
1413  LinuxDistro Distro = DetectLinuxDistro(Arch);
1414
1415  if (IsUbuntu(Distro)) {
1416    ExtraOpts.push_back("-z");
1417    ExtraOpts.push_back("relro");
1418  }
1419
1420  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
1421    ExtraOpts.push_back("-X");
1422
1423  if (IsFedora(Distro) || Distro == UbuntuMaverick || Distro == UbuntuNatty)
1424    ExtraOpts.push_back("--hash-style=gnu");
1425
1426  if (IsDebian(Distro) || Distro == UbuntuLucid || Distro == UbuntuJaunty ||
1427      Distro == UbuntuKarmic)
1428    ExtraOpts.push_back("--hash-style=both");
1429
1430  if (IsFedora(Distro))
1431    ExtraOpts.push_back("--no-add-needed");
1432
1433  if (Distro == DebianSqueeze || IsOpenSuse(Distro) ||
1434      IsFedora(Distro) || Distro == UbuntuLucid || Distro == UbuntuMaverick ||
1435      Distro == UbuntuKarmic || Distro == UbuntuNatty)
1436    ExtraOpts.push_back("--build-id");
1437
1438  if (Distro == ArchLinux)
1439    Lib = "lib";
1440
1441  Paths.push_back(Base + Suffix);
1442  if (HasMultilib(Arch, Distro)) {
1443    if (IsOpenSuse(Distro) && Is32Bits)
1444      Paths.push_back(Base + "/../../../../" + GccTriple + "/lib/../lib");
1445    Paths.push_back(Base + "/../../../../" + Lib);
1446    Paths.push_back("/lib/../" + Lib);
1447    Paths.push_back("/usr/lib/../" + Lib);
1448  }
1449  if (!Suffix.empty())
1450    Paths.push_back(Base);
1451  if (IsOpenSuse(Distro))
1452    Paths.push_back(Base + "/../../../../" + GccTriple + "/lib");
1453  Paths.push_back(Base + "/../../..");
1454  if (Arch == getArch() && IsUbuntu(Distro))
1455    Paths.push_back("/usr/lib/" + GccTriple);
1456}
1457
1458bool Linux::HasNativeLLVMSupport() const {
1459  return true;
1460}
1461
1462Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
1463                        const ActionList &Inputs) const {
1464  Action::ActionClass Key;
1465  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1466    Key = Action::AnalyzeJobClass;
1467  else
1468    Key = JA.getKind();
1469
1470  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1471                                             options::OPT_no_integrated_as,
1472                                             IsIntegratedAssemblerDefault());
1473
1474  Tool *&T = Tools[Key];
1475  if (!T) {
1476    switch (Key) {
1477    case Action::AssembleJobClass:
1478      if (UseIntegratedAs)
1479        T = new tools::ClangAs(*this);
1480      else
1481        T = new tools::linuxtools::Assemble(*this);
1482      break;
1483    case Action::LinkJobClass:
1484      T = new tools::linuxtools::Link(*this); break;
1485    default:
1486      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1487    }
1488  }
1489
1490  return *T;
1491}
1492
1493/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
1494
1495DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
1496  : Generic_ELF(Host, Triple) {
1497
1498  // Path mangling to find libexec
1499  getProgramPaths().push_back(getDriver().getInstalledDir());
1500  if (getDriver().getInstalledDir() != getDriver().Dir)
1501    getProgramPaths().push_back(getDriver().Dir);
1502
1503  getFilePaths().push_back(getDriver().Dir + "/../lib");
1504  getFilePaths().push_back("/usr/lib");
1505  getFilePaths().push_back("/usr/lib/gcc41");
1506}
1507
1508Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
1509                            const ActionList &Inputs) const {
1510  Action::ActionClass Key;
1511  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1512    Key = Action::AnalyzeJobClass;
1513  else
1514    Key = JA.getKind();
1515
1516  Tool *&T = Tools[Key];
1517  if (!T) {
1518    switch (Key) {
1519    case Action::AssembleJobClass:
1520      T = new tools::dragonfly::Assemble(*this); break;
1521    case Action::LinkJobClass:
1522      T = new tools::dragonfly::Link(*this); break;
1523    default:
1524      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1525    }
1526  }
1527
1528  return *T;
1529}
1530
1531Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple)
1532  : ToolChain(Host, Triple) {
1533}
1534
1535Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA,
1536                          const ActionList &Inputs) const {
1537  Action::ActionClass Key;
1538  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1539    Key = Action::AnalyzeJobClass;
1540  else
1541    Key = JA.getKind();
1542
1543  Tool *&T = Tools[Key];
1544  if (!T) {
1545    switch (Key) {
1546    case Action::InputClass:
1547    case Action::BindArchClass:
1548    case Action::LipoJobClass:
1549    case Action::DsymutilJobClass:
1550      assert(0 && "Invalid tool kind.");
1551    case Action::PreprocessJobClass:
1552    case Action::PrecompileJobClass:
1553    case Action::AnalyzeJobClass:
1554    case Action::CompileJobClass:
1555      T = new tools::Clang(*this); break;
1556    case Action::AssembleJobClass:
1557      T = new tools::ClangAs(*this); break;
1558    case Action::LinkJobClass:
1559      T = new tools::visualstudio::Link(*this); break;
1560    }
1561  }
1562
1563  return *T;
1564}
1565
1566bool Windows::IsIntegratedAssemblerDefault() const {
1567  return true;
1568}
1569
1570bool Windows::IsUnwindTablesDefault() const {
1571  // FIXME: Gross; we should probably have some separate target
1572  // definition, possibly even reusing the one in clang.
1573  return getArchName() == "x86_64";
1574}
1575
1576const char *Windows::GetDefaultRelocationModel() const {
1577  return "static";
1578}
1579
1580const char *Windows::GetForcedPicModel() const {
1581  if (getArchName() == "x86_64")
1582    return "pic";
1583  return 0;
1584}
1585