ToolChains.cpp revision 3393cef18e887723aaa2395d33550ab35551af1d
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#ifdef HAVE_CLANG_CONFIG_H
13# include "clang/Config/config.h"
14#endif
15
16#include "clang/Driver/Arg.h"
17#include "clang/Driver/ArgList.h"
18#include "clang/Driver/Compilation.h"
19#include "clang/Driver/Driver.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/HostInfo.h"
22#include "clang/Driver/OptTable.h"
23#include "clang/Driver/Option.h"
24#include "clang/Driver/Options.h"
25#include "clang/Basic/Version.h"
26
27#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/FileSystem.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/system_error.h"
35
36#include <cstdlib> // ::getenv
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 (Triple.getArch() == llvm::Triple::ppc &&
1011      llvm::Triple(getDriver().DefaultHostTriple).getArch() ==
1012        llvm::Triple::ppc64)
1013    Lib32 = true;
1014
1015  if (Lib32) {
1016    getFilePaths().push_back("/usr/lib32");
1017  } else {
1018    getFilePaths().push_back("/usr/lib");
1019  }
1020}
1021
1022Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1023                          const ActionList &Inputs) const {
1024  Action::ActionClass Key;
1025  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1026    Key = Action::AnalyzeJobClass;
1027  else
1028    Key = JA.getKind();
1029
1030  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1031                                             options::OPT_no_integrated_as,
1032                                             IsIntegratedAssemblerDefault());
1033
1034  Tool *&T = Tools[Key];
1035  if (!T) {
1036    switch (Key) {
1037    case Action::AssembleJobClass:
1038      if (UseIntegratedAs)
1039        T = new tools::ClangAs(*this);
1040      else
1041        T = new tools::freebsd::Assemble(*this);
1042      break;
1043    case Action::LinkJobClass:
1044      T = new tools::freebsd::Link(*this); break;
1045    default:
1046      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1047    }
1048  }
1049
1050  return *T;
1051}
1052
1053/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1054
1055NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple,
1056               const llvm::Triple& ToolTriple)
1057  : Generic_ELF(Host, Triple), ToolTriple(ToolTriple) {
1058
1059  // Determine if we are compiling 32-bit code on an x86_64 platform.
1060  bool Lib32 = false;
1061  if (ToolTriple.getArch() == llvm::Triple::x86_64 &&
1062      Triple.getArch() == llvm::Triple::x86)
1063    Lib32 = true;
1064
1065  if (getDriver().UseStdLib) {
1066    if (Lib32)
1067      getFilePaths().push_back("=/usr/lib/i386");
1068    else
1069      getFilePaths().push_back("=/usr/lib");
1070  }
1071}
1072
1073Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1074                         const ActionList &Inputs) const {
1075  Action::ActionClass Key;
1076  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1077    Key = Action::AnalyzeJobClass;
1078  else
1079    Key = JA.getKind();
1080
1081  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1082                                             options::OPT_no_integrated_as,
1083                                             IsIntegratedAssemblerDefault());
1084
1085  Tool *&T = Tools[Key];
1086  if (!T) {
1087    switch (Key) {
1088    case Action::AssembleJobClass:
1089      if (UseIntegratedAs)
1090        T = new tools::ClangAs(*this);
1091      else
1092        T = new tools::netbsd::Assemble(*this, ToolTriple);
1093      break;
1094    case Action::LinkJobClass:
1095      T = new tools::netbsd::Link(*this, ToolTriple);
1096      break;
1097    default:
1098      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1099    }
1100  }
1101
1102  return *T;
1103}
1104
1105/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1106
1107Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
1108  : Generic_GCC(Host, Triple) {
1109  getFilePaths().push_back(getDriver().Dir + "/../lib");
1110  getFilePaths().push_back("/usr/lib");
1111  getFilePaths().push_back("/usr/gnu/lib");
1112  getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
1113}
1114
1115Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1116                        const ActionList &Inputs) const {
1117  Action::ActionClass Key;
1118  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1119    Key = Action::AnalyzeJobClass;
1120  else
1121    Key = JA.getKind();
1122
1123  Tool *&T = Tools[Key];
1124  if (!T) {
1125    switch (Key) {
1126    case Action::AssembleJobClass:
1127      T = new tools::minix::Assemble(*this); break;
1128    case Action::LinkJobClass:
1129      T = new tools::minix::Link(*this); break;
1130    default:
1131      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1132    }
1133  }
1134
1135  return *T;
1136}
1137
1138/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1139
1140AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
1141  : Generic_GCC(Host, Triple) {
1142
1143  getProgramPaths().push_back(getDriver().getInstalledDir());
1144  if (getDriver().getInstalledDir() != getDriver().Dir)
1145    getProgramPaths().push_back(getDriver().Dir);
1146
1147  getFilePaths().push_back(getDriver().Dir + "/../lib");
1148  getFilePaths().push_back("/usr/lib");
1149  getFilePaths().push_back("/usr/sfw/lib");
1150  getFilePaths().push_back("/opt/gcc4/lib");
1151  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1152
1153}
1154
1155Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1156                           const ActionList &Inputs) const {
1157  Action::ActionClass Key;
1158  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1159    Key = Action::AnalyzeJobClass;
1160  else
1161    Key = JA.getKind();
1162
1163  Tool *&T = Tools[Key];
1164  if (!T) {
1165    switch (Key) {
1166    case Action::AssembleJobClass:
1167      T = new tools::auroraux::Assemble(*this); break;
1168    case Action::LinkJobClass:
1169      T = new tools::auroraux::Link(*this); break;
1170    default:
1171      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1172    }
1173  }
1174
1175  return *T;
1176}
1177
1178
1179/// Linux toolchain (very bare-bones at the moment).
1180
1181enum LinuxDistro {
1182  ArchLinux,
1183  DebianLenny,
1184  DebianSqueeze,
1185  DebianWheezy,
1186  Exherbo,
1187  RHEL4,
1188  RHEL5,
1189  RHEL6,
1190  Fedora13,
1191  Fedora14,
1192  Fedora15,
1193  FedoraRawhide,
1194  OpenSuse11_3,
1195  OpenSuse11_4,
1196  OpenSuse12_1,
1197  UbuntuHardy,
1198  UbuntuIntrepid,
1199  UbuntuJaunty,
1200  UbuntuKarmic,
1201  UbuntuLucid,
1202  UbuntuMaverick,
1203  UbuntuNatty,
1204  UnknownDistro
1205};
1206
1207static bool IsRedhat(enum LinuxDistro Distro) {
1208  return Distro == Fedora13 || Distro == Fedora14 ||
1209         Distro == Fedora15 || Distro == FedoraRawhide ||
1210         Distro == RHEL4 || Distro == RHEL5 || Distro == RHEL6;
1211}
1212
1213static bool IsOpenSuse(enum LinuxDistro Distro) {
1214  return Distro == OpenSuse11_3 || Distro == OpenSuse11_4 ||
1215         Distro == OpenSuse12_1;
1216}
1217
1218static bool IsDebian(enum LinuxDistro Distro) {
1219  return Distro == DebianLenny || Distro == DebianSqueeze ||
1220         Distro == DebianWheezy;
1221}
1222
1223static bool IsUbuntu(enum LinuxDistro Distro) {
1224  return Distro == UbuntuHardy  || Distro == UbuntuIntrepid ||
1225         Distro == UbuntuLucid  || Distro == UbuntuMaverick ||
1226         Distro == UbuntuJaunty || Distro == UbuntuKarmic ||
1227         Distro == UbuntuNatty;
1228}
1229
1230static bool IsDebianBased(enum LinuxDistro Distro) {
1231  return IsDebian(Distro) || IsUbuntu(Distro);
1232}
1233
1234static bool HasMultilib(llvm::Triple::ArchType Arch, enum LinuxDistro Distro) {
1235  if (Arch == llvm::Triple::x86_64) {
1236    bool Exists;
1237    if (Distro == Exherbo &&
1238        (llvm::sys::fs::exists("/usr/lib32/libc.so", Exists) || !Exists))
1239      return false;
1240
1241    return true;
1242  }
1243  if (Arch == llvm::Triple::ppc64)
1244    return true;
1245  if ((Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc) &&
1246      IsDebianBased(Distro))
1247    return true;
1248  return false;
1249}
1250
1251static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1252  llvm::OwningPtr<llvm::MemoryBuffer> File;
1253  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1254    llvm::StringRef Data = File.get()->getBuffer();
1255    llvm::SmallVector<llvm::StringRef, 8> Lines;
1256    Data.split(Lines, "\n");
1257    for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) {
1258      if (Lines[i] == "DISTRIB_CODENAME=hardy")
1259        return UbuntuHardy;
1260      else if (Lines[i] == "DISTRIB_CODENAME=intrepid")
1261        return UbuntuIntrepid;
1262      else if (Lines[i] == "DISTRIB_CODENAME=jaunty")
1263        return UbuntuJaunty;
1264      else if (Lines[i] == "DISTRIB_CODENAME=karmic")
1265        return UbuntuKarmic;
1266      else if (Lines[i] == "DISTRIB_CODENAME=lucid")
1267        return UbuntuLucid;
1268      else if (Lines[i] == "DISTRIB_CODENAME=maverick")
1269        return UbuntuMaverick;
1270      else if (Lines[i] == "DISTRIB_CODENAME=natty")
1271        return UbuntuNatty;
1272    }
1273    return UnknownDistro;
1274  }
1275
1276  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1277    llvm::StringRef Data = File.get()->getBuffer();
1278    if (Data.startswith("Fedora release 15"))
1279      return Fedora15;
1280    else if (Data.startswith("Fedora release 14"))
1281      return Fedora14;
1282    else if (Data.startswith("Fedora release 13"))
1283      return Fedora13;
1284    else if (Data.startswith("Fedora release") &&
1285             Data.find("Rawhide") != llvm::StringRef::npos)
1286      return FedoraRawhide;
1287    else if (Data.startswith("Red Hat Enterprise Linux") &&
1288             Data.find("release 6") != llvm::StringRef::npos)
1289      return RHEL6;
1290    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1291	      Data.startswith("CentOS")) &&
1292             Data.find("release 5") != llvm::StringRef::npos)
1293      return RHEL5;
1294    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1295	      Data.startswith("CentOS")) &&
1296             Data.find("release 4") != llvm::StringRef::npos)
1297      return RHEL4;
1298    return UnknownDistro;
1299  }
1300
1301  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1302    llvm::StringRef Data = File.get()->getBuffer();
1303    if (Data[0] == '5')
1304      return DebianLenny;
1305    else if (Data.startswith("squeeze/sid"))
1306      return DebianSqueeze;
1307    else if (Data.startswith("wheezy/sid"))
1308      return DebianWheezy;
1309    return UnknownDistro;
1310  }
1311
1312  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
1313    llvm::StringRef Data = File.get()->getBuffer();
1314    if (Data.startswith("openSUSE 11.3"))
1315      return OpenSuse11_3;
1316    else if (Data.startswith("openSUSE 11.4"))
1317      return OpenSuse11_4;
1318    else if (Data.startswith("openSUSE 12.1"))
1319      return OpenSuse12_1;
1320    return UnknownDistro;
1321  }
1322
1323  bool Exists;
1324  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1325    return Exherbo;
1326
1327  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1328    return ArchLinux;
1329
1330  return UnknownDistro;
1331}
1332
1333static std::string findGCCBaseLibDir(const std::string &GccTriple) {
1334  // FIXME: Using CXX_INCLUDE_ROOT is here is a bit of a hack, but
1335  // avoids adding yet another option to configure/cmake.
1336  // It would probably be cleaner to break it in two variables
1337  // CXX_GCC_ROOT with just /foo/bar
1338  // CXX_GCC_VER with 4.5.2
1339  // Then we would have
1340  // CXX_INCLUDE_ROOT = CXX_GCC_ROOT/include/c++/CXX_GCC_VER
1341  // and this function would return
1342  // CXX_GCC_ROOT/lib/gcc/CXX_INCLUDE_ARCH/CXX_GCC_VER
1343  llvm::SmallString<128> CxxIncludeRoot(CXX_INCLUDE_ROOT);
1344  if (CxxIncludeRoot != "") {
1345    // This is of the form /foo/bar/include/c++/4.5.2/
1346    if (CxxIncludeRoot.back() == '/')
1347      llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the /
1348    llvm::StringRef Version = llvm::sys::path::filename(CxxIncludeRoot);
1349    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the version
1350    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the c++
1351    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the include
1352    std::string ret(CxxIncludeRoot.c_str());
1353    ret.append("/lib/gcc/");
1354    ret.append(CXX_INCLUDE_ARCH);
1355    ret.append("/");
1356    ret.append(Version);
1357    return ret;
1358  }
1359  static const char* GccVersions[] = {"4.6.0", "4.6",
1360                                      "4.5.2", "4.5.1", "4.5",
1361                                      "4.4.5", "4.4.4", "4.4.3", "4.4",
1362                                      "4.3.4", "4.3.3", "4.3.2", "4.3",
1363                                      "4.2.4", "4.2.3", "4.2.2", "4.2.1",
1364                                      "4.2", "4.1.1"};
1365  bool Exists;
1366  for (unsigned i = 0; i < sizeof(GccVersions)/sizeof(char*); ++i) {
1367    std::string Suffix = GccTriple + "/" + GccVersions[i];
1368    std::string t1 = "/usr/lib/gcc/" + Suffix;
1369    if (!llvm::sys::fs::exists(t1 + "/crtbegin.o", Exists) && Exists)
1370      return t1;
1371    std::string t2 = "/usr/lib64/gcc/" + Suffix;
1372    if (!llvm::sys::fs::exists(t2 + "/crtbegin.o", Exists) && Exists)
1373      return t2;
1374    std::string t3 = "/usr/lib/" + GccTriple + "/gcc/" + Suffix;
1375    if (!llvm::sys::fs::exists(t3 + "/crtbegin.o", Exists) && Exists)
1376      return t3;
1377  }
1378  return "";
1379}
1380
1381Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
1382  : Generic_ELF(Host, Triple) {
1383  llvm::Triple::ArchType Arch =
1384    llvm::Triple(getDriver().DefaultHostTriple).getArch();
1385
1386  std::string Suffix32  = "";
1387  if (Arch == llvm::Triple::x86_64)
1388    Suffix32 = "/32";
1389
1390  std::string Suffix64  = "";
1391  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
1392    Suffix64 = "/64";
1393
1394  std::string Lib32 = "lib";
1395
1396  bool Exists;
1397  if (!llvm::sys::fs::exists("/lib32", Exists) && Exists)
1398    Lib32 = "lib32";
1399
1400  std::string Lib64 = "lib";
1401  bool Symlink;
1402  if (!llvm::sys::fs::exists("/lib64", Exists) && Exists &&
1403      (llvm::sys::fs::is_symlink("/lib64", Symlink) || !Symlink))
1404    Lib64 = "lib64";
1405
1406  std::string GccTriple = "";
1407  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
1408    if (!llvm::sys::fs::exists("/usr/lib/gcc/arm-linux-gnueabi", Exists) &&
1409        Exists)
1410      GccTriple = "arm-linux-gnueabi";
1411  } else if (Arch == llvm::Triple::x86_64) {
1412    if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-linux-gnu", Exists) &&
1413        Exists)
1414      GccTriple = "x86_64-linux-gnu";
1415    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-unknown-linux-gnu",
1416             Exists) && Exists)
1417      GccTriple = "x86_64-unknown-linux-gnu";
1418    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-pc-linux-gnu",
1419             Exists) && Exists)
1420      GccTriple = "x86_64-pc-linux-gnu";
1421    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-redhat-linux",
1422             Exists) && Exists)
1423      GccTriple = "x86_64-redhat-linux";
1424    else if (!llvm::sys::fs::exists("/usr/lib64/gcc/x86_64-suse-linux",
1425             Exists) && Exists)
1426      GccTriple = "x86_64-suse-linux";
1427    else if (!llvm::sys::fs::exists("/usr/lib/gcc/x86_64-manbo-linux-gnu",
1428             Exists) && Exists)
1429      GccTriple = "x86_64-manbo-linux-gnu";
1430    else if (!llvm::sys::fs::exists("/usr/lib/x86_64-linux-gnu/gcc",
1431             Exists) && Exists)
1432      GccTriple = "x86_64-linux-gnu";
1433  } else if (Arch == llvm::Triple::x86) {
1434    if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-linux-gnu", Exists) && Exists)
1435      GccTriple = "i686-linux-gnu";
1436    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-pc-linux-gnu", Exists) &&
1437             Exists)
1438      GccTriple = "i686-pc-linux-gnu";
1439    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-linux-gnu", Exists) &&
1440             Exists)
1441      GccTriple = "i486-linux-gnu";
1442    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i686-redhat-linux", Exists) &&
1443             Exists)
1444      GccTriple = "i686-redhat-linux";
1445    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i586-suse-linux", Exists) &&
1446             Exists)
1447      GccTriple = "i586-suse-linux";
1448    else if (!llvm::sys::fs::exists("/usr/lib/gcc/i486-slackware-linux", Exists)
1449            && Exists)
1450      GccTriple = "i486-slackware-linux";
1451  } else if (Arch == llvm::Triple::ppc) {
1452    if (!llvm::sys::fs::exists("/usr/lib/powerpc-linux-gnu", Exists) && Exists)
1453      GccTriple = "powerpc-linux-gnu";
1454    else if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc-unknown-linux-gnu",
1455                                    Exists) && Exists)
1456      GccTriple = "powerpc-unknown-linux-gnu";
1457  } else if (Arch == llvm::Triple::ppc64) {
1458    if (!llvm::sys::fs::exists("/usr/lib/gcc/powerpc64-unknown-linux-gnu",
1459                               Exists) && Exists)
1460      GccTriple = "powerpc64-unknown-linux-gnu";
1461    else if (!llvm::sys::fs::exists("/usr/lib64/gcc/"
1462                                    "powerpc64-unknown-linux-gnu", Exists) &&
1463             Exists)
1464      GccTriple = "powerpc64-unknown-linux-gnu";
1465  }
1466
1467  std::string Base = findGCCBaseLibDir(GccTriple);
1468  path_list &Paths = getFilePaths();
1469  bool Is32Bits = (getArch() == llvm::Triple::x86 ||
1470                   getArch() == llvm::Triple::ppc);
1471
1472  std::string Suffix;
1473  std::string Lib;
1474
1475  if (Is32Bits) {
1476    Suffix = Suffix32;
1477    Lib = Lib32;
1478  } else {
1479    Suffix = Suffix64;
1480    Lib = Lib64;
1481  }
1482
1483  llvm::sys::Path LinkerPath(Base + "/../../../../" + GccTriple + "/bin/ld");
1484  if (!llvm::sys::fs::exists(LinkerPath.str(), Exists) && Exists)
1485    Linker = LinkerPath.str();
1486  else
1487    Linker = GetProgramPath("ld");
1488
1489  LinuxDistro Distro = DetectLinuxDistro(Arch);
1490
1491  if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
1492    ExtraOpts.push_back("-z");
1493    ExtraOpts.push_back("relro");
1494  }
1495
1496  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
1497    ExtraOpts.push_back("-X");
1498
1499  if (IsRedhat(Distro) || IsOpenSuse(Distro) || Distro == UbuntuMaverick ||
1500      Distro == UbuntuNatty)
1501    ExtraOpts.push_back("--hash-style=gnu");
1502
1503  if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
1504      Distro == UbuntuJaunty || Distro == UbuntuKarmic)
1505    ExtraOpts.push_back("--hash-style=both");
1506
1507  if (IsRedhat(Distro))
1508    ExtraOpts.push_back("--no-add-needed");
1509
1510  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
1511      IsOpenSuse(Distro) ||
1512      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
1513      Distro == UbuntuLucid ||
1514      Distro == UbuntuMaverick || Distro == UbuntuKarmic ||
1515      Distro == UbuntuNatty)
1516    ExtraOpts.push_back("--build-id");
1517
1518  if (IsOpenSuse(Distro))
1519    ExtraOpts.push_back("--enable-new-dtags");
1520
1521  if (Distro == ArchLinux)
1522    Lib = "lib";
1523
1524  Paths.push_back(Base + Suffix);
1525  if (HasMultilib(Arch, Distro)) {
1526    if (IsOpenSuse(Distro) && Is32Bits)
1527      Paths.push_back(Base + "/../../../../" + GccTriple + "/lib/../lib");
1528    Paths.push_back(Base + "/../../../../" + Lib);
1529  }
1530
1531  // FIXME: This is in here to find crt1.o. It is provided by libc, and
1532  // libc (like gcc), can be installed in any directory. Once we are
1533  // fetching this from a config file, we should have a libc prefix.
1534  Paths.push_back("/lib/../" + Lib);
1535  Paths.push_back("/usr/lib/../" + Lib);
1536
1537  if (!Suffix.empty())
1538    Paths.push_back(Base);
1539  if (IsOpenSuse(Distro))
1540    Paths.push_back(Base + "/../../../../" + GccTriple + "/lib");
1541  Paths.push_back(Base + "/../../..");
1542  if (Arch == getArch() && IsUbuntu(Distro))
1543    Paths.push_back("/usr/lib/" + GccTriple);
1544}
1545
1546bool Linux::HasNativeLLVMSupport() const {
1547  return true;
1548}
1549
1550Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
1551                        const ActionList &Inputs) const {
1552  Action::ActionClass Key;
1553  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1554    Key = Action::AnalyzeJobClass;
1555  else
1556    Key = JA.getKind();
1557
1558  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1559                                             options::OPT_no_integrated_as,
1560                                             IsIntegratedAssemblerDefault());
1561
1562  Tool *&T = Tools[Key];
1563  if (!T) {
1564    switch (Key) {
1565    case Action::AssembleJobClass:
1566      if (UseIntegratedAs)
1567        T = new tools::ClangAs(*this);
1568      else
1569        T = new tools::linuxtools::Assemble(*this);
1570      break;
1571    case Action::LinkJobClass:
1572      T = new tools::linuxtools::Link(*this); break;
1573    default:
1574      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1575    }
1576  }
1577
1578  return *T;
1579}
1580
1581/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
1582
1583DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
1584  : Generic_ELF(Host, Triple) {
1585
1586  // Path mangling to find libexec
1587  getProgramPaths().push_back(getDriver().getInstalledDir());
1588  if (getDriver().getInstalledDir() != getDriver().Dir)
1589    getProgramPaths().push_back(getDriver().Dir);
1590
1591  getFilePaths().push_back(getDriver().Dir + "/../lib");
1592  getFilePaths().push_back("/usr/lib");
1593  getFilePaths().push_back("/usr/lib/gcc41");
1594}
1595
1596Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
1597                            const ActionList &Inputs) const {
1598  Action::ActionClass Key;
1599  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1600    Key = Action::AnalyzeJobClass;
1601  else
1602    Key = JA.getKind();
1603
1604  Tool *&T = Tools[Key];
1605  if (!T) {
1606    switch (Key) {
1607    case Action::AssembleJobClass:
1608      T = new tools::dragonfly::Assemble(*this); break;
1609    case Action::LinkJobClass:
1610      T = new tools::dragonfly::Link(*this); break;
1611    default:
1612      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1613    }
1614  }
1615
1616  return *T;
1617}
1618
1619Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple)
1620  : ToolChain(Host, Triple) {
1621}
1622
1623Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA,
1624                          const ActionList &Inputs) const {
1625  Action::ActionClass Key;
1626  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1627    Key = Action::AnalyzeJobClass;
1628  else
1629    Key = JA.getKind();
1630
1631  Tool *&T = Tools[Key];
1632  if (!T) {
1633    switch (Key) {
1634    case Action::InputClass:
1635    case Action::BindArchClass:
1636    case Action::LipoJobClass:
1637    case Action::DsymutilJobClass:
1638      assert(0 && "Invalid tool kind.");
1639    case Action::PreprocessJobClass:
1640    case Action::PrecompileJobClass:
1641    case Action::AnalyzeJobClass:
1642    case Action::CompileJobClass:
1643      T = new tools::Clang(*this); break;
1644    case Action::AssembleJobClass:
1645      T = new tools::ClangAs(*this); break;
1646    case Action::LinkJobClass:
1647      T = new tools::visualstudio::Link(*this); break;
1648    }
1649  }
1650
1651  return *T;
1652}
1653
1654bool Windows::IsIntegratedAssemblerDefault() const {
1655  return true;
1656}
1657
1658bool Windows::IsUnwindTablesDefault() const {
1659  // FIXME: Gross; we should probably have some separate target
1660  // definition, possibly even reusing the one in clang.
1661  return getArchName() == "x86_64";
1662}
1663
1664const char *Windows::GetDefaultRelocationModel() const {
1665  return "static";
1666}
1667
1668const char *Windows::GetForcedPicModel() const {
1669  if (getArchName() == "x86_64")
1670    return "pic";
1671  return 0;
1672}
1673