ToolChains.cpp revision 89088797876bddb866ce821f050a4395b7514dc2
1//===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ToolChains.h"
11
12#ifdef HAVE_CLANG_CONFIG_H
13# include "clang/Config/config.h"
14#endif
15
16#include "clang/Driver/Arg.h"
17#include "clang/Driver/ArgList.h"
18#include "clang/Driver/Compilation.h"
19#include "clang/Driver/Driver.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/HostInfo.h"
22#include "clang/Driver/ObjCRuntime.h"
23#include "clang/Driver/OptTable.h"
24#include "clang/Driver/Option.h"
25#include "clang/Driver/Options.h"
26#include "clang/Basic/Version.h"
27
28#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/StringSwitch.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/raw_ostream.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/system_error.h"
38
39#include <cstdlib> // ::getenv
40
41#include "llvm/Config/config.h" // for CXX_INCLUDE_ROOT
42
43using namespace clang::driver;
44using namespace clang::driver::toolchains;
45using namespace clang;
46
47/// Darwin - Darwin tool chain for i386 and x86_64.
48
49Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple)
50  : ToolChain(Host, Triple), TargetInitialized(false),
51    ARCRuntimeForSimulator(ARCSimulator_None),
52    LibCXXForSimulator(LibCXXSimulator_None)
53{
54  // Compute the initial Darwin version based on the host.
55  bool HadExtra;
56  std::string OSName = Triple.getOSName();
57  if (!Driver::GetReleaseVersion(&OSName.c_str()[6],
58                                 DarwinVersion[0], DarwinVersion[1],
59                                 DarwinVersion[2], HadExtra))
60    getDriver().Diag(diag::err_drv_invalid_darwin_version) << OSName;
61
62  llvm::raw_string_ostream(MacosxVersionMin)
63    << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.'
64    << DarwinVersion[1];
65}
66
67types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
68  types::ID Ty = types::lookupTypeForExtension(Ext);
69
70  // Darwin always preprocesses assembly files (unless -x is used explicitly).
71  if (Ty == types::TY_PP_Asm)
72    return types::TY_Asm;
73
74  return Ty;
75}
76
77bool Darwin::HasNativeLLVMSupport() const {
78  return true;
79}
80
81bool Darwin::hasARCRuntime() const {
82  // FIXME: Remove this once there is a proper way to detect an ARC runtime
83  // for the simulator.
84  switch (ARCRuntimeForSimulator) {
85  case ARCSimulator_None:
86    break;
87  case ARCSimulator_HasARCRuntime:
88    return true;
89  case ARCSimulator_NoARCRuntime:
90    return false;
91  }
92
93  if (isTargetIPhoneOS())
94    return !isIPhoneOSVersionLT(5);
95  else
96    return !isMacosxVersionLT(10, 7);
97}
98
99/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
100void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const {
101  if (runtime.getKind() != ObjCRuntime::NeXT)
102    return ToolChain::configureObjCRuntime(runtime);
103
104  runtime.HasARC = runtime.HasWeak = hasARCRuntime();
105
106  // So far, objc_terminate is only available in iOS 5.
107  // FIXME: do the simulator logic properly.
108  if (!ARCRuntimeForSimulator && isTargetIPhoneOS())
109    runtime.HasTerminate = !isIPhoneOSVersionLT(5);
110  else
111    runtime.HasTerminate = false;
112}
113
114/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
115bool Darwin::hasBlocksRuntime() const {
116  if (isTargetIPhoneOS())
117    return !isIPhoneOSVersionLT(3, 2);
118  else
119    return !isMacosxVersionLT(10, 6);
120}
121
122static const char *GetArmArchForMArch(StringRef Value) {
123  return llvm::StringSwitch<const char*>(Value)
124    .Case("armv6k", "armv6")
125    .Case("armv5tej", "armv5")
126    .Case("xscale", "xscale")
127    .Case("armv4t", "armv4t")
128    .Case("armv7", "armv7")
129    .Cases("armv7a", "armv7-a", "armv7")
130    .Cases("armv7r", "armv7-r", "armv7")
131    .Cases("armv7m", "armv7-m", "armv7")
132    .Default(0);
133}
134
135static const char *GetArmArchForMCpu(StringRef Value) {
136  return llvm::StringSwitch<const char *>(Value)
137    .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
138    .Cases("arm10e", "arm10tdmi", "armv5")
139    .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
140    .Case("xscale", "xscale")
141    .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s",
142           "arm1176jzf-s", "cortex-m0", "armv6")
143    .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "armv7")
144    .Default(0);
145}
146
147StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
148  switch (getTriple().getArch()) {
149  default:
150    return getArchName();
151
152  case llvm::Triple::thumb:
153  case llvm::Triple::arm: {
154    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
155      if (const char *Arch = GetArmArchForMArch(A->getValue(Args)))
156        return Arch;
157
158    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
159      if (const char *Arch = GetArmArchForMCpu(A->getValue(Args)))
160        return Arch;
161
162    return "arm";
163  }
164  }
165}
166
167Darwin::~Darwin() {
168  // Free tool implementations.
169  for (llvm::DenseMap<unsigned, Tool*>::iterator
170         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
171    delete it->second;
172}
173
174std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
175                                                types::ID InputType) const {
176  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
177
178  // If the target isn't initialized (e.g., an unknown Darwin platform, return
179  // the default triple).
180  if (!isTargetInitialized())
181    return Triple.getTriple();
182
183  unsigned Version[3];
184  getTargetVersion(Version);
185
186  llvm::SmallString<16> Str;
187  llvm::raw_svector_ostream(Str)
188    << (isTargetIPhoneOS() ? "ios" : "macosx")
189    << Version[0] << "." << Version[1] << "." << Version[2];
190  Triple.setOSName(Str.str());
191
192  return Triple.getTriple();
193}
194
195void Generic_ELF::anchor() {}
196
197Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
198                         const ActionList &Inputs) const {
199  Action::ActionClass Key;
200
201  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
202    // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI.
203    if (Inputs.size() == 1 &&
204        types::isCXX(Inputs[0]->getType()) &&
205        getTriple().isOSDarwin() &&
206        getTriple().getArch() == llvm::Triple::x86 &&
207        (C.getArgs().getLastArg(options::OPT_fapple_kext) ||
208         C.getArgs().getLastArg(options::OPT_mkernel)))
209      Key = JA.getKind();
210    else
211      Key = Action::AnalyzeJobClass;
212  } else
213    Key = JA.getKind();
214
215  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
216                                             options::OPT_no_integrated_as,
217                                             IsIntegratedAssemblerDefault());
218
219  Tool *&T = Tools[Key];
220  if (!T) {
221    switch (Key) {
222    case Action::InputClass:
223    case Action::BindArchClass:
224      llvm_unreachable("Invalid tool kind.");
225    case Action::PreprocessJobClass:
226      T = new tools::darwin::Preprocess(*this); break;
227    case Action::AnalyzeJobClass:
228      T = new tools::Clang(*this); break;
229    case Action::PrecompileJobClass:
230    case Action::CompileJobClass:
231      T = new tools::darwin::Compile(*this); break;
232    case Action::AssembleJobClass: {
233      if (UseIntegratedAs)
234        T = new tools::ClangAs(*this);
235      else
236        T = new tools::darwin::Assemble(*this);
237      break;
238    }
239    case Action::LinkJobClass:
240      T = new tools::darwin::Link(*this); break;
241    case Action::LipoJobClass:
242      T = new tools::darwin::Lipo(*this); break;
243    case Action::DsymutilJobClass:
244      T = new tools::darwin::Dsymutil(*this); break;
245    case Action::VerifyJobClass:
246      T = new tools::darwin::VerifyDebug(*this); break;
247    }
248  }
249
250  return *T;
251}
252
253
254DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple)
255  : Darwin(Host, Triple)
256{
257  getProgramPaths().push_back(getDriver().getInstalledDir());
258  if (getDriver().getInstalledDir() != getDriver().Dir)
259    getProgramPaths().push_back(getDriver().Dir);
260
261  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
262  getProgramPaths().push_back(getDriver().getInstalledDir());
263  if (getDriver().getInstalledDir() != getDriver().Dir)
264    getProgramPaths().push_back(getDriver().Dir);
265
266  // For fallback, we need to know how to find the GCC cc1 executables, so we
267  // also add the GCC libexec paths. This is legacy code that can be removed
268  // once fallback is no longer useful.
269  AddGCCLibexecPath(DarwinVersion[0]);
270  AddGCCLibexecPath(DarwinVersion[0] - 2);
271  AddGCCLibexecPath(DarwinVersion[0] - 1);
272  AddGCCLibexecPath(DarwinVersion[0] + 1);
273  AddGCCLibexecPath(DarwinVersion[0] + 2);
274}
275
276void DarwinClang::AddGCCLibexecPath(unsigned darwinVersion) {
277  std::string ToolChainDir = "i686-apple-darwin";
278  ToolChainDir += llvm::utostr(darwinVersion);
279  ToolChainDir += "/4.2.1";
280
281  std::string Path = getDriver().Dir;
282  Path += "/../llvm-gcc-4.2/libexec/gcc/";
283  Path += ToolChainDir;
284  getProgramPaths().push_back(Path);
285
286  Path = "/usr/llvm-gcc-4.2/libexec/gcc/";
287  Path += ToolChainDir;
288  getProgramPaths().push_back(Path);
289}
290
291void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args,
292                                       ArgStringList &CmdArgs) const {
293  // The Clang toolchain uses explicit paths for internal libraries.
294
295  // Unfortunately, we still might depend on a few of the libraries that are
296  // only available in the gcc library directory (in particular
297  // libstdc++.dylib). For now, hardcode the path to the known install location.
298  // FIXME: This should get ripped out someday.  However, when building on
299  // 10.6 (darwin10), we're still relying on this to find libstdc++.dylib.
300  llvm::sys::Path P(getDriver().Dir);
301  P.eraseComponent(); // .../usr/bin -> ../usr
302  P.appendComponent("llvm-gcc-4.2");
303  P.appendComponent("lib");
304  P.appendComponent("gcc");
305  switch (getTriple().getArch()) {
306  default:
307    llvm_unreachable("Invalid Darwin arch!");
308  case llvm::Triple::x86:
309  case llvm::Triple::x86_64:
310    P.appendComponent("i686-apple-darwin10");
311    break;
312  case llvm::Triple::arm:
313  case llvm::Triple::thumb:
314    P.appendComponent("arm-apple-darwin10");
315    break;
316  case llvm::Triple::ppc:
317  case llvm::Triple::ppc64:
318    P.appendComponent("powerpc-apple-darwin10");
319    break;
320  }
321  P.appendComponent("4.2.1");
322
323  // Determine the arch specific GCC subdirectory.
324  const char *ArchSpecificDir = 0;
325  switch (getTriple().getArch()) {
326  default:
327    break;
328  case llvm::Triple::arm:
329  case llvm::Triple::thumb: {
330    std::string Triple = ComputeLLVMTriple(Args);
331    StringRef TripleStr = Triple;
332    if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5"))
333      ArchSpecificDir = "v5";
334    else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6"))
335      ArchSpecificDir = "v6";
336    else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7"))
337      ArchSpecificDir = "v7";
338    break;
339  }
340  case llvm::Triple::ppc64:
341    ArchSpecificDir = "ppc64";
342    break;
343  case llvm::Triple::x86_64:
344    ArchSpecificDir = "x86_64";
345    break;
346  }
347
348  if (ArchSpecificDir) {
349    P.appendComponent(ArchSpecificDir);
350    bool Exists;
351    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
352      CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
353    P.eraseComponent();
354  }
355
356  bool Exists;
357  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
358    CmdArgs.push_back(Args.MakeArgString("-L" + P.str()));
359}
360
361void DarwinClang::AddLinkARCArgs(const ArgList &Args,
362                                 ArgStringList &CmdArgs) const {
363
364  CmdArgs.push_back("-force_load");
365  llvm::sys::Path P(getDriver().ClangExecutable);
366  P.eraseComponent(); // 'clang'
367  P.eraseComponent(); // 'bin'
368  P.appendComponent("lib");
369  P.appendComponent("arc");
370  P.appendComponent("libarclite_");
371  std::string s = P.str();
372  // Mash in the platform.
373  if (isTargetIOSSimulator())
374    s += "iphonesimulator";
375  else if (isTargetIPhoneOS())
376    s += "iphoneos";
377  // FIXME: Remove this once we depend fully on -mios-simulator-version-min.
378  else if (ARCRuntimeForSimulator != ARCSimulator_None)
379    s += "iphonesimulator";
380  else
381    s += "macosx";
382  s += ".a";
383
384  CmdArgs.push_back(Args.MakeArgString(s));
385}
386
387void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
388                                    ArgStringList &CmdArgs,
389                                    const char *DarwinStaticLib) const {
390  llvm::sys::Path P(getDriver().ResourceDir);
391  P.appendComponent("lib");
392  P.appendComponent("darwin");
393  P.appendComponent(DarwinStaticLib);
394
395  // For now, allow missing resource libraries to support developers who may
396  // not have compiler-rt checked out or integrated into their build.
397  bool Exists;
398  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
399    CmdArgs.push_back(Args.MakeArgString(P.str()));
400}
401
402void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
403                                        ArgStringList &CmdArgs) const {
404  // Darwin only supports the compiler-rt based runtime libraries.
405  switch (GetRuntimeLibType(Args)) {
406  case ToolChain::RLT_CompilerRT:
407    break;
408  default:
409    getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
410      << Args.getLastArg(options::OPT_rtlib_EQ)->getValue(Args) << "darwin";
411    return;
412  }
413
414  // Darwin doesn't support real static executables, don't link any runtime
415  // libraries with -static.
416  if (Args.hasArg(options::OPT_static))
417    return;
418
419  // Reject -static-libgcc for now, we can deal with this when and if someone
420  // cares. This is useful in situations where someone wants to statically link
421  // something like libstdc++, and needs its runtime support routines.
422  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
423    getDriver().Diag(diag::err_drv_unsupported_opt)
424      << A->getAsString(Args);
425    return;
426  }
427
428  // If we are building profile support, link that library in.
429  if (Args.hasArg(options::OPT_fprofile_arcs) ||
430      Args.hasArg(options::OPT_fprofile_generate) ||
431      Args.hasArg(options::OPT_fcreate_profile) ||
432      Args.hasArg(options::OPT_coverage)) {
433    // Select the appropriate runtime library for the target.
434    if (isTargetIPhoneOS()) {
435      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
436    } else {
437      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
438    }
439  }
440
441  // Add ASAN runtime library, if required. Dynamic libraries and bundles
442  // should not be linked with the runtime library.
443  if (Args.hasFlag(options::OPT_faddress_sanitizer,
444                   options::OPT_fno_address_sanitizer, false)) {
445    if (Args.hasArg(options::OPT_dynamiclib) ||
446        Args.hasArg(options::OPT_bundle)) return;
447    if (isTargetIPhoneOS()) {
448      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
449        << "-faddress-sanitizer";
450    } else {
451      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a");
452
453      // The ASAN runtime library requires C++ and CoreFoundation.
454      AddCXXStdlibLibArgs(Args, CmdArgs);
455      CmdArgs.push_back("-framework");
456      CmdArgs.push_back("CoreFoundation");
457    }
458  }
459
460  // Otherwise link libSystem, then the dynamic runtime library, and finally any
461  // target specific static runtime library.
462  CmdArgs.push_back("-lSystem");
463
464  // Select the dynamic runtime library and the target specific static library.
465  if (isTargetIPhoneOS()) {
466    // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
467    // it never went into the SDK.
468    // Linking against libgcc_s.1 isn't needed for iOS 5.0+
469    if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
470      CmdArgs.push_back("-lgcc_s.1");
471
472    // We currently always need a static runtime library for iOS.
473    AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
474  } else {
475    // The dynamic runtime library was merged with libSystem for 10.6 and
476    // beyond; only 10.4 and 10.5 need an additional runtime library.
477    if (isMacosxVersionLT(10, 5))
478      CmdArgs.push_back("-lgcc_s.10.4");
479    else if (isMacosxVersionLT(10, 6))
480      CmdArgs.push_back("-lgcc_s.10.5");
481
482    // For OS X, we thought we would only need a static runtime library when
483    // targeting 10.4, to provide versions of the static functions which were
484    // omitted from 10.4.dylib.
485    //
486    // Unfortunately, that turned out to not be true, because Darwin system
487    // headers can still use eprintf on i386, and it is not exported from
488    // libSystem. Therefore, we still must provide a runtime library just for
489    // the tiny tiny handful of projects that *might* use that symbol.
490    if (isMacosxVersionLT(10, 5)) {
491      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
492    } else {
493      if (getTriple().getArch() == llvm::Triple::x86)
494        AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
495      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
496    }
497  }
498}
499
500static inline StringRef SimulatorVersionDefineName() {
501  return "__IPHONE_OS_VERSION_MIN_REQUIRED";
502}
503
504/// \brief Parse the simulator version define:
505/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
506// and return the grouped values as integers, e.g:
507//   __IPHONE_OS_VERSION_MIN_REQUIRED=40201
508// will return Major=4, Minor=2, Micro=1.
509static bool GetVersionFromSimulatorDefine(StringRef define,
510                                          unsigned &Major, unsigned &Minor,
511                                          unsigned &Micro) {
512  assert(define.startswith(SimulatorVersionDefineName()));
513  StringRef name, version;
514  llvm::tie(name, version) = define.split('=');
515  if (version.empty())
516    return false;
517  std::string verstr = version.str();
518  char *end;
519  unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
520  if (*end != '\0')
521    return false;
522  Major = num / 10000;
523  num = num % 10000;
524  Minor = num / 100;
525  Micro = num % 100;
526  return true;
527}
528
529void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
530  const OptTable &Opts = getDriver().getOpts();
531
532  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
533  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
534  Arg *iOSSimVersion = Args.getLastArg(
535    options::OPT_mios_simulator_version_min_EQ);
536
537  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
538    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
539          << OSXVersion->getAsString(Args)
540          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
541    iOSVersion = iOSSimVersion = 0;
542  } else if (iOSVersion && iOSSimVersion) {
543    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
544          << iOSVersion->getAsString(Args)
545          << iOSSimVersion->getAsString(Args);
546    iOSSimVersion = 0;
547  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
548    // If no deployment target was specified on the command line, check for
549    // environment defines.
550    StringRef OSXTarget;
551    StringRef iOSTarget;
552    StringRef iOSSimTarget;
553    if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
554      OSXTarget = env;
555    if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
556      iOSTarget = env;
557    if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
558      iOSSimTarget = env;
559
560    // If no '-miphoneos-version-min' specified on the command line and
561    // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
562    // based on isysroot.
563    if (iOSTarget.empty()) {
564      if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
565        StringRef first, second;
566        StringRef isysroot = A->getValue(Args);
567        llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
568        if (second != "")
569          iOSTarget = second.substr(0,3);
570      }
571    }
572
573    // If no OSX or iOS target has been specified and we're compiling for armv7,
574    // go ahead as assume we're targeting iOS.
575    if (OSXTarget.empty() && iOSTarget.empty())
576      if (getDarwinArchName(Args) == "armv7")
577        iOSTarget = "0.0";
578
579    // Handle conflicting deployment targets
580    //
581    // FIXME: Don't hardcode default here.
582
583    // Do not allow conflicts with the iOS simulator target.
584    if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
585      getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
586        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
587        << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
588            "IPHONEOS_DEPLOYMENT_TARGET");
589    }
590
591    // Allow conflicts among OSX and iOS for historical reasons, but choose the
592    // default platform.
593    if (!OSXTarget.empty() && !iOSTarget.empty()) {
594      if (getTriple().getArch() == llvm::Triple::arm ||
595          getTriple().getArch() == llvm::Triple::thumb)
596        OSXTarget = "";
597      else
598        iOSTarget = "";
599    }
600
601    if (!OSXTarget.empty()) {
602      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
603      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
604      Args.append(OSXVersion);
605    } else if (!iOSTarget.empty()) {
606      const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
607      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
608      Args.append(iOSVersion);
609    } else if (!iOSSimTarget.empty()) {
610      const Option *O = Opts.getOption(
611        options::OPT_mios_simulator_version_min_EQ);
612      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
613      Args.append(iOSSimVersion);
614    } else {
615      // Otherwise, assume we are targeting OS X.
616      const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
617      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
618      Args.append(OSXVersion);
619    }
620  }
621
622  // FIXME: HACK! When compiling for the simulator we can't depend
623  // on getting '-mios-simulator-version-min'; try to parse a
624  // __IPHONE_OS_VERSION_MIN_REQUIRED define passed in command-line.
625  if (OSXVersion) {
626    for (arg_iterator it = Args.filtered_begin(options::OPT_D),
627           ie = Args.filtered_end(); it != ie; ++it) {
628      StringRef define = (*it)->getValue(Args);
629      if (define.startswith(SimulatorVersionDefineName())) {
630        unsigned Major = 0, Minor = 0, Micro = 0;
631        if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
632            Major < 10 && Minor < 100 && Micro < 100) {
633          std::string iOSSimTarget;
634          llvm::raw_string_ostream(iOSSimTarget)
635              << Major << '.' << Minor << '.' << Micro;
636          const Option *O = Opts.getOption(
637            options::OPT_mios_simulator_version_min_EQ);
638          iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
639          Args.append(iOSSimVersion);
640          OSXVersion = 0;
641        }
642        break;
643      }
644    }
645  }
646
647  // Reject invalid architecture combinations.
648  if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
649                        getTriple().getArch() != llvm::Triple::x86_64)) {
650    getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
651      << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
652  }
653
654  // Set the tool chain target information.
655  unsigned Major, Minor, Micro;
656  bool HadExtra;
657  if (OSXVersion) {
658    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
659    if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor,
660                                   Micro, HadExtra) || HadExtra ||
661        Major != 10 || Minor >= 100 || Micro >= 100)
662      getDriver().Diag(diag::err_drv_invalid_version_number)
663        << OSXVersion->getAsString(Args);
664  } else {
665    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
666    assert(Version && "Unknown target platform!");
667    if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor,
668                                   Micro, HadExtra) || HadExtra ||
669        Major >= 10 || Minor >= 100 || Micro >= 100)
670      getDriver().Diag(diag::err_drv_invalid_version_number)
671        << Version->getAsString(Args);
672  }
673
674  bool IsIOSSim = bool(iOSSimVersion);
675
676  // In GCC, the simulator historically was treated as being OS X in some
677  // contexts, like determining the link logic, despite generally being called
678  // with an iOS deployment target. For compatibility, we detect the
679  // simulator as iOS + x86, and treat it differently in a few contexts.
680  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
681                     getTriple().getArch() == llvm::Triple::x86_64))
682    IsIOSSim = true;
683
684  setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
685}
686
687void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
688                                      ArgStringList &CmdArgs) const {
689  CXXStdlibType Type = GetCXXStdlibType(Args);
690
691  switch (Type) {
692  case ToolChain::CST_Libcxx:
693    CmdArgs.push_back("-lc++");
694    break;
695
696  case ToolChain::CST_Libstdcxx: {
697    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
698    // it was previously found in the gcc lib dir. However, for all the Darwin
699    // platforms we care about it was -lstdc++.6, so we search for that
700    // explicitly if we can't see an obvious -lstdc++ candidate.
701
702    // Check in the sysroot first.
703    bool Exists;
704    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
705      llvm::sys::Path P(A->getValue(Args));
706      P.appendComponent("usr");
707      P.appendComponent("lib");
708      P.appendComponent("libstdc++.dylib");
709
710      if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
711        P.eraseComponent();
712        P.appendComponent("libstdc++.6.dylib");
713        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
714          CmdArgs.push_back(Args.MakeArgString(P.str()));
715          return;
716        }
717      }
718    }
719
720    // Otherwise, look in the root.
721    // FIXME: This should be removed someday when we don't have to care about
722    // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
723    if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
724      (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
725      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
726      return;
727    }
728
729    // Otherwise, let the linker search.
730    CmdArgs.push_back("-lstdc++");
731    break;
732  }
733  }
734}
735
736void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
737                                   ArgStringList &CmdArgs) const {
738
739  // For Darwin platforms, use the compiler-rt-based support library
740  // instead of the gcc-provided one (which is also incidentally
741  // only present in the gcc lib dir, which makes it hard to find).
742
743  llvm::sys::Path P(getDriver().ResourceDir);
744  P.appendComponent("lib");
745  P.appendComponent("darwin");
746  P.appendComponent("libclang_rt.cc_kext.a");
747
748  // For now, allow missing resource libraries to support developers who may
749  // not have compiler-rt checked out or integrated into their build.
750  bool Exists;
751  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
752    CmdArgs.push_back(Args.MakeArgString(P.str()));
753}
754
755DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
756                                      const char *BoundArch) const {
757  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
758  const OptTable &Opts = getDriver().getOpts();
759
760  // FIXME: We really want to get out of the tool chain level argument
761  // translation business, as it makes the driver functionality much
762  // more opaque. For now, we follow gcc closely solely for the
763  // purpose of easily achieving feature parity & testability. Once we
764  // have something that works, we should reevaluate each translation
765  // and try to push it down into tool specific logic.
766
767  for (ArgList::const_iterator it = Args.begin(),
768         ie = Args.end(); it != ie; ++it) {
769    Arg *A = *it;
770
771    if (A->getOption().matches(options::OPT_Xarch__)) {
772      // Skip this argument unless the architecture matches either the toolchain
773      // triple arch, or the arch being bound.
774      //
775      // FIXME: Canonicalize name.
776      StringRef XarchArch = A->getValue(Args, 0);
777      if (!(XarchArch == getArchName()  ||
778            (BoundArch && XarchArch == BoundArch)))
779        continue;
780
781      Arg *OriginalArg = A;
782      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1));
783      unsigned Prev = Index;
784      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
785
786      // If the argument parsing failed or more than one argument was
787      // consumed, the -Xarch_ argument's parameter tried to consume
788      // extra arguments. Emit an error and ignore.
789      //
790      // We also want to disallow any options which would alter the
791      // driver behavior; that isn't going to work in our model. We
792      // use isDriverOption() as an approximation, although things
793      // like -O4 are going to slip through.
794      if (!XarchArg || Index > Prev + 1) {
795        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
796          << A->getAsString(Args);
797        continue;
798      } else if (XarchArg->getOption().isDriverOption()) {
799        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
800          << A->getAsString(Args);
801        continue;
802      }
803
804      XarchArg->setBaseArg(A);
805      A = XarchArg;
806
807      DAL->AddSynthesizedArg(A);
808
809      // Linker input arguments require custom handling. The problem is that we
810      // have already constructed the phase actions, so we can not treat them as
811      // "input arguments".
812      if (A->getOption().isLinkerInput()) {
813        // Convert the argument into individual Zlinker_input_args.
814        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
815          DAL->AddSeparateArg(OriginalArg,
816                              Opts.getOption(options::OPT_Zlinker_input),
817                              A->getValue(Args, i));
818
819        }
820        continue;
821      }
822    }
823
824    // Sob. These is strictly gcc compatible for the time being. Apple
825    // gcc translates options twice, which means that self-expanding
826    // options add duplicates.
827    switch ((options::ID) A->getOption().getID()) {
828    default:
829      DAL->append(A);
830      break;
831
832    case options::OPT_mkernel:
833    case options::OPT_fapple_kext:
834      DAL->append(A);
835      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
836      break;
837
838    case options::OPT_dependency_file:
839      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
840                          A->getValue(Args));
841      break;
842
843    case options::OPT_gfull:
844      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
845      DAL->AddFlagArg(A,
846               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
847      break;
848
849    case options::OPT_gused:
850      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
851      DAL->AddFlagArg(A,
852             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
853      break;
854
855    case options::OPT_shared:
856      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
857      break;
858
859    case options::OPT_fconstant_cfstrings:
860      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
861      break;
862
863    case options::OPT_fno_constant_cfstrings:
864      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
865      break;
866
867    case options::OPT_Wnonportable_cfstrings:
868      DAL->AddFlagArg(A,
869                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
870      break;
871
872    case options::OPT_Wno_nonportable_cfstrings:
873      DAL->AddFlagArg(A,
874                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
875      break;
876
877    case options::OPT_fpascal_strings:
878      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
879      break;
880
881    case options::OPT_fno_pascal_strings:
882      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
883      break;
884    }
885  }
886
887  if (getTriple().getArch() == llvm::Triple::x86 ||
888      getTriple().getArch() == llvm::Triple::x86_64)
889    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
890      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
891
892  // Add the arch options based on the particular spelling of -arch, to match
893  // how the driver driver works.
894  if (BoundArch) {
895    StringRef Name = BoundArch;
896    const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ);
897    const Option *MArch = Opts.getOption(options::OPT_march_EQ);
898
899    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
900    // which defines the list of which architectures we accept.
901    if (Name == "ppc")
902      ;
903    else if (Name == "ppc601")
904      DAL->AddJoinedArg(0, MCpu, "601");
905    else if (Name == "ppc603")
906      DAL->AddJoinedArg(0, MCpu, "603");
907    else if (Name == "ppc604")
908      DAL->AddJoinedArg(0, MCpu, "604");
909    else if (Name == "ppc604e")
910      DAL->AddJoinedArg(0, MCpu, "604e");
911    else if (Name == "ppc750")
912      DAL->AddJoinedArg(0, MCpu, "750");
913    else if (Name == "ppc7400")
914      DAL->AddJoinedArg(0, MCpu, "7400");
915    else if (Name == "ppc7450")
916      DAL->AddJoinedArg(0, MCpu, "7450");
917    else if (Name == "ppc970")
918      DAL->AddJoinedArg(0, MCpu, "970");
919
920    else if (Name == "ppc64")
921      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
922
923    else if (Name == "i386")
924      ;
925    else if (Name == "i486")
926      DAL->AddJoinedArg(0, MArch, "i486");
927    else if (Name == "i586")
928      DAL->AddJoinedArg(0, MArch, "i586");
929    else if (Name == "i686")
930      DAL->AddJoinedArg(0, MArch, "i686");
931    else if (Name == "pentium")
932      DAL->AddJoinedArg(0, MArch, "pentium");
933    else if (Name == "pentium2")
934      DAL->AddJoinedArg(0, MArch, "pentium2");
935    else if (Name == "pentpro")
936      DAL->AddJoinedArg(0, MArch, "pentiumpro");
937    else if (Name == "pentIIm3")
938      DAL->AddJoinedArg(0, MArch, "pentium2");
939
940    else if (Name == "x86_64")
941      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
942
943    else if (Name == "arm")
944      DAL->AddJoinedArg(0, MArch, "armv4t");
945    else if (Name == "armv4t")
946      DAL->AddJoinedArg(0, MArch, "armv4t");
947    else if (Name == "armv5")
948      DAL->AddJoinedArg(0, MArch, "armv5tej");
949    else if (Name == "xscale")
950      DAL->AddJoinedArg(0, MArch, "xscale");
951    else if (Name == "armv6")
952      DAL->AddJoinedArg(0, MArch, "armv6k");
953    else if (Name == "armv7")
954      DAL->AddJoinedArg(0, MArch, "armv7a");
955
956    else
957      llvm_unreachable("invalid Darwin arch");
958  }
959
960  // Add an explicit version min argument for the deployment target. We do this
961  // after argument translation because -Xarch_ arguments may add a version min
962  // argument.
963  AddDeploymentTarget(*DAL);
964
965  // Validate the C++ standard library choice.
966  CXXStdlibType Type = GetCXXStdlibType(*DAL);
967  if (Type == ToolChain::CST_Libcxx) {
968    switch (LibCXXForSimulator) {
969    case LibCXXSimulator_None:
970      // Handle non-simulator cases.
971      if (isTargetIPhoneOS()) {
972        if (isIPhoneOSVersionLT(5, 0)) {
973          getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
974            << "iOS 5.0";
975        }
976      }
977      break;
978    case LibCXXSimulator_NotAvailable:
979      getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
980        << "iOS 5.0";
981      break;
982    case LibCXXSimulator_Available:
983      break;
984    }
985  }
986
987  return DAL;
988}
989
990bool Darwin::IsUnwindTablesDefault() const {
991  // FIXME: Gross; we should probably have some separate target
992  // definition, possibly even reusing the one in clang.
993  return getArchName() == "x86_64";
994}
995
996bool Darwin::UseDwarfDebugFlags() const {
997  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
998    return S[0] != '\0';
999  return false;
1000}
1001
1002bool Darwin::UseSjLjExceptions() const {
1003  // Darwin uses SjLj exceptions on ARM.
1004  return (getTriple().getArch() == llvm::Triple::arm ||
1005          getTriple().getArch() == llvm::Triple::thumb);
1006}
1007
1008const char *Darwin::GetDefaultRelocationModel() const {
1009  return "pic";
1010}
1011
1012const char *Darwin::GetForcedPicModel() const {
1013  if (getArchName() == "x86_64")
1014    return "pic";
1015  return 0;
1016}
1017
1018bool Darwin::SupportsProfiling() const {
1019  // Profiling instrumentation is only supported on x86.
1020  return getArchName() == "i386" || getArchName() == "x86_64";
1021}
1022
1023bool Darwin::SupportsObjCGC() const {
1024  // Garbage collection is supported everywhere except on iPhone OS.
1025  return !isTargetIPhoneOS();
1026}
1027
1028std::string
1029Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
1030                                                types::ID InputType) const {
1031  return ComputeLLVMTriple(Args, InputType);
1032}
1033
1034/// Generic_GCC - A tool chain using the 'gcc' command to perform
1035/// all subcommands; this relies on gcc translating the majority of
1036/// command line options.
1037
1038/// \brief Parse a GCCVersion object out of a string of text.
1039///
1040/// This is the primary means of forming GCCVersion objects.
1041/*static*/
1042Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1043  const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
1044  std::pair<StringRef, StringRef> First = VersionText.split('.');
1045  std::pair<StringRef, StringRef> Second = First.second.split('.');
1046
1047  GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
1048  if (First.first.getAsInteger(10, GoodVersion.Major) ||
1049      GoodVersion.Major < 0)
1050    return BadVersion;
1051  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
1052      GoodVersion.Minor < 0)
1053    return BadVersion;
1054
1055  // First look for a number prefix and parse that if present. Otherwise just
1056  // stash the entire patch string in the suffix, and leave the number
1057  // unspecified. This covers versions strings such as:
1058  //   4.4
1059  //   4.4.0
1060  //   4.4.x
1061  //   4.4.2-rc4
1062  //   4.4.x-patched
1063  // And retains any patch number it finds.
1064  StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1065  if (!PatchText.empty()) {
1066    if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) {
1067      // Try to parse the number and any suffix.
1068      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1069          GoodVersion.Patch < 0)
1070        return BadVersion;
1071      GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
1072    }
1073  }
1074
1075  return GoodVersion;
1076}
1077
1078/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1079bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
1080  if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
1081  if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
1082
1083  // Note that we rank versions with *no* patch specified is better than ones
1084  // hard-coding a patch version. Thus if the RHS has no patch, it always
1085  // wins, and the LHS only wins if it has no patch and the RHS does have
1086  // a patch.
1087  if (RHS.Patch == -1) return true;   if (Patch == -1) return false;
1088  if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
1089
1090  // Finally, between completely tied version numbers, the version with the
1091  // suffix loses as we prefer full releases.
1092  if (RHS.PatchSuffix.empty()) return true;
1093  return false;
1094}
1095
1096/// \brief Construct a GCCInstallationDetector from the driver.
1097///
1098/// This performs all of the autodetection and sets up the various paths.
1099/// Once constructed, a GCCInstallation is esentially immutable.
1100Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(const Driver &D)
1101  : IsValid(false),
1102    // FIXME: GCCTriple is using the target triple as both the target and host
1103    // triple here.
1104    GCCTriple(D.TargetTriple) {
1105  // FIXME: Using CXX_INCLUDE_ROOT is here is a bit of a hack, but
1106  // avoids adding yet another option to configure/cmake.
1107  // It would probably be cleaner to break it in two variables
1108  // CXX_GCC_ROOT with just /foo/bar
1109  // CXX_GCC_VER with 4.5.2
1110  // Then we would have
1111  // CXX_INCLUDE_ROOT = CXX_GCC_ROOT/include/c++/CXX_GCC_VER
1112  // and this function would return
1113  // CXX_GCC_ROOT/lib/gcc/CXX_INCLUDE_ARCH/CXX_GCC_VER
1114  llvm::SmallString<128> CxxIncludeRoot(CXX_INCLUDE_ROOT);
1115  if (CxxIncludeRoot != "") {
1116    // This is of the form /foo/bar/include/c++/4.5.2/
1117    if (CxxIncludeRoot.back() == '/')
1118      llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the /
1119    StringRef Version = llvm::sys::path::filename(CxxIncludeRoot);
1120    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the version
1121    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the c++
1122    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the include
1123    GCCInstallPath = CxxIncludeRoot.str();
1124    GCCInstallPath.append("/lib/gcc/");
1125    GCCInstallPath.append(CXX_INCLUDE_ARCH);
1126    GCCInstallPath.append("/");
1127    GCCInstallPath.append(Version);
1128    GCCParentLibPath = GCCInstallPath + "/../../..";
1129    IsValid = true;
1130    return;
1131  }
1132
1133  llvm::Triple::ArchType HostArch = GCCTriple.getArch();
1134  // The library directories which may contain GCC installations.
1135  SmallVector<StringRef, 4> CandidateLibDirs;
1136  // The compatible GCC triples for this particular architecture.
1137  SmallVector<StringRef, 10> CandidateTriples;
1138  CollectLibDirsAndTriples(HostArch, CandidateLibDirs, CandidateTriples);
1139
1140  // Always include the default host triple as the final fallback if no
1141  // specific triple is detected.
1142  // FIXME: This is using the Driver's target triple as the host triple!
1143  CandidateTriples.push_back(D.TargetTriple.str());
1144
1145  // Compute the set of prefixes for our search.
1146  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1147                                       D.PrefixDirs.end());
1148  Prefixes.push_back(D.SysRoot);
1149  Prefixes.push_back(D.SysRoot + "/usr");
1150  Prefixes.push_back(D.InstalledDir + "/..");
1151
1152  // Loop over the various components which exist and select the best GCC
1153  // installation available. GCC installs are ranked by version number.
1154  Version = GCCVersion::Parse("0.0.0");
1155  for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1156    if (!llvm::sys::fs::exists(Prefixes[i]))
1157      continue;
1158    for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1159      const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1160      if (!llvm::sys::fs::exists(LibDir))
1161        continue;
1162      for (unsigned k = 0, ke = CandidateTriples.size(); k < ke; ++k)
1163        ScanLibDirForGCCTriple(HostArch, LibDir, CandidateTriples[k]);
1164    }
1165  }
1166}
1167
1168/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1169    llvm::Triple::ArchType HostArch, SmallVectorImpl<StringRef> &LibDirs,
1170    SmallVectorImpl<StringRef> &Triples) {
1171  if (HostArch == llvm::Triple::arm || HostArch == llvm::Triple::thumb) {
1172    static const char *const ARMLibDirs[] = { "/lib" };
1173    static const char *const ARMTriples[] = {
1174      "arm-linux-gnueabi",
1175      "arm-linux-androideabi"
1176    };
1177    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1178    Triples.append(ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1179  } else if (HostArch == llvm::Triple::x86_64) {
1180    static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1181    static const char *const X86_64Triples[] = {
1182      "x86_64-linux-gnu",
1183      "x86_64-unknown-linux-gnu",
1184      "x86_64-pc-linux-gnu",
1185      "x86_64-redhat-linux6E",
1186      "x86_64-redhat-linux",
1187      "x86_64-suse-linux",
1188      "x86_64-manbo-linux-gnu",
1189      "x86_64-linux-gnu",
1190      "x86_64-slackware-linux"
1191    };
1192    LibDirs.append(X86_64LibDirs,
1193                   X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1194    Triples.append(X86_64Triples,
1195                   X86_64Triples + llvm::array_lengthof(X86_64Triples));
1196  } else if (HostArch == llvm::Triple::x86) {
1197    static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1198    static const char *const X86Triples[] = {
1199      "i686-linux-gnu",
1200      "i686-pc-linux-gnu",
1201      "i486-linux-gnu",
1202      "i386-linux-gnu",
1203      "i686-redhat-linux",
1204      "i586-redhat-linux",
1205      "i386-redhat-linux",
1206      "i586-suse-linux",
1207      "i486-slackware-linux"
1208    };
1209    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1210    Triples.append(X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1211  } else if (HostArch == llvm::Triple::mips) {
1212    static const char *const MIPSLibDirs[] = { "/lib" };
1213    static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1214    LibDirs.append(MIPSLibDirs,
1215                   MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1216    Triples.append(MIPSTriples,
1217                   MIPSTriples + llvm::array_lengthof(MIPSTriples));
1218  } else if (HostArch == llvm::Triple::mipsel) {
1219    static const char *const MIPSELLibDirs[] = { "/lib" };
1220    static const char *const MIPSELTriples[] = { "mipsel-linux-gnu" };
1221    LibDirs.append(MIPSELLibDirs,
1222                   MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1223    Triples.append(MIPSELTriples,
1224                   MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1225  } else if (HostArch == llvm::Triple::ppc) {
1226    static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1227    static const char *const PPCTriples[] = {
1228      "powerpc-linux-gnu",
1229      "powerpc-unknown-linux-gnu",
1230      "powerpc-suse-linux"
1231    };
1232    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1233    Triples.append(PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1234  } else if (HostArch == llvm::Triple::ppc64) {
1235    static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1236    static const char *const PPC64Triples[] = {
1237      "powerpc64-unknown-linux-gnu",
1238      "powerpc64-suse-linux",
1239      "ppc64-redhat-linux"
1240    };
1241    LibDirs.append(PPC64LibDirs,
1242                   PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1243    Triples.append(PPC64Triples,
1244                   PPC64Triples + llvm::array_lengthof(PPC64Triples));
1245  }
1246}
1247
1248void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1249    llvm::Triple::ArchType HostArch, const std::string &LibDir,
1250    StringRef CandidateTriple) {
1251  // There are various different suffixes involving the triple we
1252  // check for. We also record what is necessary to walk from each back
1253  // up to the lib directory.
1254  const std::string Suffixes[] = {
1255    "/gcc/" + CandidateTriple.str(),
1256    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1257
1258    // Ubuntu has a strange mis-matched pair of triples that this happens to
1259    // match.
1260    // FIXME: It may be worthwhile to generalize this and look for a second
1261    // triple.
1262    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1263  };
1264  const std::string InstallSuffixes[] = {
1265    "/../../..",
1266    "/../../../..",
1267    "/../../../.."
1268  };
1269  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1270  const unsigned NumSuffixes = (llvm::array_lengthof(Suffixes) -
1271                                (HostArch != llvm::Triple::x86));
1272  for (unsigned i = 0; i < NumSuffixes; ++i) {
1273    StringRef Suffix = Suffixes[i];
1274    llvm::error_code EC;
1275    for (llvm::sys::fs::directory_iterator LI(LibDir + Suffix, EC), LE;
1276         !EC && LI != LE; LI = LI.increment(EC)) {
1277      StringRef VersionText = llvm::sys::path::filename(LI->path());
1278      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1279      static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1280      if (CandidateVersion < MinVersion)
1281        continue;
1282      if (CandidateVersion <= Version)
1283        continue;
1284
1285      // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1286      // in what would normally be GCCInstallPath and put the 64-bit
1287      // libs in a subdirectory named 64. We need the 64-bit libs
1288      // for linking.
1289      bool UseSlash64 = false;
1290      if (HostArch == llvm::Triple::ppc64 &&
1291            llvm::sys::fs::exists(LI->path() + "/64/crtbegin.o"))
1292        UseSlash64 = true;
1293
1294      if (!llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1295        continue;
1296
1297      Version = CandidateVersion;
1298      GCCTriple.setTriple(CandidateTriple);
1299      // FIXME: We hack together the directory name here instead of
1300      // using LI to ensure stable path separators across Windows and
1301      // Linux.
1302      GCCInstallPath = LibDir + Suffixes[i] + "/" + VersionText.str();
1303      GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1304      if (UseSlash64) GCCInstallPath = GCCInstallPath + "/64";
1305      IsValid = true;
1306    }
1307  }
1308}
1309
1310Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
1311  : ToolChain(Host, Triple), GCCInstallation(getDriver()) {
1312  getProgramPaths().push_back(getDriver().getInstalledDir());
1313  if (getDriver().getInstalledDir() != getDriver().Dir)
1314    getProgramPaths().push_back(getDriver().Dir);
1315}
1316
1317Generic_GCC::~Generic_GCC() {
1318  // Free tool implementations.
1319  for (llvm::DenseMap<unsigned, Tool*>::iterator
1320         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1321    delete it->second;
1322}
1323
1324Tool &Generic_GCC::SelectTool(const Compilation &C,
1325                              const JobAction &JA,
1326                              const ActionList &Inputs) const {
1327  Action::ActionClass Key;
1328  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1329    Key = Action::AnalyzeJobClass;
1330  else
1331    Key = JA.getKind();
1332
1333  Tool *&T = Tools[Key];
1334  if (!T) {
1335    switch (Key) {
1336    case Action::InputClass:
1337    case Action::BindArchClass:
1338      llvm_unreachable("Invalid tool kind.");
1339    case Action::PreprocessJobClass:
1340      T = new tools::gcc::Preprocess(*this); break;
1341    case Action::PrecompileJobClass:
1342      T = new tools::gcc::Precompile(*this); break;
1343    case Action::AnalyzeJobClass:
1344      T = new tools::Clang(*this); break;
1345    case Action::CompileJobClass:
1346      T = new tools::gcc::Compile(*this); break;
1347    case Action::AssembleJobClass:
1348      T = new tools::gcc::Assemble(*this); break;
1349    case Action::LinkJobClass:
1350      T = new tools::gcc::Link(*this); break;
1351
1352      // This is a bit ungeneric, but the only platform using a driver
1353      // driver is Darwin.
1354    case Action::LipoJobClass:
1355      T = new tools::darwin::Lipo(*this); break;
1356    case Action::DsymutilJobClass:
1357      T = new tools::darwin::Dsymutil(*this); break;
1358    case Action::VerifyJobClass:
1359      T = new tools::darwin::VerifyDebug(*this); break;
1360    }
1361  }
1362
1363  return *T;
1364}
1365
1366bool Generic_GCC::IsUnwindTablesDefault() const {
1367  // FIXME: Gross; we should probably have some separate target
1368  // definition, possibly even reusing the one in clang.
1369  return getArchName() == "x86_64";
1370}
1371
1372const char *Generic_GCC::GetDefaultRelocationModel() const {
1373  return "static";
1374}
1375
1376const char *Generic_GCC::GetForcedPicModel() const {
1377  return 0;
1378}
1379/// Hexagon Toolchain
1380
1381Hexagon_TC::Hexagon_TC(const HostInfo &Host, const llvm::Triple& Triple)
1382  : ToolChain(Host, Triple) {
1383  getProgramPaths().push_back(getDriver().getInstalledDir());
1384  if (getDriver().getInstalledDir() != getDriver().Dir.c_str())
1385    getProgramPaths().push_back(getDriver().Dir);
1386}
1387
1388Hexagon_TC::~Hexagon_TC() {
1389  // Free tool implementations.
1390  for (llvm::DenseMap<unsigned, Tool*>::iterator
1391         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1392    delete it->second;
1393}
1394
1395Tool &Hexagon_TC::SelectTool(const Compilation &C,
1396                             const JobAction &JA,
1397                             const ActionList &Inputs) const {
1398  Action::ActionClass Key;
1399  //   if (JA.getKind () == Action::CompileJobClass)
1400  //     Key = JA.getKind ();
1401  //     else
1402
1403  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1404    Key = Action::AnalyzeJobClass;
1405  else
1406    Key = JA.getKind();
1407  //   if ((JA.getKind () == Action::CompileJobClass)
1408  //     && (JA.getType () != types::TY_LTO_BC)) {
1409  //     Key = JA.getKind ();
1410  //   }
1411
1412  Tool *&T = Tools[Key];
1413  if (!T) {
1414    switch (Key) {
1415    case Action::InputClass:
1416    case Action::BindArchClass:
1417      assert(0 && "Invalid tool kind.");
1418    case Action::AnalyzeJobClass:
1419      T = new tools::Clang(*this); break;
1420    case Action::AssembleJobClass:
1421      T = new tools::hexagon::Assemble(*this); break;
1422    case Action::LinkJobClass:
1423      T = new tools::hexagon::Link(*this); break;
1424    default:
1425      assert(false && "Unsupported action for Hexagon target.");
1426    }
1427  }
1428
1429  return *T;
1430}
1431
1432bool Hexagon_TC::IsUnwindTablesDefault() const {
1433  // FIXME: Gross; we should probably have some separate target
1434  // definition, possibly even reusing the one in clang.
1435  return getArchName() == "x86_64";
1436}
1437
1438const char *Hexagon_TC::GetDefaultRelocationModel() const {
1439  return "static";
1440}
1441
1442const char *Hexagon_TC::GetForcedPicModel() const {
1443  return 0;
1444} // End Hexagon
1445
1446
1447/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1448/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1449/// Currently does not support anything else but compilation.
1450
1451TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple)
1452  : ToolChain(Host, Triple) {
1453  // Path mangling to find libexec
1454  std::string Path(getDriver().Dir);
1455
1456  Path += "/../libexec";
1457  getProgramPaths().push_back(Path);
1458}
1459
1460TCEToolChain::~TCEToolChain() {
1461  for (llvm::DenseMap<unsigned, Tool*>::iterator
1462           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1463      delete it->second;
1464}
1465
1466bool TCEToolChain::IsMathErrnoDefault() const {
1467  return true;
1468}
1469
1470bool TCEToolChain::IsUnwindTablesDefault() const {
1471  return false;
1472}
1473
1474const char *TCEToolChain::GetDefaultRelocationModel() const {
1475  return "static";
1476}
1477
1478const char *TCEToolChain::GetForcedPicModel() const {
1479  return 0;
1480}
1481
1482Tool &TCEToolChain::SelectTool(const Compilation &C,
1483                            const JobAction &JA,
1484                               const ActionList &Inputs) const {
1485  Action::ActionClass Key;
1486  Key = Action::AnalyzeJobClass;
1487
1488  Tool *&T = Tools[Key];
1489  if (!T) {
1490    switch (Key) {
1491    case Action::PreprocessJobClass:
1492      T = new tools::gcc::Preprocess(*this); break;
1493    case Action::AnalyzeJobClass:
1494      T = new tools::Clang(*this); break;
1495    default:
1496     llvm_unreachable("Unsupported action for TCE target.");
1497    }
1498  }
1499  return *T;
1500}
1501
1502/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1503
1504OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple)
1505  : Generic_ELF(Host, Triple) {
1506  getFilePaths().push_back(getDriver().Dir + "/../lib");
1507  getFilePaths().push_back("/usr/lib");
1508}
1509
1510Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
1511                          const ActionList &Inputs) const {
1512  Action::ActionClass Key;
1513  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1514    Key = Action::AnalyzeJobClass;
1515  else
1516    Key = JA.getKind();
1517
1518  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1519                                             options::OPT_no_integrated_as,
1520                                             IsIntegratedAssemblerDefault());
1521
1522  Tool *&T = Tools[Key];
1523  if (!T) {
1524    switch (Key) {
1525    case Action::AssembleJobClass: {
1526      if (UseIntegratedAs)
1527        T = new tools::ClangAs(*this);
1528      else
1529        T = new tools::openbsd::Assemble(*this);
1530      break;
1531    }
1532    case Action::LinkJobClass:
1533      T = new tools::openbsd::Link(*this); break;
1534    default:
1535      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1536    }
1537  }
1538
1539  return *T;
1540}
1541
1542/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1543
1544FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple)
1545  : Generic_ELF(Host, Triple) {
1546
1547  // Determine if we are compiling 32-bit code on an x86_64 platform.
1548  bool Lib32 = false;
1549  // FIXME: This is using the Driver's target triple as the host triple!
1550  if (Triple.getArch() == llvm::Triple::x86 &&
1551      getDriver().TargetTriple.getArch() == llvm::Triple::x86_64)
1552    Lib32 = true;
1553
1554  // FIXME: This is using the Driver's target triple as the host triple!
1555  if (Triple.getArch() == llvm::Triple::ppc &&
1556      getDriver().TargetTriple.getArch() == llvm::Triple::ppc64)
1557    Lib32 = true;
1558
1559  if (Lib32) {
1560    getFilePaths().push_back("/usr/lib32");
1561  } else {
1562    getFilePaths().push_back("/usr/lib");
1563  }
1564}
1565
1566Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
1567                          const ActionList &Inputs) const {
1568  Action::ActionClass Key;
1569  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1570    Key = Action::AnalyzeJobClass;
1571  else
1572    Key = JA.getKind();
1573
1574  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1575                                             options::OPT_no_integrated_as,
1576                                             IsIntegratedAssemblerDefault());
1577
1578  Tool *&T = Tools[Key];
1579  if (!T) {
1580    switch (Key) {
1581    case Action::AssembleJobClass:
1582      if (UseIntegratedAs)
1583        T = new tools::ClangAs(*this);
1584      else
1585        T = new tools::freebsd::Assemble(*this);
1586      break;
1587    case Action::LinkJobClass:
1588      T = new tools::freebsd::Link(*this); break;
1589    default:
1590      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1591    }
1592  }
1593
1594  return *T;
1595}
1596
1597/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1598
1599NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple,
1600               const llvm::Triple& ToolTriple)
1601  : Generic_ELF(Host, Triple), ToolTriple(ToolTriple) {
1602
1603  // Determine if we are compiling 32-bit code on an x86_64 platform.
1604  bool Lib32 = false;
1605  if (ToolTriple.getArch() == llvm::Triple::x86_64 &&
1606      Triple.getArch() == llvm::Triple::x86)
1607    Lib32 = true;
1608
1609  if (getDriver().UseStdLib) {
1610    if (Lib32)
1611      getFilePaths().push_back("=/usr/lib/i386");
1612    else
1613      getFilePaths().push_back("=/usr/lib");
1614  }
1615}
1616
1617Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
1618                         const ActionList &Inputs) const {
1619  Action::ActionClass Key;
1620  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1621    Key = Action::AnalyzeJobClass;
1622  else
1623    Key = JA.getKind();
1624
1625  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1626                                             options::OPT_no_integrated_as,
1627                                             IsIntegratedAssemblerDefault());
1628
1629  Tool *&T = Tools[Key];
1630  if (!T) {
1631    switch (Key) {
1632    case Action::AssembleJobClass:
1633      if (UseIntegratedAs)
1634        T = new tools::ClangAs(*this);
1635      else
1636        T = new tools::netbsd::Assemble(*this, ToolTriple);
1637      break;
1638    case Action::LinkJobClass:
1639      T = new tools::netbsd::Link(*this, ToolTriple);
1640      break;
1641    default:
1642      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1643    }
1644  }
1645
1646  return *T;
1647}
1648
1649/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1650
1651Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
1652  : Generic_ELF(Host, Triple) {
1653  getFilePaths().push_back(getDriver().Dir + "/../lib");
1654  getFilePaths().push_back("/usr/lib");
1655}
1656
1657Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
1658                        const ActionList &Inputs) const {
1659  Action::ActionClass Key;
1660  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1661    Key = Action::AnalyzeJobClass;
1662  else
1663    Key = JA.getKind();
1664
1665  Tool *&T = Tools[Key];
1666  if (!T) {
1667    switch (Key) {
1668    case Action::AssembleJobClass:
1669      T = new tools::minix::Assemble(*this); break;
1670    case Action::LinkJobClass:
1671      T = new tools::minix::Link(*this); break;
1672    default:
1673      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1674    }
1675  }
1676
1677  return *T;
1678}
1679
1680/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1681
1682AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
1683  : Generic_GCC(Host, Triple) {
1684
1685  getProgramPaths().push_back(getDriver().getInstalledDir());
1686  if (getDriver().getInstalledDir() != getDriver().Dir)
1687    getProgramPaths().push_back(getDriver().Dir);
1688
1689  getFilePaths().push_back(getDriver().Dir + "/../lib");
1690  getFilePaths().push_back("/usr/lib");
1691  getFilePaths().push_back("/usr/sfw/lib");
1692  getFilePaths().push_back("/opt/gcc4/lib");
1693  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1694
1695}
1696
1697Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
1698                           const ActionList &Inputs) const {
1699  Action::ActionClass Key;
1700  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
1701    Key = Action::AnalyzeJobClass;
1702  else
1703    Key = JA.getKind();
1704
1705  Tool *&T = Tools[Key];
1706  if (!T) {
1707    switch (Key) {
1708    case Action::AssembleJobClass:
1709      T = new tools::auroraux::Assemble(*this); break;
1710    case Action::LinkJobClass:
1711      T = new tools::auroraux::Link(*this); break;
1712    default:
1713      T = &Generic_GCC::SelectTool(C, JA, Inputs);
1714    }
1715  }
1716
1717  return *T;
1718}
1719
1720
1721/// Linux toolchain (very bare-bones at the moment).
1722
1723enum LinuxDistro {
1724  ArchLinux,
1725  DebianLenny,
1726  DebianSqueeze,
1727  DebianWheezy,
1728  Exherbo,
1729  RHEL4,
1730  RHEL5,
1731  RHEL6,
1732  Fedora13,
1733  Fedora14,
1734  Fedora15,
1735  FedoraRawhide,
1736  OpenSuse11_3,
1737  OpenSuse11_4,
1738  OpenSuse12_1,
1739  UbuntuHardy,
1740  UbuntuIntrepid,
1741  UbuntuJaunty,
1742  UbuntuKarmic,
1743  UbuntuLucid,
1744  UbuntuMaverick,
1745  UbuntuNatty,
1746  UbuntuOneiric,
1747  UnknownDistro
1748};
1749
1750static bool IsRedhat(enum LinuxDistro Distro) {
1751  return Distro == Fedora13 || Distro == Fedora14 ||
1752         Distro == Fedora15 || Distro == FedoraRawhide ||
1753         Distro == RHEL4 || Distro == RHEL5 || Distro == RHEL6;
1754}
1755
1756static bool IsOpenSuse(enum LinuxDistro Distro) {
1757  return Distro == OpenSuse11_3 || Distro == OpenSuse11_4 ||
1758         Distro == OpenSuse12_1;
1759}
1760
1761static bool IsDebian(enum LinuxDistro Distro) {
1762  return Distro == DebianLenny || Distro == DebianSqueeze ||
1763         Distro == DebianWheezy;
1764}
1765
1766static bool IsUbuntu(enum LinuxDistro Distro) {
1767  return Distro == UbuntuHardy  || Distro == UbuntuIntrepid ||
1768         Distro == UbuntuLucid  || Distro == UbuntuMaverick ||
1769         Distro == UbuntuJaunty || Distro == UbuntuKarmic ||
1770         Distro == UbuntuNatty  || Distro == UbuntuOneiric;
1771}
1772
1773static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
1774  llvm::OwningPtr<llvm::MemoryBuffer> File;
1775  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
1776    StringRef Data = File.get()->getBuffer();
1777    SmallVector<StringRef, 8> Lines;
1778    Data.split(Lines, "\n");
1779    for (unsigned int i = 0, s = Lines.size(); i < s; ++ i) {
1780      if (Lines[i] == "DISTRIB_CODENAME=hardy")
1781        return UbuntuHardy;
1782      else if (Lines[i] == "DISTRIB_CODENAME=intrepid")
1783        return UbuntuIntrepid;
1784      else if (Lines[i] == "DISTRIB_CODENAME=jaunty")
1785        return UbuntuJaunty;
1786      else if (Lines[i] == "DISTRIB_CODENAME=karmic")
1787        return UbuntuKarmic;
1788      else if (Lines[i] == "DISTRIB_CODENAME=lucid")
1789        return UbuntuLucid;
1790      else if (Lines[i] == "DISTRIB_CODENAME=maverick")
1791        return UbuntuMaverick;
1792      else if (Lines[i] == "DISTRIB_CODENAME=natty")
1793        return UbuntuNatty;
1794      else if (Lines[i] == "DISTRIB_CODENAME=oneiric")
1795        return UbuntuOneiric;
1796    }
1797    return UnknownDistro;
1798  }
1799
1800  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
1801    StringRef Data = File.get()->getBuffer();
1802    if (Data.startswith("Fedora release 15"))
1803      return Fedora15;
1804    else if (Data.startswith("Fedora release 14"))
1805      return Fedora14;
1806    else if (Data.startswith("Fedora release 13"))
1807      return Fedora13;
1808    else if (Data.startswith("Fedora release") &&
1809             Data.find("Rawhide") != StringRef::npos)
1810      return FedoraRawhide;
1811    else if (Data.startswith("Red Hat Enterprise Linux") &&
1812             Data.find("release 6") != StringRef::npos)
1813      return RHEL6;
1814    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1815	      Data.startswith("CentOS")) &&
1816             Data.find("release 5") != StringRef::npos)
1817      return RHEL5;
1818    else if ((Data.startswith("Red Hat Enterprise Linux") ||
1819	      Data.startswith("CentOS")) &&
1820             Data.find("release 4") != StringRef::npos)
1821      return RHEL4;
1822    return UnknownDistro;
1823  }
1824
1825  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
1826    StringRef Data = File.get()->getBuffer();
1827    if (Data[0] == '5')
1828      return DebianLenny;
1829    else if (Data.startswith("squeeze/sid") || Data[0] == '6')
1830      return DebianSqueeze;
1831    else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
1832      return DebianWheezy;
1833    return UnknownDistro;
1834  }
1835
1836  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
1837    StringRef Data = File.get()->getBuffer();
1838    if (Data.startswith("openSUSE 11.3"))
1839      return OpenSuse11_3;
1840    else if (Data.startswith("openSUSE 11.4"))
1841      return OpenSuse11_4;
1842    else if (Data.startswith("openSUSE 12.1"))
1843      return OpenSuse12_1;
1844    return UnknownDistro;
1845  }
1846
1847  bool Exists;
1848  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
1849    return Exherbo;
1850
1851  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
1852    return ArchLinux;
1853
1854  return UnknownDistro;
1855}
1856
1857static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
1858  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
1859}
1860
1861/// \brief Get our best guess at the multiarch triple for a target.
1862///
1863/// Debian-based systems are starting to use a multiarch setup where they use
1864/// a target-triple directory in the library and header search paths.
1865/// Unfortunately, this triple does not align with the vanilla target triple,
1866/// so we provide a rough mapping here.
1867static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
1868                                      StringRef SysRoot) {
1869  // For most architectures, just use whatever we have rather than trying to be
1870  // clever.
1871  switch (TargetTriple.getArch()) {
1872  default:
1873    return TargetTriple.str();
1874
1875    // We use the existence of '/lib/<triple>' as a directory to detect some
1876    // common linux triples that don't quite match the Clang triple for both
1877    // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
1878    // regardless of what the actual target triple is.
1879  case llvm::Triple::x86:
1880    if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
1881      return "i386-linux-gnu";
1882    return TargetTriple.str();
1883  case llvm::Triple::x86_64:
1884    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
1885      return "x86_64-linux-gnu";
1886    return TargetTriple.str();
1887  case llvm::Triple::mips:
1888    if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
1889      return "mips-linux-gnu";
1890    return TargetTriple.str();
1891  case llvm::Triple::mipsel:
1892    if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
1893      return "mipsel-linux-gnu";
1894    return TargetTriple.str();
1895  }
1896}
1897
1898Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
1899  : Generic_ELF(Host, Triple) {
1900  llvm::Triple::ArchType Arch = Triple.getArch();
1901  const std::string &SysRoot = getDriver().SysRoot;
1902
1903  // OpenSuse stores the linker with the compiler, add that to the search
1904  // path.
1905  ToolChain::path_list &PPaths = getProgramPaths();
1906  PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
1907                         GCCInstallation.getTriple().str() + "/bin").str());
1908
1909  Linker = GetProgramPath("ld");
1910
1911  LinuxDistro Distro = DetectLinuxDistro(Arch);
1912
1913  if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
1914    ExtraOpts.push_back("-z");
1915    ExtraOpts.push_back("relro");
1916  }
1917
1918  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
1919    ExtraOpts.push_back("-X");
1920
1921  const bool IsMips = Arch == llvm::Triple::mips ||
1922                      Arch == llvm::Triple::mipsel ||
1923                      Arch == llvm::Triple::mips64 ||
1924                      Arch == llvm::Triple::mips64el;
1925
1926  const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::ANDROIDEABI;
1927
1928  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
1929  // and the MIPS ABI require .dynsym to be sorted in different ways.
1930  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
1931  // ABI requires a mapping between the GOT and the symbol table.
1932  // Android loader does not support .gnu.hash.
1933  if (!IsMips && !IsAndroid) {
1934    if (IsRedhat(Distro) || IsOpenSuse(Distro) || Distro == UbuntuMaverick ||
1935        Distro == UbuntuNatty || Distro == UbuntuOneiric)
1936      ExtraOpts.push_back("--hash-style=gnu");
1937
1938    if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
1939        Distro == UbuntuJaunty || Distro == UbuntuKarmic)
1940      ExtraOpts.push_back("--hash-style=both");
1941  }
1942
1943  if (IsRedhat(Distro))
1944    ExtraOpts.push_back("--no-add-needed");
1945
1946  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
1947      IsOpenSuse(Distro) ||
1948      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
1949      Distro == UbuntuLucid ||
1950      Distro == UbuntuMaverick || Distro == UbuntuKarmic ||
1951      Distro == UbuntuNatty || Distro == UbuntuOneiric)
1952    ExtraOpts.push_back("--build-id");
1953
1954  if (IsOpenSuse(Distro))
1955    ExtraOpts.push_back("--enable-new-dtags");
1956
1957  // The selection of paths to try here is designed to match the patterns which
1958  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
1959  // This was determined by running GCC in a fake filesystem, creating all
1960  // possible permutations of these directories, and seeing which ones it added
1961  // to the link paths.
1962  path_list &Paths = getFilePaths();
1963
1964  const bool Is32Bits = (Arch == llvm::Triple::x86 ||
1965                         Arch == llvm::Triple::mips ||
1966                         Arch == llvm::Triple::mipsel ||
1967                         Arch == llvm::Triple::ppc);
1968
1969  const std::string Multilib = Is32Bits ? "lib32" : "lib64";
1970  const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
1971
1972  // Add the multilib suffixed paths where they are available.
1973  bool SuffixedGCCInstallation = false;
1974  if (GCCInstallation.isValid()) {
1975    StringRef Suffix32;
1976    StringRef Suffix64;
1977    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
1978    if (GCCTriple.getArch() == llvm::Triple::x86_64 ||
1979        GCCTriple.getArch() == llvm::Triple::ppc64) {
1980      Suffix32 = "/32";
1981      Suffix64 = "";
1982    } else {
1983      Suffix32 = "";
1984      Suffix64 = "/64";
1985    }
1986    const std::string Suffix = Is32Bits ? Suffix32 : Suffix64;
1987    SuffixedGCCInstallation = !Suffix.empty();
1988
1989    const std::string &LibPath = GCCInstallation.getParentLibPath();
1990    addPathIfExists(GCCInstallation.getInstallPath() + Suffix, Paths);
1991    addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
1992                    Paths);
1993    addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
1994    addPathIfExists(LibPath + "/../" + Multilib, Paths);
1995  }
1996  addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
1997  addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
1998  addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
1999  addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2000
2001  // Try walking via the GCC triple path in case of multiarch GCC
2002  // installations with strange symlinks.
2003  if (GCCInstallation.isValid())
2004    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2005                    "/../../" + Multilib, Paths);
2006
2007  // Add the non-multilib suffixed paths (if potentially different).
2008  if (GCCInstallation.isValid()) {
2009    const std::string &LibPath = GCCInstallation.getParentLibPath();
2010    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2011    if (SuffixedGCCInstallation)
2012      addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2013    addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2014    addPathIfExists(LibPath, Paths);
2015  }
2016  addPathIfExists(SysRoot + "/lib", Paths);
2017  addPathIfExists(SysRoot + "/usr/lib", Paths);
2018}
2019
2020bool Linux::HasNativeLLVMSupport() const {
2021  return true;
2022}
2023
2024Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
2025                        const ActionList &Inputs) const {
2026  Action::ActionClass Key;
2027  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2028    Key = Action::AnalyzeJobClass;
2029  else
2030    Key = JA.getKind();
2031
2032  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
2033                                             options::OPT_no_integrated_as,
2034                                             IsIntegratedAssemblerDefault());
2035
2036  Tool *&T = Tools[Key];
2037  if (!T) {
2038    switch (Key) {
2039    case Action::AssembleJobClass:
2040      if (UseIntegratedAs)
2041        T = new tools::ClangAs(*this);
2042      else
2043        T = new tools::linuxtools::Assemble(*this);
2044      break;
2045    case Action::LinkJobClass:
2046      T = new tools::linuxtools::Link(*this); break;
2047    default:
2048      T = &Generic_GCC::SelectTool(C, JA, Inputs);
2049    }
2050  }
2051
2052  return *T;
2053}
2054
2055void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2056                                      ArgStringList &CC1Args) const {
2057  const Driver &D = getDriver();
2058
2059  if (DriverArgs.hasArg(options::OPT_nostdinc))
2060    return;
2061
2062  if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2063    addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2064
2065  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2066    llvm::sys::Path P(D.ResourceDir);
2067    P.appendComponent("include");
2068    addSystemInclude(DriverArgs, CC1Args, P.str());
2069  }
2070
2071  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2072    return;
2073
2074  // Check for configure-time C include directories.
2075  StringRef CIncludeDirs(C_INCLUDE_DIRS);
2076  if (CIncludeDirs != "") {
2077    SmallVector<StringRef, 5> dirs;
2078    CIncludeDirs.split(dirs, ":");
2079    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2080         I != E; ++I) {
2081      StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2082      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2083    }
2084    return;
2085  }
2086
2087  // Lacking those, try to detect the correct set of system includes for the
2088  // target triple.
2089
2090  // Implement generic Debian multiarch support.
2091  const StringRef X86_64MultiarchIncludeDirs[] = {
2092    "/usr/include/x86_64-linux-gnu",
2093
2094    // FIXME: These are older forms of multiarch. It's not clear that they're
2095    // in use in any released version of Debian, so we should consider
2096    // removing them.
2097    "/usr/include/i686-linux-gnu/64",
2098    "/usr/include/i486-linux-gnu/64"
2099  };
2100  const StringRef X86MultiarchIncludeDirs[] = {
2101    "/usr/include/i386-linux-gnu",
2102
2103    // FIXME: These are older forms of multiarch. It's not clear that they're
2104    // in use in any released version of Debian, so we should consider
2105    // removing them.
2106    "/usr/include/x86_64-linux-gnu/32",
2107    "/usr/include/i686-linux-gnu",
2108    "/usr/include/i486-linux-gnu"
2109  };
2110  const StringRef ARMMultiarchIncludeDirs[] = {
2111    "/usr/include/arm-linux-gnueabi"
2112  };
2113  const StringRef MIPSMultiarchIncludeDirs[] = {
2114    "/usr/include/mips-linux-gnu"
2115  };
2116  const StringRef MIPSELMultiarchIncludeDirs[] = {
2117    "/usr/include/mipsel-linux-gnu"
2118  };
2119  ArrayRef<StringRef> MultiarchIncludeDirs;
2120  if (getTriple().getArch() == llvm::Triple::x86_64) {
2121    MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2122  } else if (getTriple().getArch() == llvm::Triple::x86) {
2123    MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2124  } else if (getTriple().getArch() == llvm::Triple::arm) {
2125    MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2126  } else if (getTriple().getArch() == llvm::Triple::mips) {
2127    MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2128  } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2129    MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2130  }
2131  for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2132                                     E = MultiarchIncludeDirs.end();
2133       I != E; ++I) {
2134    if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2135      addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2136      break;
2137    }
2138  }
2139
2140  if (getTriple().getOS() == llvm::Triple::RTEMS)
2141    return;
2142
2143  // Add an include of '/include' directly. This isn't provided by default by
2144  // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2145  // add even when Clang is acting as-if it were a system compiler.
2146  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2147
2148  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2149}
2150
2151/// \brief Helper to add the thre variant paths for a libstdc++ installation.
2152/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2153                                                const ArgList &DriverArgs,
2154                                                ArgStringList &CC1Args) {
2155  if (!llvm::sys::fs::exists(Base))
2156    return false;
2157  addSystemInclude(DriverArgs, CC1Args, Base);
2158  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2159  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2160  return true;
2161}
2162
2163void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2164                                         ArgStringList &CC1Args) const {
2165  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2166      DriverArgs.hasArg(options::OPT_nostdincxx))
2167    return;
2168
2169  // Check if libc++ has been enabled and provide its include paths if so.
2170  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2171    // libc++ is always installed at a fixed path on Linux currently.
2172    addSystemInclude(DriverArgs, CC1Args,
2173                     getDriver().SysRoot + "/usr/include/c++/v1");
2174    return;
2175  }
2176
2177  const llvm::Triple &TargetTriple = getTriple();
2178
2179  StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
2180  if (!CxxIncludeRoot.empty()) {
2181    StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
2182    if (CxxIncludeArch.empty())
2183      CxxIncludeArch = TargetTriple.str();
2184
2185    addLibStdCXXIncludePaths(
2186      CxxIncludeRoot,
2187      CxxIncludeArch + (isTarget64Bit() ? CXX_INCLUDE_64BIT_DIR
2188                                        : CXX_INCLUDE_32BIT_DIR),
2189      DriverArgs, CC1Args);
2190    return;
2191  }
2192
2193  // Check if the target architecture specific dirs need a suffix. Note that we
2194  // only support the suffix-based bi-arch-like header scheme for host/target
2195  // mismatches of just bit width.
2196  // FIXME: This is using the Driver's target triple to emulate the host triple!
2197  llvm::Triple::ArchType HostArch = getDriver().TargetTriple.getArch();
2198  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2199  StringRef Suffix;
2200  if ((HostArch == llvm::Triple::x86 && TargetArch == llvm::Triple::x86_64) ||
2201      (HostArch == llvm::Triple::ppc && TargetArch == llvm::Triple::ppc64))
2202    Suffix = "/64";
2203  if ((HostArch == llvm::Triple::x86_64 && TargetArch == llvm::Triple::x86) ||
2204      (HostArch == llvm::Triple::ppc64 && TargetArch == llvm::Triple::ppc))
2205    Suffix = "/32";
2206
2207  // By default, look for the C++ headers in an include directory adjacent to
2208  // the lib directory of the GCC installation. Note that this is expect to be
2209  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2210  StringRef LibDir = GCCInstallation.getParentLibPath();
2211  StringRef InstallDir = GCCInstallation.getInstallPath();
2212  StringRef Version = GCCInstallation.getVersion();
2213  if (!addLibStdCXXIncludePaths(LibDir + "/../include/c++/" + Version,
2214                                GCCInstallation.getTriple().str() + Suffix,
2215                                DriverArgs, CC1Args)) {
2216    // Gentoo is weird and places its headers inside the GCC install, so if the
2217    // first attempt to find the headers fails, try this pattern.
2218    addLibStdCXXIncludePaths(InstallDir + "/include/g++-v4",
2219                             GCCInstallation.getTriple().str() + Suffix,
2220                             DriverArgs, CC1Args);
2221  }
2222}
2223
2224/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2225
2226DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
2227  : Generic_ELF(Host, Triple) {
2228
2229  // Path mangling to find libexec
2230  getProgramPaths().push_back(getDriver().getInstalledDir());
2231  if (getDriver().getInstalledDir() != getDriver().Dir)
2232    getProgramPaths().push_back(getDriver().Dir);
2233
2234  getFilePaths().push_back(getDriver().Dir + "/../lib");
2235  getFilePaths().push_back("/usr/lib");
2236  getFilePaths().push_back("/usr/lib/gcc41");
2237}
2238
2239Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
2240                            const ActionList &Inputs) const {
2241  Action::ActionClass Key;
2242  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
2243    Key = Action::AnalyzeJobClass;
2244  else
2245    Key = JA.getKind();
2246
2247  Tool *&T = Tools[Key];
2248  if (!T) {
2249    switch (Key) {
2250    case Action::AssembleJobClass:
2251      T = new tools::dragonfly::Assemble(*this); break;
2252    case Action::LinkJobClass:
2253      T = new tools::dragonfly::Link(*this); break;
2254    default:
2255      T = &Generic_GCC::SelectTool(C, JA, Inputs);
2256    }
2257  }
2258
2259  return *T;
2260}
2261