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