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