ToolChains.cpp revision e5dce308870cd7d6b5156640af3724433bc1c575
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#include "SanitizerArgs.h"
12#include "clang/Basic/ObjCRuntime.h"
13#include "clang/Basic/Version.h"
14#include "clang/Driver/Arg.h"
15#include "clang/Driver/ArgList.h"
16#include "clang/Driver/Compilation.h"
17#include "clang/Driver/Driver.h"
18#include "clang/Driver/DriverDiagnostic.h"
19#include "clang/Driver/OptTable.h"
20#include "clang/Driver/Option.h"
21#include "clang/Driver/Options.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Support/system_error.h"
32
33// FIXME: This needs to be listed last until we fix the broken include guards
34// in these files and the LLVM config.h files.
35#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
36
37#include <cstdlib> // ::getenv
38
39using namespace clang::driver;
40using namespace clang::driver::toolchains;
41using namespace clang;
42
43/// Darwin - Darwin tool chain for i386 and x86_64.
44
45Darwin::Darwin(const Driver &D, const llvm::Triple& Triple)
46  : ToolChain(D, Triple), TargetInitialized(false)
47{
48  // Compute the initial Darwin version from the triple
49  unsigned Major, Minor, Micro;
50  if (!Triple.getMacOSXVersion(Major, Minor, Micro))
51    getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
52      Triple.getOSName();
53  llvm::raw_string_ostream(MacosxVersionMin)
54    << Major << '.' << Minor << '.' << Micro;
55
56  // FIXME: DarwinVersion is only used to find GCC's libexec directory.
57  // It should be removed when we stop supporting that.
58  DarwinVersion[0] = Minor + 4;
59  DarwinVersion[1] = Micro;
60  DarwinVersion[2] = 0;
61
62  // Compute the initial iOS version from the triple
63  Triple.getiOSVersion(Major, Minor, Micro);
64  llvm::raw_string_ostream(iOSVersionMin)
65    << Major << '.' << Minor << '.' << Micro;
66}
67
68types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
69  types::ID Ty = types::lookupTypeForExtension(Ext);
70
71  // Darwin always preprocesses assembly files (unless -x is used explicitly).
72  if (Ty == types::TY_PP_Asm)
73    return types::TY_Asm;
74
75  return Ty;
76}
77
78bool Darwin::HasNativeLLVMSupport() const {
79  return true;
80}
81
82/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
83ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
84  if (isTargetIPhoneOS())
85    return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
86  if (isNonFragile)
87    return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
88  return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
89}
90
91/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
92bool Darwin::hasBlocksRuntime() const {
93  if (isTargetIPhoneOS())
94    return !isIPhoneOSVersionLT(3, 2);
95  else
96    return !isMacosxVersionLT(10, 6);
97}
98
99static const char *GetArmArchForMArch(StringRef Value) {
100  return llvm::StringSwitch<const char*>(Value)
101    .Case("armv6k", "armv6")
102    .Case("armv6m", "armv6m")
103    .Case("armv5tej", "armv5")
104    .Case("xscale", "xscale")
105    .Case("armv4t", "armv4t")
106    .Case("armv7", "armv7")
107    .Cases("armv7a", "armv7-a", "armv7")
108    .Cases("armv7r", "armv7-r", "armv7")
109    .Cases("armv7em", "armv7e-m", "armv7em")
110    .Cases("armv7f", "armv7-f", "armv7f")
111    .Cases("armv7k", "armv7-k", "armv7k")
112    .Cases("armv7m", "armv7-m", "armv7m")
113    .Cases("armv7s", "armv7-s", "armv7s")
114    .Default(0);
115}
116
117static const char *GetArmArchForMCpu(StringRef Value) {
118  return llvm::StringSwitch<const char *>(Value)
119    .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
120    .Cases("arm10e", "arm10tdmi", "armv5")
121    .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
122    .Case("xscale", "xscale")
123    .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
124    .Case("cortex-m0", "armv6m")
125    .Cases("cortex-a8", "cortex-r4", "cortex-a9", "cortex-a15", "armv7")
126    .Case("cortex-a9-mp", "armv7f")
127    .Case("cortex-m3", "armv7m")
128    .Case("cortex-m4", "armv7em")
129    .Case("swift", "armv7s")
130    .Default(0);
131}
132
133StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
134  switch (getTriple().getArch()) {
135  default:
136    return getArchName();
137
138  case llvm::Triple::thumb:
139  case llvm::Triple::arm: {
140    if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
141      if (const char *Arch = GetArmArchForMArch(A->getValue()))
142        return Arch;
143
144    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
145      if (const char *Arch = GetArmArchForMCpu(A->getValue()))
146        return Arch;
147
148    return "arm";
149  }
150  }
151}
152
153Darwin::~Darwin() {
154  // Free tool implementations.
155  for (llvm::DenseMap<unsigned, Tool*>::iterator
156         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
157    delete it->second;
158}
159
160std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
161                                                types::ID InputType) const {
162  llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
163
164  // If the target isn't initialized (e.g., an unknown Darwin platform, return
165  // the default triple).
166  if (!isTargetInitialized())
167    return Triple.getTriple();
168
169  SmallString<16> Str;
170  Str += isTargetIPhoneOS() ? "ios" : "macosx";
171  Str += getTargetVersion().getAsString();
172  Triple.setOSName(Str);
173
174  return Triple.getTriple();
175}
176
177void Generic_ELF::anchor() {}
178
179Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA) const {
180  Action::ActionClass Key = JA.getKind();
181
182  if (getDriver().ShouldUseClangCompiler(JA)) {
183    // FIXME: This seems like a hacky way to choose clang frontend.
184    Key = Action::AnalyzeJobClass;
185  }
186
187  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
188                                             options::OPT_no_integrated_as,
189                                             IsIntegratedAssemblerDefault());
190
191  Tool *&T = Tools[Key];
192  if (!T) {
193    switch (Key) {
194    case Action::InputClass:
195    case Action::BindArchClass:
196      llvm_unreachable("Invalid tool kind.");
197    case Action::PreprocessJobClass:
198    case Action::AnalyzeJobClass:
199    case Action::MigrateJobClass:
200    case Action::PrecompileJobClass:
201    case Action::CompileJobClass:
202      T = new tools::Clang(*this); break;
203    case Action::AssembleJobClass: {
204      if (UseIntegratedAs)
205        T = new tools::ClangAs(*this);
206      else
207        T = new tools::darwin::Assemble(*this);
208      break;
209    }
210    case Action::LinkJobClass:
211      T = new tools::darwin::Link(*this); break;
212    case Action::LipoJobClass:
213      T = new tools::darwin::Lipo(*this); break;
214    case Action::DsymutilJobClass:
215      T = new tools::darwin::Dsymutil(*this); break;
216    case Action::VerifyJobClass:
217      T = new tools::darwin::VerifyDebug(*this); break;
218    }
219  }
220
221  return *T;
222}
223
224
225DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple)
226  : Darwin(D, Triple)
227{
228  getProgramPaths().push_back(getDriver().getInstalledDir());
229  if (getDriver().getInstalledDir() != getDriver().Dir)
230    getProgramPaths().push_back(getDriver().Dir);
231
232  // We expect 'as', 'ld', etc. to be adjacent to our install dir.
233  getProgramPaths().push_back(getDriver().getInstalledDir());
234  if (getDriver().getInstalledDir() != getDriver().Dir)
235    getProgramPaths().push_back(getDriver().Dir);
236}
237
238void DarwinClang::AddLinkARCArgs(const ArgList &Args,
239                                 ArgStringList &CmdArgs) const {
240
241  CmdArgs.push_back("-force_load");
242  llvm::sys::Path P(getDriver().ClangExecutable);
243  P.eraseComponent(); // 'clang'
244  P.eraseComponent(); // 'bin'
245  P.appendComponent("lib");
246  P.appendComponent("arc");
247  P.appendComponent("libarclite_");
248  std::string s = P.str();
249  // Mash in the platform.
250  if (isTargetIOSSimulator())
251    s += "iphonesimulator";
252  else if (isTargetIPhoneOS())
253    s += "iphoneos";
254  else
255    s += "macosx";
256  s += ".a";
257
258  CmdArgs.push_back(Args.MakeArgString(s));
259}
260
261void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
262                                    ArgStringList &CmdArgs,
263                                    const char *DarwinStaticLib,
264                                    bool AlwaysLink) const {
265  llvm::sys::Path P(getDriver().ResourceDir);
266  P.appendComponent("lib");
267  P.appendComponent("darwin");
268  P.appendComponent(DarwinStaticLib);
269
270  // For now, allow missing resource libraries to support developers who may
271  // not have compiler-rt checked out or integrated into their build (unless
272  // we explicitly force linking with this library).
273  bool Exists;
274  if (AlwaysLink || (!llvm::sys::fs::exists(P.str(), Exists) && Exists))
275    CmdArgs.push_back(Args.MakeArgString(P.str()));
276}
277
278void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
279                                        ArgStringList &CmdArgs) const {
280  // Darwin only supports the compiler-rt based runtime libraries.
281  switch (GetRuntimeLibType(Args)) {
282  case ToolChain::RLT_CompilerRT:
283    break;
284  default:
285    getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
286      << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
287    return;
288  }
289
290  // Darwin doesn't support real static executables, don't link any runtime
291  // libraries with -static.
292  if (Args.hasArg(options::OPT_static) ||
293      Args.hasArg(options::OPT_fapple_kext) ||
294      Args.hasArg(options::OPT_mkernel))
295    return;
296
297  // Reject -static-libgcc for now, we can deal with this when and if someone
298  // cares. This is useful in situations where someone wants to statically link
299  // something like libstdc++, and needs its runtime support routines.
300  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
301    getDriver().Diag(diag::err_drv_unsupported_opt)
302      << A->getAsString(Args);
303    return;
304  }
305
306  // If we are building profile support, link that library in.
307  if (Args.hasArg(options::OPT_fprofile_arcs) ||
308      Args.hasArg(options::OPT_fprofile_generate) ||
309      Args.hasArg(options::OPT_fcreate_profile) ||
310      Args.hasArg(options::OPT_coverage)) {
311    // Select the appropriate runtime library for the target.
312    if (isTargetIPhoneOS()) {
313      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
314    } else {
315      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
316    }
317  }
318
319  SanitizerArgs Sanitize(getDriver(), Args);
320
321  // Add Ubsan runtime library, if required.
322  if (Sanitize.needsUbsanRt()) {
323    if (isTargetIPhoneOS()) {
324      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
325        << "-fsanitize=undefined";
326    } else {
327      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true);
328
329      // The Ubsan runtime library requires C++.
330      AddCXXStdlibLibArgs(Args, CmdArgs);
331    }
332  }
333
334  // Add ASAN runtime library, if required. Dynamic libraries and bundles
335  // should not be linked with the runtime library.
336  if (Sanitize.needsAsanRt()) {
337    if (Args.hasArg(options::OPT_dynamiclib) ||
338        Args.hasArg(options::OPT_bundle)) {
339      // Assume the binary will provide the ASan runtime.
340    } else if (isTargetIPhoneOS()) {
341      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
342        << "-fsanitize=address";
343    } else {
344      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx_dynamic.dylib", true);
345
346      // The ASAN runtime library requires C++.
347      AddCXXStdlibLibArgs(Args, CmdArgs);
348    }
349  }
350
351  // Otherwise link libSystem, then the dynamic runtime library, and finally any
352  // target specific static runtime library.
353  CmdArgs.push_back("-lSystem");
354
355  // Select the dynamic runtime library and the target specific static library.
356  if (isTargetIPhoneOS()) {
357    // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
358    // it never went into the SDK.
359    // Linking against libgcc_s.1 isn't needed for iOS 5.0+
360    if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
361      CmdArgs.push_back("-lgcc_s.1");
362
363    // We currently always need a static runtime library for iOS.
364    AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
365  } else {
366    // The dynamic runtime library was merged with libSystem for 10.6 and
367    // beyond; only 10.4 and 10.5 need an additional runtime library.
368    if (isMacosxVersionLT(10, 5))
369      CmdArgs.push_back("-lgcc_s.10.4");
370    else if (isMacosxVersionLT(10, 6))
371      CmdArgs.push_back("-lgcc_s.10.5");
372
373    // For OS X, we thought we would only need a static runtime library when
374    // targeting 10.4, to provide versions of the static functions which were
375    // omitted from 10.4.dylib.
376    //
377    // Unfortunately, that turned out to not be true, because Darwin system
378    // headers can still use eprintf on i386, and it is not exported from
379    // libSystem. Therefore, we still must provide a runtime library just for
380    // the tiny tiny handful of projects that *might* use that symbol.
381    if (isMacosxVersionLT(10, 5)) {
382      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
383    } else {
384      if (getTriple().getArch() == llvm::Triple::x86)
385        AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
386      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
387    }
388  }
389}
390
391void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
392  const OptTable &Opts = getDriver().getOpts();
393
394  // Support allowing the SDKROOT environment variable used by xcrun and other
395  // Xcode tools to define the default sysroot, by making it the default for
396  // isysroot.
397  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
398    // Warn if the path does not exist.
399    bool Exists;
400    if (llvm::sys::fs::exists(A->getValue(), Exists) || !Exists)
401      getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
402  } else {
403    if (char *env = ::getenv("SDKROOT")) {
404      // We only use this value as the default if it is an absolute path,
405      // exists, and it is not the root path.
406      if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) &&
407          StringRef(env) != "/") {
408        Args.append(Args.MakeSeparateArg(
409                      0, Opts.getOption(options::OPT_isysroot), env));
410      }
411    }
412  }
413
414  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
415  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
416  Arg *iOSSimVersion = Args.getLastArg(
417    options::OPT_mios_simulator_version_min_EQ);
418
419  if (OSXVersion && (iOSVersion || iOSSimVersion)) {
420    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
421          << OSXVersion->getAsString(Args)
422          << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
423    iOSVersion = iOSSimVersion = 0;
424  } else if (iOSVersion && iOSSimVersion) {
425    getDriver().Diag(diag::err_drv_argument_not_allowed_with)
426          << iOSVersion->getAsString(Args)
427          << iOSSimVersion->getAsString(Args);
428    iOSSimVersion = 0;
429  } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
430    // If no deployment target was specified on the command line, check for
431    // environment defines.
432    StringRef OSXTarget;
433    StringRef iOSTarget;
434    StringRef iOSSimTarget;
435    if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
436      OSXTarget = env;
437    if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
438      iOSTarget = env;
439    if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
440      iOSSimTarget = env;
441
442    // If no '-miphoneos-version-min' specified on the command line and
443    // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
444    // based on -isysroot.
445    if (iOSTarget.empty()) {
446      if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
447        StringRef first, second;
448        StringRef isysroot = A->getValue();
449        llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
450        if (second != "")
451          iOSTarget = second.substr(0,3);
452      }
453    }
454
455    // If no OSX or iOS target has been specified and we're compiling for armv7,
456    // go ahead as assume we're targeting iOS.
457    if (OSXTarget.empty() && iOSTarget.empty() &&
458        (getDarwinArchName(Args) == "armv7" ||
459         getDarwinArchName(Args) == "armv7s"))
460        iOSTarget = iOSVersionMin;
461
462    // Handle conflicting deployment targets
463    //
464    // FIXME: Don't hardcode default here.
465
466    // Do not allow conflicts with the iOS simulator target.
467    if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
468      getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
469        << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
470        << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
471            "IPHONEOS_DEPLOYMENT_TARGET");
472    }
473
474    // Allow conflicts among OSX and iOS for historical reasons, but choose the
475    // default platform.
476    if (!OSXTarget.empty() && !iOSTarget.empty()) {
477      if (getTriple().getArch() == llvm::Triple::arm ||
478          getTriple().getArch() == llvm::Triple::thumb)
479        OSXTarget = "";
480      else
481        iOSTarget = "";
482    }
483
484    if (!OSXTarget.empty()) {
485      const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
486      OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
487      Args.append(OSXVersion);
488    } else if (!iOSTarget.empty()) {
489      const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
490      iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
491      Args.append(iOSVersion);
492    } else if (!iOSSimTarget.empty()) {
493      const Option O = Opts.getOption(
494        options::OPT_mios_simulator_version_min_EQ);
495      iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
496      Args.append(iOSSimVersion);
497    } else {
498      // Otherwise, assume we are targeting OS X.
499      const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
500      OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
501      Args.append(OSXVersion);
502    }
503  }
504
505  // Reject invalid architecture combinations.
506  if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
507                        getTriple().getArch() != llvm::Triple::x86_64)) {
508    getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
509      << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
510  }
511
512  // Set the tool chain target information.
513  unsigned Major, Minor, Micro;
514  bool HadExtra;
515  if (OSXVersion) {
516    assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
517    if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor,
518                                   Micro, HadExtra) || HadExtra ||
519        Major != 10 || Minor >= 100 || Micro >= 100)
520      getDriver().Diag(diag::err_drv_invalid_version_number)
521        << OSXVersion->getAsString(Args);
522  } else {
523    const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
524    assert(Version && "Unknown target platform!");
525    if (!Driver::GetReleaseVersion(Version->getValue(), Major, Minor,
526                                   Micro, HadExtra) || HadExtra ||
527        Major >= 10 || Minor >= 100 || Micro >= 100)
528      getDriver().Diag(diag::err_drv_invalid_version_number)
529        << Version->getAsString(Args);
530  }
531
532  bool IsIOSSim = bool(iOSSimVersion);
533
534  // In GCC, the simulator historically was treated as being OS X in some
535  // contexts, like determining the link logic, despite generally being called
536  // with an iOS deployment target. For compatibility, we detect the
537  // simulator as iOS + x86, and treat it differently in a few contexts.
538  if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
539                     getTriple().getArch() == llvm::Triple::x86_64))
540    IsIOSSim = true;
541
542  setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
543}
544
545void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
546                                      ArgStringList &CmdArgs) const {
547  CXXStdlibType Type = GetCXXStdlibType(Args);
548
549  switch (Type) {
550  case ToolChain::CST_Libcxx:
551    CmdArgs.push_back("-lc++");
552    break;
553
554  case ToolChain::CST_Libstdcxx: {
555    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
556    // it was previously found in the gcc lib dir. However, for all the Darwin
557    // platforms we care about it was -lstdc++.6, so we search for that
558    // explicitly if we can't see an obvious -lstdc++ candidate.
559
560    // Check in the sysroot first.
561    bool Exists;
562    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
563      llvm::sys::Path P(A->getValue());
564      P.appendComponent("usr");
565      P.appendComponent("lib");
566      P.appendComponent("libstdc++.dylib");
567
568      if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
569        P.eraseComponent();
570        P.appendComponent("libstdc++.6.dylib");
571        if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
572          CmdArgs.push_back(Args.MakeArgString(P.str()));
573          return;
574        }
575      }
576    }
577
578    // Otherwise, look in the root.
579    // FIXME: This should be removed someday when we don't have to care about
580    // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
581    if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
582      (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
583      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
584      return;
585    }
586
587    // Otherwise, let the linker search.
588    CmdArgs.push_back("-lstdc++");
589    break;
590  }
591  }
592}
593
594void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
595                                   ArgStringList &CmdArgs) const {
596
597  // For Darwin platforms, use the compiler-rt-based support library
598  // instead of the gcc-provided one (which is also incidentally
599  // only present in the gcc lib dir, which makes it hard to find).
600
601  llvm::sys::Path P(getDriver().ResourceDir);
602  P.appendComponent("lib");
603  P.appendComponent("darwin");
604
605  // Use the newer cc_kext for iOS ARM after 6.0.
606  if (!isTargetIPhoneOS() || isTargetIOSSimulator() ||
607      !isIPhoneOSVersionLT(6, 0)) {
608    P.appendComponent("libclang_rt.cc_kext.a");
609  } else {
610    P.appendComponent("libclang_rt.cc_kext_ios5.a");
611  }
612
613  // For now, allow missing resource libraries to support developers who may
614  // not have compiler-rt checked out or integrated into their build.
615  bool Exists;
616  if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
617    CmdArgs.push_back(Args.MakeArgString(P.str()));
618}
619
620DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
621                                      const char *BoundArch) const {
622  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
623  const OptTable &Opts = getDriver().getOpts();
624
625  // FIXME: We really want to get out of the tool chain level argument
626  // translation business, as it makes the driver functionality much
627  // more opaque. For now, we follow gcc closely solely for the
628  // purpose of easily achieving feature parity & testability. Once we
629  // have something that works, we should reevaluate each translation
630  // and try to push it down into tool specific logic.
631
632  for (ArgList::const_iterator it = Args.begin(),
633         ie = Args.end(); it != ie; ++it) {
634    Arg *A = *it;
635
636    if (A->getOption().matches(options::OPT_Xarch__)) {
637      // Skip this argument unless the architecture matches either the toolchain
638      // triple arch, or the arch being bound.
639      llvm::Triple::ArchType XarchArch =
640        tools::darwin::getArchTypeForDarwinArchName(A->getValue(0));
641      if (!(XarchArch == getArch()  ||
642            (BoundArch && XarchArch ==
643             tools::darwin::getArchTypeForDarwinArchName(BoundArch))))
644        continue;
645
646      Arg *OriginalArg = A;
647      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
648      unsigned Prev = Index;
649      Arg *XarchArg = Opts.ParseOneArg(Args, Index);
650
651      // If the argument parsing failed or more than one argument was
652      // consumed, the -Xarch_ argument's parameter tried to consume
653      // extra arguments. Emit an error and ignore.
654      //
655      // We also want to disallow any options which would alter the
656      // driver behavior; that isn't going to work in our model. We
657      // use isDriverOption() as an approximation, although things
658      // like -O4 are going to slip through.
659      if (!XarchArg || Index > Prev + 1) {
660        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
661          << A->getAsString(Args);
662        continue;
663      } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
664        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
665          << A->getAsString(Args);
666        continue;
667      }
668
669      XarchArg->setBaseArg(A);
670      A = XarchArg;
671
672      DAL->AddSynthesizedArg(A);
673
674      // Linker input arguments require custom handling. The problem is that we
675      // have already constructed the phase actions, so we can not treat them as
676      // "input arguments".
677      if (A->getOption().hasFlag(options::LinkerInput)) {
678        // Convert the argument into individual Zlinker_input_args.
679        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
680          DAL->AddSeparateArg(OriginalArg,
681                              Opts.getOption(options::OPT_Zlinker_input),
682                              A->getValue(i));
683
684        }
685        continue;
686      }
687    }
688
689    // Sob. These is strictly gcc compatible for the time being. Apple
690    // gcc translates options twice, which means that self-expanding
691    // options add duplicates.
692    switch ((options::ID) A->getOption().getID()) {
693    default:
694      DAL->append(A);
695      break;
696
697    case options::OPT_mkernel:
698    case options::OPT_fapple_kext:
699      DAL->append(A);
700      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
701      break;
702
703    case options::OPT_dependency_file:
704      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
705                          A->getValue());
706      break;
707
708    case options::OPT_gfull:
709      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
710      DAL->AddFlagArg(A,
711               Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
712      break;
713
714    case options::OPT_gused:
715      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
716      DAL->AddFlagArg(A,
717             Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
718      break;
719
720    case options::OPT_shared:
721      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
722      break;
723
724    case options::OPT_fconstant_cfstrings:
725      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
726      break;
727
728    case options::OPT_fno_constant_cfstrings:
729      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
730      break;
731
732    case options::OPT_Wnonportable_cfstrings:
733      DAL->AddFlagArg(A,
734                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
735      break;
736
737    case options::OPT_Wno_nonportable_cfstrings:
738      DAL->AddFlagArg(A,
739                   Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
740      break;
741
742    case options::OPT_fpascal_strings:
743      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
744      break;
745
746    case options::OPT_fno_pascal_strings:
747      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
748      break;
749    }
750  }
751
752  if (getTriple().getArch() == llvm::Triple::x86 ||
753      getTriple().getArch() == llvm::Triple::x86_64)
754    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
755      DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
756
757  // Add the arch options based on the particular spelling of -arch, to match
758  // how the driver driver works.
759  if (BoundArch) {
760    StringRef Name = BoundArch;
761    const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
762    const Option MArch = Opts.getOption(options::OPT_march_EQ);
763
764    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
765    // which defines the list of which architectures we accept.
766    if (Name == "ppc")
767      ;
768    else if (Name == "ppc601")
769      DAL->AddJoinedArg(0, MCpu, "601");
770    else if (Name == "ppc603")
771      DAL->AddJoinedArg(0, MCpu, "603");
772    else if (Name == "ppc604")
773      DAL->AddJoinedArg(0, MCpu, "604");
774    else if (Name == "ppc604e")
775      DAL->AddJoinedArg(0, MCpu, "604e");
776    else if (Name == "ppc750")
777      DAL->AddJoinedArg(0, MCpu, "750");
778    else if (Name == "ppc7400")
779      DAL->AddJoinedArg(0, MCpu, "7400");
780    else if (Name == "ppc7450")
781      DAL->AddJoinedArg(0, MCpu, "7450");
782    else if (Name == "ppc970")
783      DAL->AddJoinedArg(0, MCpu, "970");
784
785    else if (Name == "ppc64")
786      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
787
788    else if (Name == "i386")
789      ;
790    else if (Name == "i486")
791      DAL->AddJoinedArg(0, MArch, "i486");
792    else if (Name == "i586")
793      DAL->AddJoinedArg(0, MArch, "i586");
794    else if (Name == "i686")
795      DAL->AddJoinedArg(0, MArch, "i686");
796    else if (Name == "pentium")
797      DAL->AddJoinedArg(0, MArch, "pentium");
798    else if (Name == "pentium2")
799      DAL->AddJoinedArg(0, MArch, "pentium2");
800    else if (Name == "pentpro")
801      DAL->AddJoinedArg(0, MArch, "pentiumpro");
802    else if (Name == "pentIIm3")
803      DAL->AddJoinedArg(0, MArch, "pentium2");
804
805    else if (Name == "x86_64")
806      DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
807
808    else if (Name == "arm")
809      DAL->AddJoinedArg(0, MArch, "armv4t");
810    else if (Name == "armv4t")
811      DAL->AddJoinedArg(0, MArch, "armv4t");
812    else if (Name == "armv5")
813      DAL->AddJoinedArg(0, MArch, "armv5tej");
814    else if (Name == "xscale")
815      DAL->AddJoinedArg(0, MArch, "xscale");
816    else if (Name == "armv6")
817      DAL->AddJoinedArg(0, MArch, "armv6k");
818    else if (Name == "armv6m")
819      DAL->AddJoinedArg(0, MArch, "armv6m");
820    else if (Name == "armv7")
821      DAL->AddJoinedArg(0, MArch, "armv7a");
822    else if (Name == "armv7em")
823      DAL->AddJoinedArg(0, MArch, "armv7em");
824    else if (Name == "armv7f")
825      DAL->AddJoinedArg(0, MArch, "armv7f");
826    else if (Name == "armv7k")
827      DAL->AddJoinedArg(0, MArch, "armv7k");
828    else if (Name == "armv7m")
829      DAL->AddJoinedArg(0, MArch, "armv7m");
830    else if (Name == "armv7s")
831      DAL->AddJoinedArg(0, MArch, "armv7s");
832
833    else
834      llvm_unreachable("invalid Darwin arch");
835  }
836
837  // Add an explicit version min argument for the deployment target. We do this
838  // after argument translation because -Xarch_ arguments may add a version min
839  // argument.
840  if (BoundArch)
841    AddDeploymentTarget(*DAL);
842
843  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
844  // FIXME: It would be far better to avoid inserting those -static arguments,
845  // but we can't check the deployment target in the translation code until
846  // it is set here.
847  if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) {
848    for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
849      Arg *A = *it;
850      ++it;
851      if (A->getOption().getID() != options::OPT_mkernel &&
852          A->getOption().getID() != options::OPT_fapple_kext)
853        continue;
854      assert(it != ie && "unexpected argument translation");
855      A = *it;
856      assert(A->getOption().getID() == options::OPT_static &&
857             "missing expected -static argument");
858      it = DAL->getArgs().erase(it);
859    }
860  }
861
862  // Validate the C++ standard library choice.
863  CXXStdlibType Type = GetCXXStdlibType(*DAL);
864  if (Type == ToolChain::CST_Libcxx) {
865    // Check whether the target provides libc++.
866    StringRef where;
867
868    // Complain about targetting iOS < 5.0 in any way.
869    if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))
870      where = "iOS 5.0";
871
872    if (where != StringRef()) {
873      getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
874        << where;
875    }
876  }
877
878  return DAL;
879}
880
881bool Darwin::IsUnwindTablesDefault() const {
882  return getArch() == llvm::Triple::x86_64;
883}
884
885bool Darwin::UseDwarfDebugFlags() const {
886  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
887    return S[0] != '\0';
888  return false;
889}
890
891bool Darwin::UseSjLjExceptions() const {
892  // Darwin uses SjLj exceptions on ARM.
893  return (getTriple().getArch() == llvm::Triple::arm ||
894          getTriple().getArch() == llvm::Triple::thumb);
895}
896
897bool Darwin::isPICDefault() const {
898  return true;
899}
900
901bool Darwin::isPICDefaultForced() const {
902  return getArch() == llvm::Triple::x86_64;
903}
904
905bool Darwin::SupportsProfiling() const {
906  // Profiling instrumentation is only supported on x86.
907  return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
908}
909
910bool Darwin::SupportsObjCGC() const {
911  // Garbage collection is supported everywhere except on iPhone OS.
912  return !isTargetIPhoneOS();
913}
914
915void Darwin::CheckObjCARC() const {
916  if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6))
917    return;
918  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
919}
920
921std::string
922Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
923                                                types::ID InputType) const {
924  return ComputeLLVMTriple(Args, InputType);
925}
926
927/// Generic_GCC - A tool chain using the 'gcc' command to perform
928/// all subcommands; this relies on gcc translating the majority of
929/// command line options.
930
931/// \brief Parse a GCCVersion object out of a string of text.
932///
933/// This is the primary means of forming GCCVersion objects.
934/*static*/
935Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
936  const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
937  std::pair<StringRef, StringRef> First = VersionText.split('.');
938  std::pair<StringRef, StringRef> Second = First.second.split('.');
939
940  GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
941  if (First.first.getAsInteger(10, GoodVersion.Major) ||
942      GoodVersion.Major < 0)
943    return BadVersion;
944  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
945      GoodVersion.Minor < 0)
946    return BadVersion;
947
948  // First look for a number prefix and parse that if present. Otherwise just
949  // stash the entire patch string in the suffix, and leave the number
950  // unspecified. This covers versions strings such as:
951  //   4.4
952  //   4.4.0
953  //   4.4.x
954  //   4.4.2-rc4
955  //   4.4.x-patched
956  // And retains any patch number it finds.
957  StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
958  if (!PatchText.empty()) {
959    if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
960      // Try to parse the number and any suffix.
961      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
962          GoodVersion.Patch < 0)
963        return BadVersion;
964      GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
965    }
966  }
967
968  return GoodVersion;
969}
970
971/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
972bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
973  if (Major != RHS.Major)
974    return Major < RHS.Major;
975  if (Minor != RHS.Minor)
976    return Minor < RHS.Minor;
977  if (Patch != RHS.Patch) {
978    // Note that versions without a specified patch sort higher than those with
979    // a patch.
980    if (RHS.Patch == -1)
981      return true;
982    if (Patch == -1)
983      return false;
984
985    // Otherwise just sort on the patch itself.
986    return Patch < RHS.Patch;
987  }
988  if (PatchSuffix != RHS.PatchSuffix) {
989    // Sort empty suffixes higher.
990    if (RHS.PatchSuffix.empty())
991      return true;
992    if (PatchSuffix.empty())
993      return false;
994
995    // Provide a lexicographic sort to make this a total ordering.
996    return PatchSuffix < RHS.PatchSuffix;
997  }
998
999  // The versions are equal.
1000  return false;
1001}
1002
1003static StringRef getGCCToolchainDir(const ArgList &Args) {
1004  const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1005  if (A)
1006    return A->getValue();
1007  return GCC_INSTALL_PREFIX;
1008}
1009
1010/// \brief Construct a GCCInstallationDetector from the driver.
1011///
1012/// This performs all of the autodetection and sets up the various paths.
1013/// Once constructed, a GCCInstallationDetector is essentially immutable.
1014///
1015/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1016/// should instead pull the target out of the driver. This is currently
1017/// necessary because the driver doesn't store the final version of the target
1018/// triple.
1019Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
1020    const Driver &D,
1021    const llvm::Triple &TargetTriple,
1022    const ArgList &Args)
1023    : IsValid(false) {
1024  llvm::Triple MultiarchTriple
1025    = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
1026                                 : TargetTriple.get32BitArchVariant();
1027  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1028  // The library directories which may contain GCC installations.
1029  SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
1030  // The compatible GCC triples for this particular architecture.
1031  SmallVector<StringRef, 10> CandidateTripleAliases;
1032  SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
1033  CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
1034                           CandidateTripleAliases,
1035                           CandidateMultiarchLibDirs,
1036                           CandidateMultiarchTripleAliases);
1037
1038  // Compute the set of prefixes for our search.
1039  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1040                                       D.PrefixDirs.end());
1041
1042  StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1043  if (GCCToolchainDir != "") {
1044    if (GCCToolchainDir.back() == '/')
1045      GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1046
1047    Prefixes.push_back(GCCToolchainDir);
1048  } else {
1049    Prefixes.push_back(D.SysRoot);
1050    Prefixes.push_back(D.SysRoot + "/usr");
1051    Prefixes.push_back(D.InstalledDir + "/..");
1052  }
1053
1054  // Loop over the various components which exist and select the best GCC
1055  // installation available. GCC installs are ranked by version number.
1056  Version = GCCVersion::Parse("0.0.0");
1057  for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
1058    if (!llvm::sys::fs::exists(Prefixes[i]))
1059      continue;
1060    for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
1061      const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
1062      if (!llvm::sys::fs::exists(LibDir))
1063        continue;
1064      for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
1065        ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1066                               CandidateTripleAliases[k]);
1067    }
1068    for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
1069      const std::string LibDir
1070        = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
1071      if (!llvm::sys::fs::exists(LibDir))
1072        continue;
1073      for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
1074           ++k)
1075        ScanLibDirForGCCTriple(TargetArch, Args, LibDir,
1076                               CandidateMultiarchTripleAliases[k],
1077                               /*NeedsMultiarchSuffix=*/true);
1078    }
1079  }
1080}
1081
1082/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1083    const llvm::Triple &TargetTriple,
1084    const llvm::Triple &MultiarchTriple,
1085    SmallVectorImpl<StringRef> &LibDirs,
1086    SmallVectorImpl<StringRef> &TripleAliases,
1087    SmallVectorImpl<StringRef> &MultiarchLibDirs,
1088    SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
1089  // Declare a bunch of static data sets that we'll select between below. These
1090  // are specifically designed to always refer to string literals to avoid any
1091  // lifetime or initialization issues.
1092  static const char *const AArch64LibDirs[] = { "/lib" };
1093  static const char *const AArch64Triples[] = {
1094    "aarch64-none-linux-gnu",
1095    "aarch64-linux-gnu"
1096  };
1097
1098  static const char *const ARMLibDirs[] = { "/lib" };
1099  static const char *const ARMTriples[] = {
1100    "arm-linux-gnueabi",
1101    "arm-linux-androideabi"
1102  };
1103  static const char *const ARMHFTriples[] = {
1104    "arm-linux-gnueabihf",
1105  };
1106
1107  static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
1108  static const char *const X86_64Triples[] = {
1109    "x86_64-linux-gnu",
1110    "x86_64-unknown-linux-gnu",
1111    "x86_64-pc-linux-gnu",
1112    "x86_64-redhat-linux6E",
1113    "x86_64-redhat-linux",
1114    "x86_64-suse-linux",
1115    "x86_64-manbo-linux-gnu",
1116    "x86_64-linux-gnu",
1117    "x86_64-slackware-linux"
1118  };
1119  static const char *const X86LibDirs[] = { "/lib32", "/lib" };
1120  static const char *const X86Triples[] = {
1121    "i686-linux-gnu",
1122    "i686-pc-linux-gnu",
1123    "i486-linux-gnu",
1124    "i386-linux-gnu",
1125    "i386-redhat-linux6E",
1126    "i686-redhat-linux",
1127    "i586-redhat-linux",
1128    "i386-redhat-linux",
1129    "i586-suse-linux",
1130    "i486-slackware-linux",
1131    "i686-montavista-linux"
1132  };
1133
1134  static const char *const MIPSLibDirs[] = { "/lib" };
1135  static const char *const MIPSTriples[] = { "mips-linux-gnu" };
1136  static const char *const MIPSELLibDirs[] = { "/lib" };
1137  static const char *const MIPSELTriples[] = {
1138    "mipsel-linux-gnu",
1139    "mipsel-linux-android"
1140  };
1141
1142  static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
1143  static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
1144  static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
1145  static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
1146
1147  static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
1148  static const char *const PPCTriples[] = {
1149    "powerpc-linux-gnu",
1150    "powerpc-unknown-linux-gnu",
1151    "powerpc-linux-gnuspe",
1152    "powerpc-suse-linux",
1153    "powerpc-montavista-linuxspe"
1154  };
1155  static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
1156  static const char *const PPC64Triples[] = {
1157    "powerpc64-linux-gnu",
1158    "powerpc64-unknown-linux-gnu",
1159    "powerpc64-suse-linux",
1160    "ppc64-redhat-linux"
1161  };
1162
1163  switch (TargetTriple.getArch()) {
1164  case llvm::Triple::aarch64:
1165    LibDirs.append(AArch64LibDirs, AArch64LibDirs
1166                   + llvm::array_lengthof(AArch64LibDirs));
1167    TripleAliases.append(
1168      AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1169    MultiarchLibDirs.append(
1170      AArch64LibDirs, AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs));
1171    MultiarchTripleAliases.append(
1172      AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples));
1173    break;
1174  case llvm::Triple::arm:
1175  case llvm::Triple::thumb:
1176    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
1177    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1178      TripleAliases.append(
1179        ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples));
1180    } else {
1181      TripleAliases.append(
1182        ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
1183    }
1184    break;
1185  case llvm::Triple::x86_64:
1186    LibDirs.append(
1187      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1188    TripleAliases.append(
1189      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1190    MultiarchLibDirs.append(
1191      X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1192    MultiarchTripleAliases.append(
1193      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1194    break;
1195  case llvm::Triple::x86:
1196    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
1197    TripleAliases.append(
1198      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
1199    MultiarchLibDirs.append(
1200      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
1201    MultiarchTripleAliases.append(
1202      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
1203    break;
1204  case llvm::Triple::mips:
1205    LibDirs.append(
1206      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1207    TripleAliases.append(
1208      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1209    MultiarchLibDirs.append(
1210      MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1211    MultiarchTripleAliases.append(
1212      MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1213    break;
1214  case llvm::Triple::mipsel:
1215    LibDirs.append(
1216      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1217    TripleAliases.append(
1218      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1219    MultiarchLibDirs.append(
1220      MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1221    MultiarchTripleAliases.append(
1222      MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1223    break;
1224  case llvm::Triple::mips64:
1225    LibDirs.append(
1226      MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
1227    TripleAliases.append(
1228      MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
1229    MultiarchLibDirs.append(
1230      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
1231    MultiarchTripleAliases.append(
1232      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
1233    break;
1234  case llvm::Triple::mips64el:
1235    LibDirs.append(
1236      MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
1237    TripleAliases.append(
1238      MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
1239    MultiarchLibDirs.append(
1240      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
1241    MultiarchTripleAliases.append(
1242      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
1243    break;
1244  case llvm::Triple::ppc:
1245    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1246    TripleAliases.append(
1247      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1248    MultiarchLibDirs.append(
1249      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1250    MultiarchTripleAliases.append(
1251      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1252    break;
1253  case llvm::Triple::ppc64:
1254    LibDirs.append(
1255      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
1256    TripleAliases.append(
1257      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
1258    MultiarchLibDirs.append(
1259      PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
1260    MultiarchTripleAliases.append(
1261      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
1262    break;
1263
1264  default:
1265    // By default, just rely on the standard lib directories and the original
1266    // triple.
1267    break;
1268  }
1269
1270  // Always append the drivers target triple to the end, in case it doesn't
1271  // match any of our aliases.
1272  TripleAliases.push_back(TargetTriple.str());
1273
1274  // Also include the multiarch variant if it's different.
1275  if (TargetTriple.str() != MultiarchTriple.str())
1276    MultiarchTripleAliases.push_back(MultiarchTriple.str());
1277}
1278
1279// FIXME: There is the same routine in the Tools.cpp.
1280static bool hasMipsN32ABIArg(const ArgList &Args) {
1281  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1282  return A && (A->getValue() == StringRef("n32"));
1283}
1284
1285static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,
1286                                          const ArgList &Args) {
1287  if (TargetArch == llvm::Triple::x86_64 ||
1288      TargetArch == llvm::Triple::ppc64)
1289    return "/64";
1290
1291  if (TargetArch == llvm::Triple::mips64 ||
1292      TargetArch == llvm::Triple::mips64el) {
1293    if (hasMipsN32ABIArg(Args))
1294      return "/n32";
1295    else
1296      return "/64";
1297  }
1298
1299  return "/32";
1300}
1301
1302void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
1303    llvm::Triple::ArchType TargetArch, const ArgList &Args,
1304    const std::string &LibDir,
1305    StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
1306  // There are various different suffixes involving the triple we
1307  // check for. We also record what is necessary to walk from each back
1308  // up to the lib directory.
1309  const std::string LibSuffixes[] = {
1310    "/gcc/" + CandidateTriple.str(),
1311    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
1312
1313    // The Freescale PPC SDK has the gcc libraries in
1314    // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
1315    "/" + CandidateTriple.str(),
1316
1317    // Ubuntu has a strange mis-matched pair of triples that this happens to
1318    // match.
1319    // FIXME: It may be worthwhile to generalize this and look for a second
1320    // triple.
1321    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
1322  };
1323  const std::string InstallSuffixes[] = {
1324    "/../../..",
1325    "/../../../..",
1326    "/../..",
1327    "/../../../.."
1328  };
1329  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
1330  const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
1331                                   (TargetArch != llvm::Triple::x86));
1332  for (unsigned i = 0; i < NumLibSuffixes; ++i) {
1333    StringRef LibSuffix = LibSuffixes[i];
1334    llvm::error_code EC;
1335    for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
1336         !EC && LI != LE; LI = LI.increment(EC)) {
1337      StringRef VersionText = llvm::sys::path::filename(LI->path());
1338      GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1339      static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
1340      if (CandidateVersion < MinVersion)
1341        continue;
1342      if (CandidateVersion <= Version)
1343        continue;
1344
1345      // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1346      // in what would normally be GCCInstallPath and put the 64-bit
1347      // libs in a subdirectory named 64. The simple logic we follow is that
1348      // *if* there is a subdirectory of the right name with crtbegin.o in it,
1349      // we use that. If not, and if not a multiarch triple, we look for
1350      // crtbegin.o without the subdirectory.
1351      StringRef MultiarchSuffix = getTargetMultiarchSuffix(TargetArch, Args);
1352      if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
1353        GCCMultiarchSuffix = MultiarchSuffix.str();
1354      } else {
1355        if (NeedsMultiarchSuffix ||
1356            !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
1357          continue;
1358        GCCMultiarchSuffix.clear();
1359      }
1360
1361      Version = CandidateVersion;
1362      GCCTriple.setTriple(CandidateTriple);
1363      // FIXME: We hack together the directory name here instead of
1364      // using LI to ensure stable path separators across Windows and
1365      // Linux.
1366      GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
1367      GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
1368      IsValid = true;
1369    }
1370  }
1371}
1372
1373Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
1374                         const ArgList &Args)
1375  : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
1376  getProgramPaths().push_back(getDriver().getInstalledDir());
1377  if (getDriver().getInstalledDir() != getDriver().Dir)
1378    getProgramPaths().push_back(getDriver().Dir);
1379}
1380
1381Generic_GCC::~Generic_GCC() {
1382  // Free tool implementations.
1383  for (llvm::DenseMap<unsigned, Tool*>::iterator
1384         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1385    delete it->second;
1386}
1387
1388Tool &Generic_GCC::SelectTool(const Compilation &C,
1389                              const JobAction &JA) const {
1390  Action::ActionClass Key;
1391  if (getDriver().ShouldUseClangCompiler(JA))
1392    Key = Action::AnalyzeJobClass;
1393  else
1394    Key = JA.getKind();
1395
1396  Tool *&T = Tools[Key];
1397  if (!T) {
1398    switch (Key) {
1399    case Action::InputClass:
1400    case Action::BindArchClass:
1401      llvm_unreachable("Invalid tool kind.");
1402    case Action::PreprocessJobClass:
1403      T = new tools::gcc::Preprocess(*this); break;
1404    case Action::PrecompileJobClass:
1405      T = new tools::gcc::Precompile(*this); break;
1406    case Action::AnalyzeJobClass:
1407    case Action::MigrateJobClass:
1408      T = new tools::Clang(*this); break;
1409    case Action::CompileJobClass:
1410      T = new tools::gcc::Compile(*this); break;
1411    case Action::AssembleJobClass:
1412      T = new tools::gcc::Assemble(*this); break;
1413    case Action::LinkJobClass:
1414      T = new tools::gcc::Link(*this); break;
1415
1416      // This is a bit ungeneric, but the only platform using a driver
1417      // driver is Darwin.
1418    case Action::LipoJobClass:
1419      T = new tools::darwin::Lipo(*this); break;
1420    case Action::DsymutilJobClass:
1421      T = new tools::darwin::Dsymutil(*this); break;
1422    case Action::VerifyJobClass:
1423      T = new tools::darwin::VerifyDebug(*this); break;
1424    }
1425  }
1426
1427  return *T;
1428}
1429
1430bool Generic_GCC::IsUnwindTablesDefault() const {
1431  return getArch() == llvm::Triple::x86_64;
1432}
1433
1434bool Generic_GCC::isPICDefault() const {
1435  return false;
1436}
1437
1438bool Generic_GCC::isPICDefaultForced() const {
1439  return false;
1440}
1441
1442/// Hexagon Toolchain
1443
1444std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir) {
1445
1446  // Locate the rest of the toolchain ...
1447  if (strlen(GCC_INSTALL_PREFIX))
1448    return std::string(GCC_INSTALL_PREFIX);
1449
1450  std::string InstallRelDir = InstalledDir + "/../../gnu";
1451  if (llvm::sys::fs::exists(InstallRelDir))
1452    return InstallRelDir;
1453
1454  std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu";
1455  if (llvm::sys::fs::exists(PrefixRelDir))
1456    return PrefixRelDir;
1457
1458  return InstallRelDir;
1459}
1460
1461static void GetHexagonLibraryPaths(
1462  const ArgList &Args,
1463  const std::string Ver,
1464  const std::string MarchString,
1465  const std::string &InstalledDir,
1466  ToolChain::path_list *LibPaths)
1467{
1468  bool buildingLib = Args.hasArg(options::OPT_shared);
1469
1470  //----------------------------------------------------------------------------
1471  // -L Args
1472  //----------------------------------------------------------------------------
1473  for (arg_iterator
1474         it = Args.filtered_begin(options::OPT_L),
1475         ie = Args.filtered_end();
1476       it != ie;
1477       ++it) {
1478    for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i)
1479      LibPaths->push_back((*it)->getValue(i));
1480  }
1481
1482  //----------------------------------------------------------------------------
1483  // Other standard paths
1484  //----------------------------------------------------------------------------
1485  const std::string MarchSuffix = "/" + MarchString;
1486  const std::string G0Suffix = "/G0";
1487  const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
1488  const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir) + "/";
1489
1490  // lib/gcc/hexagon/...
1491  std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/";
1492  if (buildingLib) {
1493    LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix);
1494    LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix);
1495  }
1496  LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix);
1497  LibPaths->push_back(LibGCCHexagonDir + Ver);
1498
1499  // lib/gcc/...
1500  LibPaths->push_back(RootDir + "lib/gcc");
1501
1502  // hexagon/lib/...
1503  std::string HexagonLibDir = RootDir + "hexagon/lib";
1504  if (buildingLib) {
1505    LibPaths->push_back(HexagonLibDir + MarchG0Suffix);
1506    LibPaths->push_back(HexagonLibDir + G0Suffix);
1507  }
1508  LibPaths->push_back(HexagonLibDir + MarchSuffix);
1509  LibPaths->push_back(HexagonLibDir);
1510}
1511
1512Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple,
1513                       const ArgList &Args)
1514  : Linux(D, Triple, Args) {
1515  const std::string InstalledDir(getDriver().getInstalledDir());
1516  const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir);
1517
1518  // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
1519  // program paths
1520  const std::string BinDir(GnuDir + "/bin");
1521  if (llvm::sys::fs::exists(BinDir))
1522    getProgramPaths().push_back(BinDir);
1523
1524  // Determine version of GCC libraries and headers to use.
1525  const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon");
1526  llvm::error_code ec;
1527  GCCVersion MaxVersion= GCCVersion::Parse("0.0.0");
1528  for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de;
1529       !ec && di != de; di = di.increment(ec)) {
1530    GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path()));
1531    if (MaxVersion < cv)
1532      MaxVersion = cv;
1533  }
1534  GCCLibAndIncVersion = MaxVersion;
1535
1536  ToolChain::path_list *LibPaths= &getFilePaths();
1537
1538  // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
1539  // 'elf' OS type, so the Linux paths are not appropriate. When we actually
1540  // support 'linux' we'll need to fix this up
1541  LibPaths->clear();
1542
1543  GetHexagonLibraryPaths(
1544    Args,
1545    GetGCCLibAndIncVersion(),
1546    GetTargetCPU(Args),
1547    InstalledDir,
1548    LibPaths);
1549}
1550
1551Hexagon_TC::~Hexagon_TC() {
1552  // Free tool implementations.
1553  for (llvm::DenseMap<unsigned, Tool*>::iterator
1554         it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1555    delete it->second;
1556}
1557
1558Tool &Hexagon_TC::SelectTool(const Compilation &C,
1559                             const JobAction &JA) const {
1560  Action::ActionClass Key;
1561  if (getDriver().ShouldUseClangCompiler(JA))
1562    Key = Action::AnalyzeJobClass;
1563  else
1564    Key = JA.getKind();
1565
1566  Tool *&T = Tools[Key];
1567  if (!T) {
1568    switch (Key) {
1569    case Action::InputClass:
1570    case Action::BindArchClass:
1571      assert(0 && "Invalid tool kind.");
1572    case Action::AnalyzeJobClass:
1573      T = new tools::Clang(*this); break;
1574    case Action::AssembleJobClass:
1575      T = new tools::hexagon::Assemble(*this); break;
1576    case Action::LinkJobClass:
1577      T = new tools::hexagon::Link(*this); break;
1578    default:
1579      assert(false && "Unsupported action for Hexagon target.");
1580    }
1581  }
1582
1583  return *T;
1584}
1585
1586void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1587                                           ArgStringList &CC1Args) const {
1588  const Driver &D = getDriver();
1589
1590  if (DriverArgs.hasArg(options::OPT_nostdinc) ||
1591      DriverArgs.hasArg(options::OPT_nostdlibinc))
1592    return;
1593
1594  llvm::sys::Path InstallDir(D.InstalledDir);
1595  std::string Ver(GetGCCLibAndIncVersion());
1596  std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir);
1597  std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver);
1598  addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include");
1599  addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed");
1600  addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include");
1601}
1602
1603void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1604                                              ArgStringList &CC1Args) const {
1605
1606  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1607      DriverArgs.hasArg(options::OPT_nostdincxx))
1608    return;
1609
1610  const Driver &D = getDriver();
1611  std::string Ver(GetGCCLibAndIncVersion());
1612  llvm::sys::Path IncludeDir(Hexagon_TC::GetGnuDir(D.InstalledDir));
1613
1614  IncludeDir.appendComponent("hexagon/include/c++/");
1615  IncludeDir.appendComponent(Ver);
1616  addSystemInclude(DriverArgs, CC1Args, IncludeDir.str());
1617}
1618
1619ToolChain::CXXStdlibType
1620Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const {
1621  Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1622  if (!A)
1623    return ToolChain::CST_Libstdcxx;
1624
1625  StringRef Value = A->getValue();
1626  if (Value != "libstdc++") {
1627    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1628      << A->getAsString(Args);
1629  }
1630
1631  return ToolChain::CST_Libstdcxx;
1632}
1633
1634static Arg *GetLastHexagonArchArg(const ArgList &Args)
1635{
1636  Arg *A = NULL;
1637
1638  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
1639       it != ie; ++it) {
1640    if ((*it)->getOption().matches(options::OPT_march_EQ) ||
1641        (*it)->getOption().matches(options::OPT_mcpu_EQ)) {
1642      A = *it;
1643      A->claim();
1644    } else if ((*it)->getOption().matches(options::OPT_m_Joined)) {
1645      StringRef Value = (*it)->getValue(0);
1646      if (Value.startswith("v")) {
1647        A = *it;
1648        A->claim();
1649      }
1650    }
1651  }
1652  return A;
1653}
1654
1655StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args)
1656{
1657  // Select the default CPU (v4) if none was given or detection failed.
1658  Arg *A = GetLastHexagonArchArg (Args);
1659  if (A) {
1660    StringRef WhichHexagon = A->getValue();
1661    if (WhichHexagon.startswith("hexagon"))
1662      return WhichHexagon.substr(sizeof("hexagon") - 1);
1663    if (WhichHexagon != "")
1664      return WhichHexagon;
1665  }
1666
1667  return "v4";
1668}
1669// End Hexagon
1670
1671/// TCEToolChain - A tool chain using the llvm bitcode tools to perform
1672/// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
1673/// Currently does not support anything else but compilation.
1674
1675TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
1676  : ToolChain(D, Triple) {
1677  // Path mangling to find libexec
1678  std::string Path(getDriver().Dir);
1679
1680  Path += "/../libexec";
1681  getProgramPaths().push_back(Path);
1682}
1683
1684TCEToolChain::~TCEToolChain() {
1685  for (llvm::DenseMap<unsigned, Tool*>::iterator
1686           it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
1687      delete it->second;
1688}
1689
1690bool TCEToolChain::IsMathErrnoDefault() const {
1691  return true;
1692}
1693
1694bool TCEToolChain::isPICDefault() const {
1695  return false;
1696}
1697
1698bool TCEToolChain::isPICDefaultForced() const {
1699  return false;
1700}
1701
1702Tool &TCEToolChain::SelectTool(const Compilation &C,
1703                               const JobAction &JA) const {
1704  Action::ActionClass Key;
1705  Key = Action::AnalyzeJobClass;
1706
1707  Tool *&T = Tools[Key];
1708  if (!T) {
1709    switch (Key) {
1710    case Action::PreprocessJobClass:
1711      T = new tools::gcc::Preprocess(*this); break;
1712    case Action::AnalyzeJobClass:
1713      T = new tools::Clang(*this); break;
1714    default:
1715     llvm_unreachable("Unsupported action for TCE target.");
1716    }
1717  }
1718  return *T;
1719}
1720
1721/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
1722
1723OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1724  : Generic_ELF(D, Triple, Args) {
1725  getFilePaths().push_back(getDriver().Dir + "/../lib");
1726  getFilePaths().push_back("/usr/lib");
1727}
1728
1729Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA) const {
1730  Action::ActionClass Key;
1731  if (getDriver().ShouldUseClangCompiler(JA))
1732    Key = Action::AnalyzeJobClass;
1733  else
1734    Key = JA.getKind();
1735
1736  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1737                                             options::OPT_no_integrated_as,
1738                                             IsIntegratedAssemblerDefault());
1739
1740  Tool *&T = Tools[Key];
1741  if (!T) {
1742    switch (Key) {
1743    case Action::AssembleJobClass: {
1744      if (UseIntegratedAs)
1745        T = new tools::ClangAs(*this);
1746      else
1747        T = new tools::openbsd::Assemble(*this);
1748      break;
1749    }
1750    case Action::LinkJobClass:
1751      T = new tools::openbsd::Link(*this); break;
1752    default:
1753      T = &Generic_GCC::SelectTool(C, JA);
1754    }
1755  }
1756
1757  return *T;
1758}
1759
1760/// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
1761
1762Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1763  : Generic_ELF(D, Triple, Args) {
1764  getFilePaths().push_back(getDriver().Dir + "/../lib");
1765  getFilePaths().push_back("/usr/lib");
1766}
1767
1768Tool &Bitrig::SelectTool(const Compilation &C, const JobAction &JA) const {
1769  Action::ActionClass Key;
1770  if (getDriver().ShouldUseClangCompiler(JA))
1771    Key = Action::AnalyzeJobClass;
1772  else
1773    Key = JA.getKind();
1774
1775  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1776                                             options::OPT_no_integrated_as,
1777                                             IsIntegratedAssemblerDefault());
1778
1779  Tool *&T = Tools[Key];
1780  if (!T) {
1781    switch (Key) {
1782    case Action::AssembleJobClass: {
1783      if (UseIntegratedAs)
1784        T = new tools::ClangAs(*this);
1785      else
1786        T = new tools::bitrig::Assemble(*this);
1787      break;
1788    }
1789    case Action::LinkJobClass:
1790      T = new tools::bitrig::Link(*this); break;
1791    default:
1792      T = &Generic_GCC::SelectTool(C, JA);
1793    }
1794  }
1795
1796  return *T;
1797}
1798
1799void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1800                                          ArgStringList &CC1Args) const {
1801  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1802      DriverArgs.hasArg(options::OPT_nostdincxx))
1803    return;
1804
1805  switch (GetCXXStdlibType(DriverArgs)) {
1806  case ToolChain::CST_Libcxx:
1807    addSystemInclude(DriverArgs, CC1Args,
1808                     getDriver().SysRoot + "/usr/include/c++/");
1809    break;
1810  case ToolChain::CST_Libstdcxx:
1811    addSystemInclude(DriverArgs, CC1Args,
1812                     getDriver().SysRoot + "/usr/include/c++/stdc++");
1813    addSystemInclude(DriverArgs, CC1Args,
1814                     getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
1815
1816    StringRef Triple = getTriple().str();
1817    if (Triple.startswith("amd64"))
1818      addSystemInclude(DriverArgs, CC1Args,
1819                       getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
1820                       Triple.substr(5));
1821    else
1822      addSystemInclude(DriverArgs, CC1Args,
1823                       getDriver().SysRoot + "/usr/include/c++/stdc++/" +
1824                       Triple);
1825    break;
1826  }
1827}
1828
1829void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
1830                                 ArgStringList &CmdArgs) const {
1831  switch (GetCXXStdlibType(Args)) {
1832  case ToolChain::CST_Libcxx:
1833    CmdArgs.push_back("-lc++");
1834    CmdArgs.push_back("-lcxxrt");
1835    // Include supc++ to provide Unwind until provided by libcxx.
1836    CmdArgs.push_back("-lgcc");
1837    break;
1838  case ToolChain::CST_Libstdcxx:
1839    CmdArgs.push_back("-lstdc++");
1840    break;
1841  }
1842}
1843
1844/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
1845
1846FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1847  : Generic_ELF(D, Triple, Args) {
1848
1849  // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
1850  // back to '/usr/lib' if it doesn't exist.
1851  if ((Triple.getArch() == llvm::Triple::x86 ||
1852       Triple.getArch() == llvm::Triple::ppc) &&
1853      llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
1854    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
1855  else
1856    getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
1857}
1858
1859Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA) const {
1860  Action::ActionClass Key;
1861  if (getDriver().ShouldUseClangCompiler(JA))
1862    Key = Action::AnalyzeJobClass;
1863  else
1864    Key = JA.getKind();
1865
1866  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1867                                             options::OPT_no_integrated_as,
1868                                             IsIntegratedAssemblerDefault());
1869
1870  Tool *&T = Tools[Key];
1871  if (!T) {
1872    switch (Key) {
1873    case Action::AssembleJobClass:
1874      if (UseIntegratedAs)
1875        T = new tools::ClangAs(*this);
1876      else
1877        T = new tools::freebsd::Assemble(*this);
1878      break;
1879    case Action::LinkJobClass:
1880      T = new tools::freebsd::Link(*this); break;
1881    default:
1882      T = &Generic_GCC::SelectTool(C, JA);
1883    }
1884  }
1885
1886  return *T;
1887}
1888
1889bool FreeBSD::UseSjLjExceptions() const {
1890  // FreeBSD uses SjLj exceptions on ARM oabi.
1891  switch (getTriple().getEnvironment()) {
1892  case llvm::Triple::GNUEABI:
1893  case llvm::Triple::EABI:
1894    return false;
1895
1896  default:
1897    return (getTriple().getArch() == llvm::Triple::arm ||
1898            getTriple().getArch() == llvm::Triple::thumb);
1899  }
1900}
1901
1902/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
1903
1904NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1905  : Generic_ELF(D, Triple, Args) {
1906
1907  if (getDriver().UseStdLib) {
1908    // When targeting a 32-bit platform, try the special directory used on
1909    // 64-bit hosts, and only fall back to the main library directory if that
1910    // doesn't work.
1911    // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
1912    // what all logic is needed to emulate the '=' prefix here.
1913    if (Triple.getArch() == llvm::Triple::x86)
1914      getFilePaths().push_back("=/usr/lib/i386");
1915
1916    getFilePaths().push_back("=/usr/lib");
1917  }
1918}
1919
1920Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA) const {
1921  Action::ActionClass Key;
1922  if (getDriver().ShouldUseClangCompiler(JA))
1923    Key = Action::AnalyzeJobClass;
1924  else
1925    Key = JA.getKind();
1926
1927  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
1928                                             options::OPT_no_integrated_as,
1929                                             IsIntegratedAssemblerDefault());
1930
1931  Tool *&T = Tools[Key];
1932  if (!T) {
1933    switch (Key) {
1934    case Action::AssembleJobClass:
1935      if (UseIntegratedAs)
1936        T = new tools::ClangAs(*this);
1937      else
1938        T = new tools::netbsd::Assemble(*this);
1939      break;
1940    case Action::LinkJobClass:
1941      T = new tools::netbsd::Link(*this);
1942      break;
1943    default:
1944      T = &Generic_GCC::SelectTool(C, JA);
1945    }
1946  }
1947
1948  return *T;
1949}
1950
1951/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
1952
1953Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
1954  : Generic_ELF(D, Triple, Args) {
1955  getFilePaths().push_back(getDriver().Dir + "/../lib");
1956  getFilePaths().push_back("/usr/lib");
1957}
1958
1959Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA) const {
1960  Action::ActionClass Key;
1961  if (getDriver().ShouldUseClangCompiler(JA))
1962    Key = Action::AnalyzeJobClass;
1963  else
1964    Key = JA.getKind();
1965
1966  Tool *&T = Tools[Key];
1967  if (!T) {
1968    switch (Key) {
1969    case Action::AssembleJobClass:
1970      T = new tools::minix::Assemble(*this); break;
1971    case Action::LinkJobClass:
1972      T = new tools::minix::Link(*this); break;
1973    default:
1974      T = &Generic_GCC::SelectTool(C, JA);
1975    }
1976  }
1977
1978  return *T;
1979}
1980
1981/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
1982
1983AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
1984                   const ArgList &Args)
1985  : Generic_GCC(D, Triple, Args) {
1986
1987  getProgramPaths().push_back(getDriver().getInstalledDir());
1988  if (getDriver().getInstalledDir() != getDriver().Dir)
1989    getProgramPaths().push_back(getDriver().Dir);
1990
1991  getFilePaths().push_back(getDriver().Dir + "/../lib");
1992  getFilePaths().push_back("/usr/lib");
1993  getFilePaths().push_back("/usr/sfw/lib");
1994  getFilePaths().push_back("/opt/gcc4/lib");
1995  getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
1996
1997}
1998
1999Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA) const {
2000  Action::ActionClass Key;
2001  if (getDriver().ShouldUseClangCompiler(JA))
2002    Key = Action::AnalyzeJobClass;
2003  else
2004    Key = JA.getKind();
2005
2006  Tool *&T = Tools[Key];
2007  if (!T) {
2008    switch (Key) {
2009    case Action::AssembleJobClass:
2010      T = new tools::auroraux::Assemble(*this); break;
2011    case Action::LinkJobClass:
2012      T = new tools::auroraux::Link(*this); break;
2013    default:
2014      T = &Generic_GCC::SelectTool(C, JA);
2015    }
2016  }
2017
2018  return *T;
2019}
2020
2021/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
2022
2023Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
2024                 const ArgList &Args)
2025  : Generic_GCC(D, Triple, Args) {
2026
2027  getProgramPaths().push_back(getDriver().getInstalledDir());
2028  if (getDriver().getInstalledDir() != getDriver().Dir)
2029    getProgramPaths().push_back(getDriver().Dir);
2030
2031  getFilePaths().push_back(getDriver().Dir + "/../lib");
2032  getFilePaths().push_back("/usr/lib");
2033}
2034
2035Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA) const {
2036  Action::ActionClass Key;
2037  if (getDriver().ShouldUseClangCompiler(JA))
2038    Key = Action::AnalyzeJobClass;
2039  else
2040    Key = JA.getKind();
2041
2042  Tool *&T = Tools[Key];
2043  if (!T) {
2044    switch (Key) {
2045    case Action::AssembleJobClass:
2046      T = new tools::solaris::Assemble(*this); break;
2047    case Action::LinkJobClass:
2048      T = new tools::solaris::Link(*this); break;
2049    default:
2050      T = &Generic_GCC::SelectTool(C, JA);
2051    }
2052  }
2053
2054  return *T;
2055}
2056
2057/// Linux toolchain (very bare-bones at the moment).
2058
2059enum LinuxDistro {
2060  ArchLinux,
2061  DebianLenny,
2062  DebianSqueeze,
2063  DebianWheezy,
2064  DebianJessie,
2065  Exherbo,
2066  RHEL4,
2067  RHEL5,
2068  RHEL6,
2069  Fedora13,
2070  Fedora14,
2071  Fedora15,
2072  Fedora16,
2073  FedoraRawhide,
2074  OpenSuse11_3,
2075  OpenSuse11_4,
2076  OpenSuse12_1,
2077  OpenSuse12_2,
2078  UbuntuHardy,
2079  UbuntuIntrepid,
2080  UbuntuJaunty,
2081  UbuntuKarmic,
2082  UbuntuLucid,
2083  UbuntuMaverick,
2084  UbuntuNatty,
2085  UbuntuOneiric,
2086  UbuntuPrecise,
2087  UbuntuQuantal,
2088  UbuntuRaring,
2089  UnknownDistro
2090};
2091
2092static bool IsRedhat(enum LinuxDistro Distro) {
2093  return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
2094         (Distro >= RHEL4    && Distro <= RHEL6);
2095}
2096
2097static bool IsOpenSuse(enum LinuxDistro Distro) {
2098  return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
2099}
2100
2101static bool IsDebian(enum LinuxDistro Distro) {
2102  return Distro >= DebianLenny && Distro <= DebianJessie;
2103}
2104
2105static bool IsUbuntu(enum LinuxDistro Distro) {
2106  return Distro >= UbuntuHardy && Distro <= UbuntuRaring;
2107}
2108
2109static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
2110  OwningPtr<llvm::MemoryBuffer> File;
2111  if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
2112    StringRef Data = File.get()->getBuffer();
2113    SmallVector<StringRef, 8> Lines;
2114    Data.split(Lines, "\n");
2115    LinuxDistro Version = UnknownDistro;
2116    for (unsigned i = 0, s = Lines.size(); i != s; ++i)
2117      if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
2118        Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
2119          .Case("hardy", UbuntuHardy)
2120          .Case("intrepid", UbuntuIntrepid)
2121          .Case("jaunty", UbuntuJaunty)
2122          .Case("karmic", UbuntuKarmic)
2123          .Case("lucid", UbuntuLucid)
2124          .Case("maverick", UbuntuMaverick)
2125          .Case("natty", UbuntuNatty)
2126          .Case("oneiric", UbuntuOneiric)
2127          .Case("precise", UbuntuPrecise)
2128          .Case("quantal", UbuntuQuantal)
2129          .Case("raring", UbuntuRaring)
2130          .Default(UnknownDistro);
2131    return Version;
2132  }
2133
2134  if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
2135    StringRef Data = File.get()->getBuffer();
2136    if (Data.startswith("Fedora release 16"))
2137      return Fedora16;
2138    else if (Data.startswith("Fedora release 15"))
2139      return Fedora15;
2140    else if (Data.startswith("Fedora release 14"))
2141      return Fedora14;
2142    else if (Data.startswith("Fedora release 13"))
2143      return Fedora13;
2144    else if (Data.startswith("Fedora release") &&
2145             Data.find("Rawhide") != StringRef::npos)
2146      return FedoraRawhide;
2147    else if (Data.startswith("Red Hat Enterprise Linux") &&
2148             Data.find("release 6") != StringRef::npos)
2149      return RHEL6;
2150    else if ((Data.startswith("Red Hat Enterprise Linux") ||
2151              Data.startswith("CentOS")) &&
2152             Data.find("release 5") != StringRef::npos)
2153      return RHEL5;
2154    else if ((Data.startswith("Red Hat Enterprise Linux") ||
2155              Data.startswith("CentOS")) &&
2156             Data.find("release 4") != StringRef::npos)
2157      return RHEL4;
2158    return UnknownDistro;
2159  }
2160
2161  if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
2162    StringRef Data = File.get()->getBuffer();
2163    if (Data[0] == '5')
2164      return DebianLenny;
2165    else if (Data.startswith("squeeze/sid") || Data[0] == '6')
2166      return DebianSqueeze;
2167    else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
2168      return DebianWheezy;
2169    else if (Data.startswith("jessie/sid")  || Data[0] == '8')
2170      return DebianJessie;
2171    return UnknownDistro;
2172  }
2173
2174  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
2175    return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
2176      .StartsWith("openSUSE 11.3", OpenSuse11_3)
2177      .StartsWith("openSUSE 11.4", OpenSuse11_4)
2178      .StartsWith("openSUSE 12.1", OpenSuse12_1)
2179      .StartsWith("openSUSE 12.2", OpenSuse12_2)
2180      .Default(UnknownDistro);
2181
2182  bool Exists;
2183  if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
2184    return Exherbo;
2185
2186  if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
2187    return ArchLinux;
2188
2189  return UnknownDistro;
2190}
2191
2192/// \brief Get our best guess at the multiarch triple for a target.
2193///
2194/// Debian-based systems are starting to use a multiarch setup where they use
2195/// a target-triple directory in the library and header search paths.
2196/// Unfortunately, this triple does not align with the vanilla target triple,
2197/// so we provide a rough mapping here.
2198static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
2199                                      StringRef SysRoot) {
2200  // For most architectures, just use whatever we have rather than trying to be
2201  // clever.
2202  switch (TargetTriple.getArch()) {
2203  default:
2204    return TargetTriple.str();
2205
2206    // We use the existence of '/lib/<triple>' as a directory to detect some
2207    // common linux triples that don't quite match the Clang triple for both
2208    // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
2209    // regardless of what the actual target triple is.
2210  case llvm::Triple::arm:
2211  case llvm::Triple::thumb:
2212    if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2213      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf"))
2214        return "arm-linux-gnueabihf";
2215    } else {
2216      if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi"))
2217        return "arm-linux-gnueabi";
2218    }
2219    return TargetTriple.str();
2220  case llvm::Triple::x86:
2221    if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
2222      return "i386-linux-gnu";
2223    return TargetTriple.str();
2224  case llvm::Triple::x86_64:
2225    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
2226      return "x86_64-linux-gnu";
2227    return TargetTriple.str();
2228  case llvm::Triple::aarch64:
2229    if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu"))
2230      return "aarch64-linux-gnu";
2231  case llvm::Triple::mips:
2232    if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
2233      return "mips-linux-gnu";
2234    return TargetTriple.str();
2235  case llvm::Triple::mipsel:
2236    if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
2237      return "mipsel-linux-gnu";
2238    return TargetTriple.str();
2239  case llvm::Triple::ppc:
2240    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
2241      return "powerpc-linux-gnuspe";
2242    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
2243      return "powerpc-linux-gnu";
2244    return TargetTriple.str();
2245  case llvm::Triple::ppc64:
2246    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
2247      return "powerpc64-linux-gnu";
2248    return TargetTriple.str();
2249  }
2250}
2251
2252static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
2253  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
2254}
2255
2256static bool isMipsArch(llvm::Triple::ArchType Arch) {
2257  return Arch == llvm::Triple::mips ||
2258         Arch == llvm::Triple::mipsel ||
2259         Arch == llvm::Triple::mips64 ||
2260         Arch == llvm::Triple::mips64el;
2261}
2262
2263static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
2264                         const ArgList &Args) {
2265  if (Arch != llvm::Triple::mips &&
2266      Arch != llvm::Triple::mipsel)
2267    return false;
2268
2269  Arg *A = Args.getLastArg(options::OPT_march_EQ,
2270                           options::OPT_mcpu_EQ,
2271                           options::OPT_mips_CPUs_Group);
2272
2273  if (!A)
2274    return false;
2275
2276  if (A->getOption().matches(options::OPT_mips_CPUs_Group))
2277    return A->getOption().matches(options::OPT_mips32r2);
2278
2279  return A->getValue() == StringRef("mips32r2");
2280}
2281
2282static StringRef getMultilibDir(const llvm::Triple &Triple,
2283                                const ArgList &Args) {
2284  if (!isMipsArch(Triple.getArch()))
2285    return Triple.isArch32Bit() ? "lib32" : "lib64";
2286
2287  // lib32 directory has a special meaning on MIPS targets.
2288  // It contains N32 ABI binaries. Use this folder if produce
2289  // code for N32 ABI only.
2290  if (hasMipsN32ABIArg(Args))
2291    return "lib32";
2292
2293  return Triple.isArch32Bit() ? "lib" : "lib64";
2294}
2295
2296Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2297  : Generic_ELF(D, Triple, Args) {
2298  llvm::Triple::ArchType Arch = Triple.getArch();
2299  const std::string &SysRoot = getDriver().SysRoot;
2300
2301  // OpenSuse stores the linker with the compiler, add that to the search
2302  // path.
2303  ToolChain::path_list &PPaths = getProgramPaths();
2304  PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
2305                         GCCInstallation.getTriple().str() + "/bin").str());
2306
2307  Linker = GetProgramPath("ld");
2308
2309  LinuxDistro Distro = DetectLinuxDistro(Arch);
2310
2311  if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
2312    ExtraOpts.push_back("-z");
2313    ExtraOpts.push_back("relro");
2314  }
2315
2316  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
2317    ExtraOpts.push_back("-X");
2318
2319  const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
2320
2321  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
2322  // and the MIPS ABI require .dynsym to be sorted in different ways.
2323  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
2324  // ABI requires a mapping between the GOT and the symbol table.
2325  // Android loader does not support .gnu.hash.
2326  if (!isMipsArch(Arch) && !IsAndroid) {
2327    if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
2328        (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
2329      ExtraOpts.push_back("--hash-style=gnu");
2330
2331    if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
2332        Distro == UbuntuJaunty || Distro == UbuntuKarmic)
2333      ExtraOpts.push_back("--hash-style=both");
2334  }
2335
2336  if (IsRedhat(Distro))
2337    ExtraOpts.push_back("--no-add-needed");
2338
2339  if (Distro == DebianSqueeze || Distro == DebianWheezy ||
2340      Distro == DebianJessie || IsOpenSuse(Distro) ||
2341      (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
2342      (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
2343    ExtraOpts.push_back("--build-id");
2344
2345  if (IsOpenSuse(Distro))
2346    ExtraOpts.push_back("--enable-new-dtags");
2347
2348  // The selection of paths to try here is designed to match the patterns which
2349  // the GCC driver itself uses, as this is part of the GCC-compatible driver.
2350  // This was determined by running GCC in a fake filesystem, creating all
2351  // possible permutations of these directories, and seeing which ones it added
2352  // to the link paths.
2353  path_list &Paths = getFilePaths();
2354
2355  const std::string Multilib = getMultilibDir(Triple, Args);
2356  const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
2357
2358  // Add the multilib suffixed paths where they are available.
2359  if (GCCInstallation.isValid()) {
2360    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2361    const std::string &LibPath = GCCInstallation.getParentLibPath();
2362
2363    if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args))
2364      addPathIfExists(GCCInstallation.getInstallPath() +
2365                      GCCInstallation.getMultiarchSuffix() +
2366                      "/mips-r2",
2367                      Paths);
2368    else
2369      addPathIfExists((GCCInstallation.getInstallPath() +
2370                       GCCInstallation.getMultiarchSuffix()),
2371                      Paths);
2372
2373    // If the GCC installation we found is inside of the sysroot, we want to
2374    // prefer libraries installed in the parent prefix of the GCC installation.
2375    // It is important to *not* use these paths when the GCC installation is
2376    // outside of the system root as that can pick up unintended libraries.
2377    // This usually happens when there is an external cross compiler on the
2378    // host system, and a more minimal sysroot available that is the target of
2379    // the cross.
2380    if (StringRef(LibPath).startswith(SysRoot)) {
2381      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
2382                      Paths);
2383      addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
2384      addPathIfExists(LibPath + "/../" + Multilib, Paths);
2385    }
2386    // On Android, libraries in the parent prefix of the GCC installation are
2387    // preferred to the ones under sysroot.
2388    if (IsAndroid) {
2389      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2390    }
2391  }
2392  addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
2393  addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
2394  addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
2395  addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
2396
2397  // Try walking via the GCC triple path in case of multiarch GCC
2398  // installations with strange symlinks.
2399  if (GCCInstallation.isValid())
2400    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
2401                    "/../../" + Multilib, Paths);
2402
2403  // Add the non-multilib suffixed paths (if potentially different).
2404  if (GCCInstallation.isValid()) {
2405    const std::string &LibPath = GCCInstallation.getParentLibPath();
2406    const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
2407    if (!GCCInstallation.getMultiarchSuffix().empty())
2408      addPathIfExists(GCCInstallation.getInstallPath(), Paths);
2409
2410    if (StringRef(LibPath).startswith(SysRoot)) {
2411      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
2412      addPathIfExists(LibPath, Paths);
2413    }
2414  }
2415  addPathIfExists(SysRoot + "/lib", Paths);
2416  addPathIfExists(SysRoot + "/usr/lib", Paths);
2417}
2418
2419bool Linux::HasNativeLLVMSupport() const {
2420  return true;
2421}
2422
2423Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA) const {
2424  Action::ActionClass Key;
2425  if (getDriver().ShouldUseClangCompiler(JA))
2426    Key = Action::AnalyzeJobClass;
2427  else
2428    Key = JA.getKind();
2429
2430  bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
2431                                             options::OPT_no_integrated_as,
2432                                             IsIntegratedAssemblerDefault());
2433
2434  Tool *&T = Tools[Key];
2435  if (!T) {
2436    switch (Key) {
2437    case Action::AssembleJobClass:
2438      if (UseIntegratedAs)
2439        T = new tools::ClangAs(*this);
2440      else
2441        T = new tools::linuxtools::Assemble(*this);
2442      break;
2443    case Action::LinkJobClass:
2444      T = new tools::linuxtools::Link(*this); break;
2445    default:
2446      T = &Generic_GCC::SelectTool(C, JA);
2447    }
2448  }
2449
2450  return *T;
2451}
2452
2453void Linux::addClangTargetOptions(const ArgList &DriverArgs,
2454                                  ArgStringList &CC1Args) const {
2455  const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2456  bool UseInitArrayDefault
2457    = V >= Generic_GCC::GCCVersion::Parse("4.7.0") ||
2458      getTriple().getArch() == llvm::Triple::aarch64 ||
2459      getTriple().getEnvironment() == llvm::Triple::Android;
2460  if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2461                         options::OPT_fno_use_init_array,
2462                         UseInitArrayDefault))
2463    CC1Args.push_back("-fuse-init-array");
2464}
2465
2466void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2467                                      ArgStringList &CC1Args) const {
2468  const Driver &D = getDriver();
2469
2470  if (DriverArgs.hasArg(options::OPT_nostdinc))
2471    return;
2472
2473  if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
2474    addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
2475
2476  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2477    llvm::sys::Path P(D.ResourceDir);
2478    P.appendComponent("include");
2479    addSystemInclude(DriverArgs, CC1Args, P.str());
2480  }
2481
2482  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2483    return;
2484
2485  // Check for configure-time C include directories.
2486  StringRef CIncludeDirs(C_INCLUDE_DIRS);
2487  if (CIncludeDirs != "") {
2488    SmallVector<StringRef, 5> dirs;
2489    CIncludeDirs.split(dirs, ":");
2490    for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
2491         I != E; ++I) {
2492      StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
2493      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
2494    }
2495    return;
2496  }
2497
2498  // Lacking those, try to detect the correct set of system includes for the
2499  // target triple.
2500
2501  // Implement generic Debian multiarch support.
2502  const StringRef X86_64MultiarchIncludeDirs[] = {
2503    "/usr/include/x86_64-linux-gnu",
2504
2505    // FIXME: These are older forms of multiarch. It's not clear that they're
2506    // in use in any released version of Debian, so we should consider
2507    // removing them.
2508    "/usr/include/i686-linux-gnu/64",
2509    "/usr/include/i486-linux-gnu/64"
2510  };
2511  const StringRef X86MultiarchIncludeDirs[] = {
2512    "/usr/include/i386-linux-gnu",
2513
2514    // FIXME: These are older forms of multiarch. It's not clear that they're
2515    // in use in any released version of Debian, so we should consider
2516    // removing them.
2517    "/usr/include/x86_64-linux-gnu/32",
2518    "/usr/include/i686-linux-gnu",
2519    "/usr/include/i486-linux-gnu"
2520  };
2521  const StringRef AArch64MultiarchIncludeDirs[] = {
2522    "/usr/include/aarch64-linux-gnu"
2523  };
2524  const StringRef ARMMultiarchIncludeDirs[] = {
2525    "/usr/include/arm-linux-gnueabi"
2526  };
2527  const StringRef ARMHFMultiarchIncludeDirs[] = {
2528    "/usr/include/arm-linux-gnueabihf"
2529  };
2530  const StringRef MIPSMultiarchIncludeDirs[] = {
2531    "/usr/include/mips-linux-gnu"
2532  };
2533  const StringRef MIPSELMultiarchIncludeDirs[] = {
2534    "/usr/include/mipsel-linux-gnu"
2535  };
2536  const StringRef PPCMultiarchIncludeDirs[] = {
2537    "/usr/include/powerpc-linux-gnu"
2538  };
2539  const StringRef PPC64MultiarchIncludeDirs[] = {
2540    "/usr/include/powerpc64-linux-gnu"
2541  };
2542  ArrayRef<StringRef> MultiarchIncludeDirs;
2543  if (getTriple().getArch() == llvm::Triple::x86_64) {
2544    MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
2545  } else if (getTriple().getArch() == llvm::Triple::x86) {
2546    MultiarchIncludeDirs = X86MultiarchIncludeDirs;
2547  } else if (getTriple().getArch() == llvm::Triple::aarch64) {
2548    MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
2549  } else if (getTriple().getArch() == llvm::Triple::arm) {
2550    if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
2551      MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
2552    else
2553      MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
2554  } else if (getTriple().getArch() == llvm::Triple::mips) {
2555    MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
2556  } else if (getTriple().getArch() == llvm::Triple::mipsel) {
2557    MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
2558  } else if (getTriple().getArch() == llvm::Triple::ppc) {
2559    MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
2560  } else if (getTriple().getArch() == llvm::Triple::ppc64) {
2561    MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
2562  }
2563  for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
2564                                     E = MultiarchIncludeDirs.end();
2565       I != E; ++I) {
2566    if (llvm::sys::fs::exists(D.SysRoot + *I)) {
2567      addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
2568      break;
2569    }
2570  }
2571
2572  if (getTriple().getOS() == llvm::Triple::RTEMS)
2573    return;
2574
2575  // Add an include of '/include' directly. This isn't provided by default by
2576  // system GCCs, but is often used with cross-compiling GCCs, and harmless to
2577  // add even when Clang is acting as-if it were a system compiler.
2578  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
2579
2580  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
2581}
2582
2583/// \brief Helper to add the three variant paths for a libstdc++ installation.
2584/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
2585                                                const ArgList &DriverArgs,
2586                                                ArgStringList &CC1Args) {
2587  if (!llvm::sys::fs::exists(Base))
2588    return false;
2589  addSystemInclude(DriverArgs, CC1Args, Base);
2590  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
2591  addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
2592  return true;
2593}
2594
2595/// \brief Helper to add an extra variant path for an (Ubuntu) multilib
2596/// libstdc++ installation.
2597/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix,
2598                                                Twine TargetArchDir,
2599                                                Twine MultiLibSuffix,
2600                                                const ArgList &DriverArgs,
2601                                                ArgStringList &CC1Args) {
2602  if (!addLibStdCXXIncludePaths(Base+Suffix, TargetArchDir + MultiLibSuffix,
2603                                DriverArgs, CC1Args))
2604    return false;
2605
2606  addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir + Suffix
2607                   + MultiLibSuffix);
2608  return true;
2609}
2610
2611void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2612                                         ArgStringList &CC1Args) const {
2613  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2614      DriverArgs.hasArg(options::OPT_nostdincxx))
2615    return;
2616
2617  // Check if libc++ has been enabled and provide its include paths if so.
2618  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
2619    // libc++ is always installed at a fixed path on Linux currently.
2620    addSystemInclude(DriverArgs, CC1Args,
2621                     getDriver().SysRoot + "/usr/include/c++/v1");
2622    return;
2623  }
2624
2625  // We need a detected GCC installation on Linux to provide libstdc++'s
2626  // headers. We handled the libc++ case above.
2627  if (!GCCInstallation.isValid())
2628    return;
2629
2630  // By default, look for the C++ headers in an include directory adjacent to
2631  // the lib directory of the GCC installation. Note that this is expect to be
2632  // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2633  StringRef LibDir = GCCInstallation.getParentLibPath();
2634  StringRef InstallDir = GCCInstallation.getInstallPath();
2635  StringRef Version = GCCInstallation.getVersion().Text;
2636  StringRef TripleStr = GCCInstallation.getTriple().str();
2637
2638  if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
2639                               "/c++/" + Version.str(),
2640                               TripleStr,
2641                               GCCInstallation.getMultiarchSuffix(),
2642                               DriverArgs, CC1Args))
2643    return;
2644
2645  const std::string IncludePathCandidates[] = {
2646    // Gentoo is weird and places its headers inside the GCC install, so if the
2647    // first attempt to find the headers fails, try this pattern.
2648    InstallDir.str() + "/include/g++-v4",
2649    // Android standalone toolchain has C++ headers in yet another place.
2650    LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(),
2651    // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
2652    // without a subdirectory corresponding to the gcc version.
2653    LibDir.str() + "/../include/c++",
2654  };
2655
2656  for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) {
2657    if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr +
2658                GCCInstallation.getMultiarchSuffix()),
2659            DriverArgs, CC1Args))
2660      break;
2661  }
2662}
2663
2664/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
2665
2666DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
2667  : Generic_ELF(D, Triple, Args) {
2668
2669  // Path mangling to find libexec
2670  getProgramPaths().push_back(getDriver().getInstalledDir());
2671  if (getDriver().getInstalledDir() != getDriver().Dir)
2672    getProgramPaths().push_back(getDriver().Dir);
2673
2674  getFilePaths().push_back(getDriver().Dir + "/../lib");
2675  getFilePaths().push_back("/usr/lib");
2676  getFilePaths().push_back("/usr/lib/gcc41");
2677}
2678
2679Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA) const {
2680  Action::ActionClass Key;
2681  if (getDriver().ShouldUseClangCompiler(JA))
2682    Key = Action::AnalyzeJobClass;
2683  else
2684    Key = JA.getKind();
2685
2686  Tool *&T = Tools[Key];
2687  if (!T) {
2688    switch (Key) {
2689    case Action::AssembleJobClass:
2690      T = new tools::dragonfly::Assemble(*this); break;
2691    case Action::LinkJobClass:
2692      T = new tools::dragonfly::Link(*this); break;
2693    default:
2694      T = &Generic_GCC::SelectTool(C, JA);
2695    }
2696  }
2697
2698  return *T;
2699}
2700