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