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