clang API Documentation

ToolChains.cpp
Go to the documentation of this file.
00001 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "ToolChains.h"
00011 
00012 #include "clang/Driver/Arg.h"
00013 #include "clang/Driver/ArgList.h"
00014 #include "clang/Driver/Compilation.h"
00015 #include "clang/Driver/Driver.h"
00016 #include "clang/Driver/DriverDiagnostic.h"
00017 #include "clang/Driver/ObjCRuntime.h"
00018 #include "clang/Driver/OptTable.h"
00019 #include "clang/Driver/Option.h"
00020 #include "clang/Driver/Options.h"
00021 #include "clang/Basic/Version.h"
00022 
00023 #include "llvm/ADT/SmallString.h"
00024 #include "llvm/ADT/StringExtras.h"
00025 #include "llvm/ADT/StringSwitch.h"
00026 #include "llvm/ADT/STLExtras.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include "llvm/Support/FileSystem.h"
00029 #include "llvm/Support/MemoryBuffer.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Support/Path.h"
00032 #include "llvm/Support/system_error.h"
00033 
00034 #include <cstdlib> // ::getenv
00035 
00036 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
00037 
00038 using namespace clang::driver;
00039 using namespace clang::driver::toolchains;
00040 using namespace clang;
00041 
00042 /// Darwin - Darwin tool chain for i386 and x86_64.
00043 
00044 Darwin::Darwin(const Driver &D, const llvm::Triple& Triple)
00045   : ToolChain(D, Triple), TargetInitialized(false),
00046     ARCRuntimeForSimulator(ARCSimulator_None),
00047     LibCXXForSimulator(LibCXXSimulator_None)
00048 {
00049   // Compute the initial Darwin version from the triple
00050   unsigned Major, Minor, Micro;
00051   if (!Triple.getMacOSXVersion(Major, Minor, Micro))
00052     getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
00053       Triple.getOSName();
00054   llvm::raw_string_ostream(MacosxVersionMin)
00055     << Major << '.' << Minor << '.' << Micro;
00056 
00057   // FIXME: DarwinVersion is only used to find GCC's libexec directory.
00058   // It should be removed when we stop supporting that.
00059   DarwinVersion[0] = Minor + 4;
00060   DarwinVersion[1] = Micro;
00061   DarwinVersion[2] = 0;
00062 
00063   // Compute the initial iOS version from the triple
00064   Triple.getiOSVersion(Major, Minor, Micro);
00065   llvm::raw_string_ostream(iOSVersionMin)
00066     << Major << '.' << Minor << '.' << Micro;
00067 }
00068 
00069 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
00070   types::ID Ty = types::lookupTypeForExtension(Ext);
00071 
00072   // Darwin always preprocesses assembly files (unless -x is used explicitly).
00073   if (Ty == types::TY_PP_Asm)
00074     return types::TY_Asm;
00075 
00076   return Ty;
00077 }
00078 
00079 bool Darwin::HasNativeLLVMSupport() const {
00080   return true;
00081 }
00082 
00083 bool Darwin::hasARCRuntime() const {
00084   // FIXME: Remove this once there is a proper way to detect an ARC runtime
00085   // for the simulator.
00086   switch (ARCRuntimeForSimulator) {
00087   case ARCSimulator_None:
00088     break;
00089   case ARCSimulator_HasARCRuntime:
00090     return true;
00091   case ARCSimulator_NoARCRuntime:
00092     return false;
00093   }
00094 
00095   if (isTargetIPhoneOS())
00096     return !isIPhoneOSVersionLT(5);
00097   else
00098     return !isMacosxVersionLT(10, 7);
00099 }
00100 
00101 bool Darwin::hasSubscriptingRuntime() const {
00102     return !isTargetIPhoneOS() && !isMacosxVersionLT(10, 8);
00103 }
00104 
00105 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
00106 void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const {
00107   if (runtime.getKind() != ObjCRuntime::NeXT)
00108     return ToolChain::configureObjCRuntime(runtime);
00109 
00110   runtime.HasARC = runtime.HasWeak = hasARCRuntime();
00111   runtime.HasSubscripting = hasSubscriptingRuntime();
00112 
00113   // So far, objc_terminate is only available in iOS 5.
00114   // FIXME: do the simulator logic properly.
00115   if (!ARCRuntimeForSimulator && isTargetIPhoneOS())
00116     runtime.HasTerminate = !isIPhoneOSVersionLT(5);
00117   else
00118     runtime.HasTerminate = false;
00119 }
00120 
00121 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
00122 bool Darwin::hasBlocksRuntime() const {
00123   if (isTargetIPhoneOS())
00124     return !isIPhoneOSVersionLT(3, 2);
00125   else
00126     return !isMacosxVersionLT(10, 6);
00127 }
00128 
00129 static const char *GetArmArchForMArch(StringRef Value) {
00130   return llvm::StringSwitch<const char*>(Value)
00131     .Case("armv6k", "armv6")
00132     .Case("armv5tej", "armv5")
00133     .Case("xscale", "xscale")
00134     .Case("armv4t", "armv4t")
00135     .Case("armv7", "armv7")
00136     .Cases("armv7a", "armv7-a", "armv7")
00137     .Cases("armv7r", "armv7-r", "armv7")
00138     .Cases("armv7m", "armv7-m", "armv7")
00139     .Default(0);
00140 }
00141 
00142 static const char *GetArmArchForMCpu(StringRef Value) {
00143   return llvm::StringSwitch<const char *>(Value)
00144     .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5")
00145     .Cases("arm10e", "arm10tdmi", "armv5")
00146     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
00147     .Case("xscale", "xscale")
00148     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s",
00149            "arm1176jzf-s", "cortex-m0", "armv6")
00150     .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "armv7")
00151     .Default(0);
00152 }
00153 
00154 StringRef Darwin::getDarwinArchName(const ArgList &Args) const {
00155   switch (getTriple().getArch()) {
00156   default:
00157     return getArchName();
00158 
00159   case llvm::Triple::thumb:
00160   case llvm::Triple::arm: {
00161     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
00162       if (const char *Arch = GetArmArchForMArch(A->getValue(Args)))
00163         return Arch;
00164 
00165     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
00166       if (const char *Arch = GetArmArchForMCpu(A->getValue(Args)))
00167         return Arch;
00168 
00169     return "arm";
00170   }
00171   }
00172 }
00173 
00174 Darwin::~Darwin() {
00175   // Free tool implementations.
00176   for (llvm::DenseMap<unsigned, Tool*>::iterator
00177          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
00178     delete it->second;
00179 }
00180 
00181 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
00182                                                 types::ID InputType) const {
00183   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
00184 
00185   // If the target isn't initialized (e.g., an unknown Darwin platform, return
00186   // the default triple).
00187   if (!isTargetInitialized())
00188     return Triple.getTriple();
00189 
00190   SmallString<16> Str;
00191   Str += isTargetIPhoneOS() ? "ios" : "macosx";
00192   Str += getTargetVersion().getAsString();
00193   Triple.setOSName(Str);
00194 
00195   return Triple.getTriple();
00196 }
00197 
00198 void Generic_ELF::anchor() {}
00199 
00200 Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
00201                          const ActionList &Inputs) const {
00202   Action::ActionClass Key = JA.getKind();
00203   bool useClang = false;
00204 
00205   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) {
00206     useClang = true;
00207     // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI.
00208     if (!getDriver().shouldForceClangUse() &&
00209         Inputs.size() == 1 &&
00210         types::isCXX(Inputs[0]->getType()) &&
00211         getTriple().isOSDarwin() &&
00212         getTriple().getArch() == llvm::Triple::x86 &&
00213         (C.getArgs().getLastArg(options::OPT_fapple_kext) ||
00214          C.getArgs().getLastArg(options::OPT_mkernel)))
00215       useClang = false;
00216   }
00217 
00218   // FIXME: This seems like a hacky way to choose clang frontend.
00219   if (useClang)
00220     Key = Action::AnalyzeJobClass;
00221 
00222   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
00223                                              options::OPT_no_integrated_as,
00224                                              IsIntegratedAssemblerDefault());
00225 
00226   Tool *&T = Tools[Key];
00227   if (!T) {
00228     switch (Key) {
00229     case Action::InputClass:
00230     case Action::BindArchClass:
00231       llvm_unreachable("Invalid tool kind.");
00232     case Action::PreprocessJobClass:
00233       T = new tools::darwin::Preprocess(*this); break;
00234     case Action::AnalyzeJobClass:
00235     case Action::MigrateJobClass:
00236       T = new tools::Clang(*this); break;
00237     case Action::PrecompileJobClass:
00238     case Action::CompileJobClass:
00239       T = new tools::darwin::Compile(*this); break;
00240     case Action::AssembleJobClass: {
00241       if (UseIntegratedAs)
00242         T = new tools::ClangAs(*this);
00243       else
00244         T = new tools::darwin::Assemble(*this);
00245       break;
00246     }
00247     case Action::LinkJobClass:
00248       T = new tools::darwin::Link(*this); break;
00249     case Action::LipoJobClass:
00250       T = new tools::darwin::Lipo(*this); break;
00251     case Action::DsymutilJobClass:
00252       T = new tools::darwin::Dsymutil(*this); break;
00253     case Action::VerifyJobClass:
00254       T = new tools::darwin::VerifyDebug(*this); break;
00255     }
00256   }
00257 
00258   return *T;
00259 }
00260 
00261 
00262 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple)
00263   : Darwin(D, Triple)
00264 {
00265   getProgramPaths().push_back(getDriver().getInstalledDir());
00266   if (getDriver().getInstalledDir() != getDriver().Dir)
00267     getProgramPaths().push_back(getDriver().Dir);
00268 
00269   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
00270   getProgramPaths().push_back(getDriver().getInstalledDir());
00271   if (getDriver().getInstalledDir() != getDriver().Dir)
00272     getProgramPaths().push_back(getDriver().Dir);
00273 
00274   // For fallback, we need to know how to find the GCC cc1 executables, so we
00275   // also add the GCC libexec paths. This is legacy code that can be removed
00276   // once fallback is no longer useful.
00277   AddGCCLibexecPath(DarwinVersion[0]);
00278   AddGCCLibexecPath(DarwinVersion[0] - 2);
00279   AddGCCLibexecPath(DarwinVersion[0] - 1);
00280   AddGCCLibexecPath(DarwinVersion[0] + 1);
00281   AddGCCLibexecPath(DarwinVersion[0] + 2);
00282 }
00283 
00284 void DarwinClang::AddGCCLibexecPath(unsigned darwinVersion) {
00285   std::string ToolChainDir = "i686-apple-darwin";
00286   ToolChainDir += llvm::utostr(darwinVersion);
00287   ToolChainDir += "/4.2.1";
00288 
00289   std::string Path = getDriver().Dir;
00290   Path += "/../llvm-gcc-4.2/libexec/gcc/";
00291   Path += ToolChainDir;
00292   getProgramPaths().push_back(Path);
00293 
00294   Path = "/usr/llvm-gcc-4.2/libexec/gcc/";
00295   Path += ToolChainDir;
00296   getProgramPaths().push_back(Path);
00297 }
00298 
00299 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
00300                                  ArgStringList &CmdArgs) const {
00301 
00302   CmdArgs.push_back("-force_load");
00303   llvm::sys::Path P(getDriver().ClangExecutable);
00304   P.eraseComponent(); // 'clang'
00305   P.eraseComponent(); // 'bin'
00306   P.appendComponent("lib");
00307   P.appendComponent("arc");
00308   P.appendComponent("libarclite_");
00309   std::string s = P.str();
00310   // Mash in the platform.
00311   if (isTargetIOSSimulator())
00312     s += "iphonesimulator";
00313   else if (isTargetIPhoneOS())
00314     s += "iphoneos";
00315   // FIXME: Remove this once we depend fully on -mios-simulator-version-min.
00316   else if (ARCRuntimeForSimulator != ARCSimulator_None)
00317     s += "iphonesimulator";
00318   else
00319     s += "macosx";
00320   s += ".a";
00321 
00322   CmdArgs.push_back(Args.MakeArgString(s));
00323 }
00324 
00325 void DarwinClang::AddLinkRuntimeLib(const ArgList &Args,
00326                                     ArgStringList &CmdArgs,
00327                                     const char *DarwinStaticLib) const {
00328   llvm::sys::Path P(getDriver().ResourceDir);
00329   P.appendComponent("lib");
00330   P.appendComponent("darwin");
00331   P.appendComponent(DarwinStaticLib);
00332 
00333   // For now, allow missing resource libraries to support developers who may
00334   // not have compiler-rt checked out or integrated into their build.
00335   bool Exists;
00336   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
00337     CmdArgs.push_back(Args.MakeArgString(P.str()));
00338 }
00339 
00340 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
00341                                         ArgStringList &CmdArgs) const {
00342   // Darwin only supports the compiler-rt based runtime libraries.
00343   switch (GetRuntimeLibType(Args)) {
00344   case ToolChain::RLT_CompilerRT:
00345     break;
00346   default:
00347     getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
00348       << Args.getLastArg(options::OPT_rtlib_EQ)->getValue(Args) << "darwin";
00349     return;
00350   }
00351 
00352   // Darwin doesn't support real static executables, don't link any runtime
00353   // libraries with -static.
00354   if (Args.hasArg(options::OPT_static))
00355     return;
00356 
00357   // Reject -static-libgcc for now, we can deal with this when and if someone
00358   // cares. This is useful in situations where someone wants to statically link
00359   // something like libstdc++, and needs its runtime support routines.
00360   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
00361     getDriver().Diag(diag::err_drv_unsupported_opt)
00362       << A->getAsString(Args);
00363     return;
00364   }
00365 
00366   // If we are building profile support, link that library in.
00367   if (Args.hasArg(options::OPT_fprofile_arcs) ||
00368       Args.hasArg(options::OPT_fprofile_generate) ||
00369       Args.hasArg(options::OPT_fcreate_profile) ||
00370       Args.hasArg(options::OPT_coverage)) {
00371     // Select the appropriate runtime library for the target.
00372     if (isTargetIPhoneOS()) {
00373       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
00374     } else {
00375       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
00376     }
00377   }
00378 
00379   // Add ASAN runtime library, if required. Dynamic libraries and bundles
00380   // should not be linked with the runtime library.
00381   if (Args.hasFlag(options::OPT_faddress_sanitizer,
00382                    options::OPT_fno_address_sanitizer, false)) {
00383     if (Args.hasArg(options::OPT_dynamiclib) ||
00384         Args.hasArg(options::OPT_bundle)) return;
00385     if (isTargetIPhoneOS()) {
00386       getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
00387         << "-faddress-sanitizer";
00388     } else {
00389       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a");
00390 
00391       // The ASAN runtime library requires C++ and CoreFoundation.
00392       AddCXXStdlibLibArgs(Args, CmdArgs);
00393       CmdArgs.push_back("-framework");
00394       CmdArgs.push_back("CoreFoundation");
00395     }
00396   }
00397 
00398   // Otherwise link libSystem, then the dynamic runtime library, and finally any
00399   // target specific static runtime library.
00400   CmdArgs.push_back("-lSystem");
00401 
00402   // Select the dynamic runtime library and the target specific static library.
00403   if (isTargetIPhoneOS()) {
00404     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
00405     // it never went into the SDK.
00406     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
00407     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator())
00408       CmdArgs.push_back("-lgcc_s.1");
00409 
00410     // We currently always need a static runtime library for iOS.
00411     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
00412   } else {
00413     // The dynamic runtime library was merged with libSystem for 10.6 and
00414     // beyond; only 10.4 and 10.5 need an additional runtime library.
00415     if (isMacosxVersionLT(10, 5))
00416       CmdArgs.push_back("-lgcc_s.10.4");
00417     else if (isMacosxVersionLT(10, 6))
00418       CmdArgs.push_back("-lgcc_s.10.5");
00419 
00420     // For OS X, we thought we would only need a static runtime library when
00421     // targeting 10.4, to provide versions of the static functions which were
00422     // omitted from 10.4.dylib.
00423     //
00424     // Unfortunately, that turned out to not be true, because Darwin system
00425     // headers can still use eprintf on i386, and it is not exported from
00426     // libSystem. Therefore, we still must provide a runtime library just for
00427     // the tiny tiny handful of projects that *might* use that symbol.
00428     if (isMacosxVersionLT(10, 5)) {
00429       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
00430     } else {
00431       if (getTriple().getArch() == llvm::Triple::x86)
00432         AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
00433       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
00434     }
00435   }
00436 }
00437 
00438 static inline StringRef SimulatorVersionDefineName() {
00439   return "__IPHONE_OS_VERSION_MIN_REQUIRED";
00440 }
00441 
00442 /// \brief Parse the simulator version define:
00443 /// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
00444 // and return the grouped values as integers, e.g:
00445 //   __IPHONE_OS_VERSION_MIN_REQUIRED=40201
00446 // will return Major=4, Minor=2, Micro=1.
00447 static bool GetVersionFromSimulatorDefine(StringRef define,
00448                                           unsigned &Major, unsigned &Minor,
00449                                           unsigned &Micro) {
00450   assert(define.startswith(SimulatorVersionDefineName()));
00451   StringRef name, version;
00452   llvm::tie(name, version) = define.split('=');
00453   if (version.empty())
00454     return false;
00455   std::string verstr = version.str();
00456   char *end;
00457   unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
00458   if (*end != '\0')
00459     return false;
00460   Major = num / 10000;
00461   num = num % 10000;
00462   Minor = num / 100;
00463   Micro = num % 100;
00464   return true;
00465 }
00466 
00467 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
00468   const OptTable &Opts = getDriver().getOpts();
00469 
00470   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
00471   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
00472   Arg *iOSSimVersion = Args.getLastArg(
00473     options::OPT_mios_simulator_version_min_EQ);
00474 
00475   // FIXME: HACK! When compiling for the simulator we don't get a
00476   // '-miphoneos-version-min' to help us know whether there is an ARC runtime
00477   // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED
00478   // define passed in command-line.
00479   if (!iOSVersion && !iOSSimVersion) {
00480     for (arg_iterator it = Args.filtered_begin(options::OPT_D),
00481            ie = Args.filtered_end(); it != ie; ++it) {
00482       StringRef define = (*it)->getValue(Args);
00483       if (define.startswith(SimulatorVersionDefineName())) {
00484         unsigned Major = 0, Minor = 0, Micro = 0;
00485         if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
00486             Major < 10 && Minor < 100 && Micro < 100) {
00487           ARCRuntimeForSimulator = Major < 5 ? ARCSimulator_NoARCRuntime
00488                                              : ARCSimulator_HasARCRuntime;
00489           LibCXXForSimulator = Major < 5 ? LibCXXSimulator_NotAvailable
00490                                          : LibCXXSimulator_Available;
00491         }
00492         break;
00493       }
00494     }
00495   }
00496 
00497   if (OSXVersion && (iOSVersion || iOSSimVersion)) {
00498     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
00499           << OSXVersion->getAsString(Args)
00500           << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args);
00501     iOSVersion = iOSSimVersion = 0;
00502   } else if (iOSVersion && iOSSimVersion) {
00503     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
00504           << iOSVersion->getAsString(Args)
00505           << iOSSimVersion->getAsString(Args);
00506     iOSSimVersion = 0;
00507   } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) {
00508     // If no deployment target was specified on the command line, check for
00509     // environment defines.
00510     StringRef OSXTarget;
00511     StringRef iOSTarget;
00512     StringRef iOSSimTarget;
00513     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
00514       OSXTarget = env;
00515     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
00516       iOSTarget = env;
00517     if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET"))
00518       iOSSimTarget = env;
00519 
00520     // If no '-miphoneos-version-min' specified on the command line and
00521     // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default
00522     // based on -isysroot.
00523     if (iOSTarget.empty()) {
00524       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
00525         StringRef first, second;
00526         StringRef isysroot = A->getValue(Args);
00527         llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS"));
00528         if (second != "")
00529           iOSTarget = second.substr(0,3);
00530       }
00531     }
00532 
00533     // If no OSX or iOS target has been specified and we're compiling for armv7,
00534     // go ahead as assume we're targeting iOS.
00535     if (OSXTarget.empty() && iOSTarget.empty() &&
00536         getDarwinArchName(Args) == "armv7")
00537         iOSTarget = iOSVersionMin;
00538 
00539     // Handle conflicting deployment targets
00540     //
00541     // FIXME: Don't hardcode default here.
00542 
00543     // Do not allow conflicts with the iOS simulator target.
00544     if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) {
00545       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
00546         << "IOS_SIMULATOR_DEPLOYMENT_TARGET"
00547         << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" :
00548             "IPHONEOS_DEPLOYMENT_TARGET");
00549     }
00550 
00551     // Allow conflicts among OSX and iOS for historical reasons, but choose the
00552     // default platform.
00553     if (!OSXTarget.empty() && !iOSTarget.empty()) {
00554       if (getTriple().getArch() == llvm::Triple::arm ||
00555           getTriple().getArch() == llvm::Triple::thumb)
00556         OSXTarget = "";
00557       else
00558         iOSTarget = "";
00559     }
00560 
00561     if (!OSXTarget.empty()) {
00562       const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
00563       OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget);
00564       Args.append(OSXVersion);
00565     } else if (!iOSTarget.empty()) {
00566       const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
00567       iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget);
00568       Args.append(iOSVersion);
00569     } else if (!iOSSimTarget.empty()) {
00570       const Option *O = Opts.getOption(
00571         options::OPT_mios_simulator_version_min_EQ);
00572       iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget);
00573       Args.append(iOSSimVersion);
00574     } else {
00575       // Otherwise, assume we are targeting OS X.
00576       const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
00577       OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin);
00578       Args.append(OSXVersion);
00579     }
00580   }
00581 
00582   // Reject invalid architecture combinations.
00583   if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 &&
00584                         getTriple().getArch() != llvm::Triple::x86_64)) {
00585     getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target)
00586       << getTriple().getArchName() << iOSSimVersion->getAsString(Args);
00587   }
00588 
00589   // Set the tool chain target information.
00590   unsigned Major, Minor, Micro;
00591   bool HadExtra;
00592   if (OSXVersion) {
00593     assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!");
00594     if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor,
00595                                    Micro, HadExtra) || HadExtra ||
00596         Major != 10 || Minor >= 100 || Micro >= 100)
00597       getDriver().Diag(diag::err_drv_invalid_version_number)
00598         << OSXVersion->getAsString(Args);
00599   } else {
00600     const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion;
00601     assert(Version && "Unknown target platform!");
00602     if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor,
00603                                    Micro, HadExtra) || HadExtra ||
00604         Major >= 10 || Minor >= 100 || Micro >= 100)
00605       getDriver().Diag(diag::err_drv_invalid_version_number)
00606         << Version->getAsString(Args);
00607   }
00608 
00609   bool IsIOSSim = bool(iOSSimVersion);
00610 
00611   // In GCC, the simulator historically was treated as being OS X in some
00612   // contexts, like determining the link logic, despite generally being called
00613   // with an iOS deployment target. For compatibility, we detect the
00614   // simulator as iOS + x86, and treat it differently in a few contexts.
00615   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
00616                      getTriple().getArch() == llvm::Triple::x86_64))
00617     IsIOSSim = true;
00618 
00619   setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim);
00620 }
00621 
00622 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
00623                                       ArgStringList &CmdArgs) const {
00624   CXXStdlibType Type = GetCXXStdlibType(Args);
00625 
00626   switch (Type) {
00627   case ToolChain::CST_Libcxx:
00628     CmdArgs.push_back("-lc++");
00629     break;
00630 
00631   case ToolChain::CST_Libstdcxx: {
00632     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
00633     // it was previously found in the gcc lib dir. However, for all the Darwin
00634     // platforms we care about it was -lstdc++.6, so we search for that
00635     // explicitly if we can't see an obvious -lstdc++ candidate.
00636 
00637     // Check in the sysroot first.
00638     bool Exists;
00639     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
00640       llvm::sys::Path P(A->getValue(Args));
00641       P.appendComponent("usr");
00642       P.appendComponent("lib");
00643       P.appendComponent("libstdc++.dylib");
00644 
00645       if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) {
00646         P.eraseComponent();
00647         P.appendComponent("libstdc++.6.dylib");
00648         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
00649           CmdArgs.push_back(Args.MakeArgString(P.str()));
00650           return;
00651         }
00652       }
00653     }
00654 
00655     // Otherwise, look in the root.
00656     // FIXME: This should be removed someday when we don't have to care about
00657     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
00658     if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&&
00659       (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){
00660       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
00661       return;
00662     }
00663 
00664     // Otherwise, let the linker search.
00665     CmdArgs.push_back("-lstdc++");
00666     break;
00667   }
00668   }
00669 }
00670 
00671 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
00672                                    ArgStringList &CmdArgs) const {
00673 
00674   // For Darwin platforms, use the compiler-rt-based support library
00675   // instead of the gcc-provided one (which is also incidentally
00676   // only present in the gcc lib dir, which makes it hard to find).
00677 
00678   llvm::sys::Path P(getDriver().ResourceDir);
00679   P.appendComponent("lib");
00680   P.appendComponent("darwin");
00681   P.appendComponent("libclang_rt.cc_kext.a");
00682 
00683   // For now, allow missing resource libraries to support developers who may
00684   // not have compiler-rt checked out or integrated into their build.
00685   bool Exists;
00686   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
00687     CmdArgs.push_back(Args.MakeArgString(P.str()));
00688 }
00689 
00690 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
00691                                       const char *BoundArch) const {
00692   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
00693   const OptTable &Opts = getDriver().getOpts();
00694 
00695   // FIXME: We really want to get out of the tool chain level argument
00696   // translation business, as it makes the driver functionality much
00697   // more opaque. For now, we follow gcc closely solely for the
00698   // purpose of easily achieving feature parity & testability. Once we
00699   // have something that works, we should reevaluate each translation
00700   // and try to push it down into tool specific logic.
00701 
00702   for (ArgList::const_iterator it = Args.begin(),
00703          ie = Args.end(); it != ie; ++it) {
00704     Arg *A = *it;
00705 
00706     if (A->getOption().matches(options::OPT_Xarch__)) {
00707       // Skip this argument unless the architecture matches either the toolchain
00708       // triple arch, or the arch being bound.
00709       //
00710       // FIXME: Canonicalize name.
00711       StringRef XarchArch = A->getValue(Args, 0);
00712       if (!(XarchArch == getArchName()  ||
00713             (BoundArch && XarchArch == BoundArch)))
00714         continue;
00715 
00716       Arg *OriginalArg = A;
00717       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1));
00718       unsigned Prev = Index;
00719       Arg *XarchArg = Opts.ParseOneArg(Args, Index);
00720 
00721       // If the argument parsing failed or more than one argument was
00722       // consumed, the -Xarch_ argument's parameter tried to consume
00723       // extra arguments. Emit an error and ignore.
00724       //
00725       // We also want to disallow any options which would alter the
00726       // driver behavior; that isn't going to work in our model. We
00727       // use isDriverOption() as an approximation, although things
00728       // like -O4 are going to slip through.
00729       if (!XarchArg || Index > Prev + 1) {
00730         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
00731           << A->getAsString(Args);
00732         continue;
00733       } else if (XarchArg->getOption().isDriverOption()) {
00734         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
00735           << A->getAsString(Args);
00736         continue;
00737       }
00738 
00739       XarchArg->setBaseArg(A);
00740       A = XarchArg;
00741 
00742       DAL->AddSynthesizedArg(A);
00743 
00744       // Linker input arguments require custom handling. The problem is that we
00745       // have already constructed the phase actions, so we can not treat them as
00746       // "input arguments".
00747       if (A->getOption().isLinkerInput()) {
00748         // Convert the argument into individual Zlinker_input_args.
00749         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
00750           DAL->AddSeparateArg(OriginalArg,
00751                               Opts.getOption(options::OPT_Zlinker_input),
00752                               A->getValue(Args, i));
00753 
00754         }
00755         continue;
00756       }
00757     }
00758 
00759     // Sob. These is strictly gcc compatible for the time being. Apple
00760     // gcc translates options twice, which means that self-expanding
00761     // options add duplicates.
00762     switch ((options::ID) A->getOption().getID()) {
00763     default:
00764       DAL->append(A);
00765       break;
00766 
00767     case options::OPT_mkernel:
00768     case options::OPT_fapple_kext:
00769       DAL->append(A);
00770       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
00771       break;
00772 
00773     case options::OPT_dependency_file:
00774       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF),
00775                           A->getValue(Args));
00776       break;
00777 
00778     case options::OPT_gfull:
00779       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
00780       DAL->AddFlagArg(A,
00781                Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
00782       break;
00783 
00784     case options::OPT_gused:
00785       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
00786       DAL->AddFlagArg(A,
00787              Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
00788       break;
00789 
00790     case options::OPT_shared:
00791       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
00792       break;
00793 
00794     case options::OPT_fconstant_cfstrings:
00795       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
00796       break;
00797 
00798     case options::OPT_fno_constant_cfstrings:
00799       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
00800       break;
00801 
00802     case options::OPT_Wnonportable_cfstrings:
00803       DAL->AddFlagArg(A,
00804                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
00805       break;
00806 
00807     case options::OPT_Wno_nonportable_cfstrings:
00808       DAL->AddFlagArg(A,
00809                    Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
00810       break;
00811 
00812     case options::OPT_fpascal_strings:
00813       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
00814       break;
00815 
00816     case options::OPT_fno_pascal_strings:
00817       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
00818       break;
00819     }
00820   }
00821 
00822   if (getTriple().getArch() == llvm::Triple::x86 ||
00823       getTriple().getArch() == llvm::Triple::x86_64)
00824     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
00825       DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2");
00826 
00827   // Add the arch options based on the particular spelling of -arch, to match
00828   // how the driver driver works.
00829   if (BoundArch) {
00830     StringRef Name = BoundArch;
00831     const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ);
00832     const Option *MArch = Opts.getOption(options::OPT_march_EQ);
00833 
00834     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
00835     // which defines the list of which architectures we accept.
00836     if (Name == "ppc")
00837       ;
00838     else if (Name == "ppc601")
00839       DAL->AddJoinedArg(0, MCpu, "601");
00840     else if (Name == "ppc603")
00841       DAL->AddJoinedArg(0, MCpu, "603");
00842     else if (Name == "ppc604")
00843       DAL->AddJoinedArg(0, MCpu, "604");
00844     else if (Name == "ppc604e")
00845       DAL->AddJoinedArg(0, MCpu, "604e");
00846     else if (Name == "ppc750")
00847       DAL->AddJoinedArg(0, MCpu, "750");
00848     else if (Name == "ppc7400")
00849       DAL->AddJoinedArg(0, MCpu, "7400");
00850     else if (Name == "ppc7450")
00851       DAL->AddJoinedArg(0, MCpu, "7450");
00852     else if (Name == "ppc970")
00853       DAL->AddJoinedArg(0, MCpu, "970");
00854 
00855     else if (Name == "ppc64")
00856       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
00857 
00858     else if (Name == "i386")
00859       ;
00860     else if (Name == "i486")
00861       DAL->AddJoinedArg(0, MArch, "i486");
00862     else if (Name == "i586")
00863       DAL->AddJoinedArg(0, MArch, "i586");
00864     else if (Name == "i686")
00865       DAL->AddJoinedArg(0, MArch, "i686");
00866     else if (Name == "pentium")
00867       DAL->AddJoinedArg(0, MArch, "pentium");
00868     else if (Name == "pentium2")
00869       DAL->AddJoinedArg(0, MArch, "pentium2");
00870     else if (Name == "pentpro")
00871       DAL->AddJoinedArg(0, MArch, "pentiumpro");
00872     else if (Name == "pentIIm3")
00873       DAL->AddJoinedArg(0, MArch, "pentium2");
00874 
00875     else if (Name == "x86_64")
00876       DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64));
00877 
00878     else if (Name == "arm")
00879       DAL->AddJoinedArg(0, MArch, "armv4t");
00880     else if (Name == "armv4t")
00881       DAL->AddJoinedArg(0, MArch, "armv4t");
00882     else if (Name == "armv5")
00883       DAL->AddJoinedArg(0, MArch, "armv5tej");
00884     else if (Name == "xscale")
00885       DAL->AddJoinedArg(0, MArch, "xscale");
00886     else if (Name == "armv6")
00887       DAL->AddJoinedArg(0, MArch, "armv6k");
00888     else if (Name == "armv7")
00889       DAL->AddJoinedArg(0, MArch, "armv7a");
00890 
00891     else
00892       llvm_unreachable("invalid Darwin arch");
00893   }
00894 
00895   // Add an explicit version min argument for the deployment target. We do this
00896   // after argument translation because -Xarch_ arguments may add a version min
00897   // argument.
00898   if (BoundArch)
00899     AddDeploymentTarget(*DAL);
00900 
00901   // Validate the C++ standard library choice.
00902   CXXStdlibType Type = GetCXXStdlibType(*DAL);
00903   if (Type == ToolChain::CST_Libcxx) {
00904     switch (LibCXXForSimulator) {
00905     case LibCXXSimulator_None:
00906       // Handle non-simulator cases.
00907       if (isTargetIPhoneOS()) {
00908         if (isIPhoneOSVersionLT(5, 0)) {
00909           getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
00910             << "iOS 5.0";
00911         }
00912       }
00913       break;
00914     case LibCXXSimulator_NotAvailable:
00915       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment)
00916         << "iOS 5.0";
00917       break;
00918     case LibCXXSimulator_Available:
00919       break;
00920     }
00921   }
00922 
00923   return DAL;
00924 }
00925 
00926 bool Darwin::IsUnwindTablesDefault() const {
00927   // FIXME: Gross; we should probably have some separate target
00928   // definition, possibly even reusing the one in clang.
00929   return getArchName() == "x86_64";
00930 }
00931 
00932 bool Darwin::UseDwarfDebugFlags() const {
00933   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
00934     return S[0] != '\0';
00935   return false;
00936 }
00937 
00938 bool Darwin::UseSjLjExceptions() const {
00939   // Darwin uses SjLj exceptions on ARM.
00940   return (getTriple().getArch() == llvm::Triple::arm ||
00941           getTriple().getArch() == llvm::Triple::thumb);
00942 }
00943 
00944 const char *Darwin::GetDefaultRelocationModel() const {
00945   return "pic";
00946 }
00947 
00948 const char *Darwin::GetForcedPicModel() const {
00949   if (getArchName() == "x86_64")
00950     return "pic";
00951   return 0;
00952 }
00953 
00954 bool Darwin::SupportsProfiling() const {
00955   // Profiling instrumentation is only supported on x86.
00956   return getArchName() == "i386" || getArchName() == "x86_64";
00957 }
00958 
00959 bool Darwin::SupportsObjCGC() const {
00960   // Garbage collection is supported everywhere except on iPhone OS.
00961   return !isTargetIPhoneOS();
00962 }
00963 
00964 bool Darwin::SupportsObjCARC() const {
00965   return isTargetIPhoneOS() || !isMacosxVersionLT(10, 6);
00966 }
00967 
00968 std::string
00969 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
00970                                                 types::ID InputType) const {
00971   return ComputeLLVMTriple(Args, InputType);
00972 }
00973 
00974 /// Generic_GCC - A tool chain using the 'gcc' command to perform
00975 /// all subcommands; this relies on gcc translating the majority of
00976 /// command line options.
00977 
00978 /// \brief Parse a GCCVersion object out of a string of text.
00979 ///
00980 /// This is the primary means of forming GCCVersion objects.
00981 /*static*/
00982 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
00983   const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" };
00984   std::pair<StringRef, StringRef> First = VersionText.split('.');
00985   std::pair<StringRef, StringRef> Second = First.second.split('.');
00986 
00987   GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" };
00988   if (First.first.getAsInteger(10, GoodVersion.Major) ||
00989       GoodVersion.Major < 0)
00990     return BadVersion;
00991   if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
00992       GoodVersion.Minor < 0)
00993     return BadVersion;
00994 
00995   // First look for a number prefix and parse that if present. Otherwise just
00996   // stash the entire patch string in the suffix, and leave the number
00997   // unspecified. This covers versions strings such as:
00998   //   4.4
00999   //   4.4.0
01000   //   4.4.x
01001   //   4.4.2-rc4
01002   //   4.4.x-patched
01003   // And retains any patch number it finds.
01004   StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
01005   if (!PatchText.empty()) {
01006     if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) {
01007       // Try to parse the number and any suffix.
01008       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
01009           GoodVersion.Patch < 0)
01010         return BadVersion;
01011       GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str();
01012     }
01013   }
01014 
01015   return GoodVersion;
01016 }
01017 
01018 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
01019 bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
01020   if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
01021   if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
01022 
01023   // Note that we rank versions with *no* patch specified is better than ones
01024   // hard-coding a patch version. Thus if the RHS has no patch, it always
01025   // wins, and the LHS only wins if it has no patch and the RHS does have
01026   // a patch.
01027   if (RHS.Patch == -1) return true;   if (Patch == -1) return false;
01028   if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
01029   if (PatchSuffix == RHS.PatchSuffix) return false;
01030 
01031   // Finally, between completely tied version numbers, the version with the
01032   // suffix loses as we prefer full releases.
01033   if (RHS.PatchSuffix.empty()) return true;
01034   return false;
01035 }
01036 
01037 static StringRef getGCCToolchainDir(const ArgList &Args) {
01038   const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
01039   if (A)
01040     return A->getValue(Args);
01041   return GCC_INSTALL_PREFIX;
01042 }
01043 
01044 /// \brief Construct a GCCInstallationDetector from the driver.
01045 ///
01046 /// This performs all of the autodetection and sets up the various paths.
01047 /// Once constructed, a GCCInstallationDetector is essentially immutable.
01048 ///
01049 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
01050 /// should instead pull the target out of the driver. This is currently
01051 /// necessary because the driver doesn't store the final version of the target
01052 /// triple.
01053 Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
01054     const Driver &D,
01055     const llvm::Triple &TargetTriple,
01056     const ArgList &Args)
01057     : IsValid(false) {
01058   llvm::Triple MultiarchTriple
01059     = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
01060                                  : TargetTriple.get32BitArchVariant();
01061   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
01062   // The library directories which may contain GCC installations.
01063   SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
01064   // The compatible GCC triples for this particular architecture.
01065   SmallVector<StringRef, 10> CandidateTripleAliases;
01066   SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
01067   CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
01068                            CandidateTripleAliases,
01069                            CandidateMultiarchLibDirs,
01070                            CandidateMultiarchTripleAliases);
01071 
01072   // Compute the set of prefixes for our search.
01073   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
01074                                        D.PrefixDirs.end());
01075 
01076   StringRef GCCToolchainDir = getGCCToolchainDir(Args);
01077   if (GCCToolchainDir != "") {
01078     if (GCCToolchainDir.back() == '/')
01079       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
01080 
01081     Prefixes.push_back(GCCToolchainDir);
01082   } else {
01083     Prefixes.push_back(D.SysRoot);
01084     Prefixes.push_back(D.SysRoot + "/usr");
01085     Prefixes.push_back(D.InstalledDir + "/..");
01086   }
01087 
01088   // Loop over the various components which exist and select the best GCC
01089   // installation available. GCC installs are ranked by version number.
01090   Version = GCCVersion::Parse("0.0.0");
01091   for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) {
01092     if (!llvm::sys::fs::exists(Prefixes[i]))
01093       continue;
01094     for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) {
01095       const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str();
01096       if (!llvm::sys::fs::exists(LibDir))
01097         continue;
01098       for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k)
01099         ScanLibDirForGCCTriple(TargetArch, LibDir, CandidateTripleAliases[k]);
01100     }
01101     for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) {
01102       const std::string LibDir
01103         = Prefixes[i] + CandidateMultiarchLibDirs[j].str();
01104       if (!llvm::sys::fs::exists(LibDir))
01105         continue;
01106       for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke;
01107            ++k)
01108         ScanLibDirForGCCTriple(TargetArch, LibDir,
01109                                CandidateMultiarchTripleAliases[k],
01110                                /*NeedsMultiarchSuffix=*/true);
01111     }
01112   }
01113 }
01114 
01115 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
01116     const llvm::Triple &TargetTriple,
01117     const llvm::Triple &MultiarchTriple,
01118     SmallVectorImpl<StringRef> &LibDirs,
01119     SmallVectorImpl<StringRef> &TripleAliases,
01120     SmallVectorImpl<StringRef> &MultiarchLibDirs,
01121     SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
01122   // Declare a bunch of static data sets that we'll select between below. These
01123   // are specifically designed to always refer to string literals to avoid any
01124   // lifetime or initialization issues.
01125   static const char *const ARMLibDirs[] = { "/lib" };
01126   static const char *const ARMTriples[] = {
01127     "arm-linux-gnueabi",
01128     "arm-linux-androideabi"
01129   };
01130 
01131   static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
01132   static const char *const X86_64Triples[] = {
01133     "x86_64-linux-gnu",
01134     "x86_64-unknown-linux-gnu",
01135     "x86_64-pc-linux-gnu",
01136     "x86_64-redhat-linux6E",
01137     "x86_64-redhat-linux",
01138     "x86_64-suse-linux",
01139     "x86_64-manbo-linux-gnu",
01140     "x86_64-linux-gnu",
01141     "x86_64-slackware-linux"
01142   };
01143   static const char *const X86LibDirs[] = { "/lib32", "/lib" };
01144   static const char *const X86Triples[] = {
01145     "i686-linux-gnu",
01146     "i686-pc-linux-gnu",
01147     "i486-linux-gnu",
01148     "i386-linux-gnu",
01149     "i686-redhat-linux",
01150     "i586-redhat-linux",
01151     "i386-redhat-linux",
01152     "i586-suse-linux",
01153     "i486-slackware-linux",
01154     "i686-montavista-linux"
01155   };
01156 
01157   static const char *const MIPSLibDirs[] = { "/lib" };
01158   static const char *const MIPSTriples[] = { "mips-linux-gnu" };
01159   static const char *const MIPSELLibDirs[] = { "/lib" };
01160   static const char *const MIPSELTriples[] = { "mipsel-linux-gnu" };
01161 
01162   static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
01163   static const char *const MIPS64Triples[] = { "mips64-linux-gnu" };
01164   static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" };
01165   static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" };
01166 
01167   static const char *const PPCLibDirs[] = { "/lib32", "/lib" };
01168   static const char *const PPCTriples[] = {
01169     "powerpc-linux-gnu",
01170     "powerpc-unknown-linux-gnu",
01171     "powerpc-suse-linux",
01172     "powerpc-montavista-linuxspe"
01173   };
01174   static const char *const PPC64LibDirs[] = { "/lib64", "/lib" };
01175   static const char *const PPC64Triples[] = {
01176     "powerpc64-linux-gnu",
01177     "powerpc64-unknown-linux-gnu",
01178     "powerpc64-suse-linux",
01179     "ppc64-redhat-linux"
01180   };
01181 
01182   switch (TargetTriple.getArch()) {
01183   case llvm::Triple::arm:
01184   case llvm::Triple::thumb:
01185     LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs));
01186     TripleAliases.append(
01187       ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
01188     break;
01189   case llvm::Triple::x86_64:
01190     LibDirs.append(
01191       X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
01192     TripleAliases.append(
01193       X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
01194     MultiarchLibDirs.append(
01195       X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
01196     MultiarchTripleAliases.append(
01197       X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
01198     break;
01199   case llvm::Triple::x86:
01200     LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
01201     TripleAliases.append(
01202       X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
01203     MultiarchLibDirs.append(
01204       X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
01205     MultiarchTripleAliases.append(
01206       X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
01207     break;
01208   case llvm::Triple::mips:
01209     LibDirs.append(
01210       MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
01211     TripleAliases.append(
01212       MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
01213     MultiarchLibDirs.append(
01214       MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
01215     MultiarchTripleAliases.append(
01216       MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
01217     break;
01218   case llvm::Triple::mipsel:
01219     LibDirs.append(
01220       MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
01221     TripleAliases.append(
01222       MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
01223     MultiarchLibDirs.append(
01224       MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
01225     MultiarchTripleAliases.append(
01226       MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
01227     break;
01228   case llvm::Triple::mips64:
01229     LibDirs.append(
01230       MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs));
01231     TripleAliases.append(
01232       MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples));
01233     MultiarchLibDirs.append(
01234       MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
01235     MultiarchTripleAliases.append(
01236       MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
01237     break;
01238   case llvm::Triple::mips64el:
01239     LibDirs.append(
01240       MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs));
01241     TripleAliases.append(
01242       MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples));
01243     MultiarchLibDirs.append(
01244       MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
01245     MultiarchTripleAliases.append(
01246       MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
01247     break;
01248   case llvm::Triple::ppc:
01249     LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
01250     TripleAliases.append(
01251       PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
01252     MultiarchLibDirs.append(
01253       PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
01254     MultiarchTripleAliases.append(
01255       PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
01256     break;
01257   case llvm::Triple::ppc64:
01258     LibDirs.append(
01259       PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
01260     TripleAliases.append(
01261       PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
01262     MultiarchLibDirs.append(
01263       PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
01264     MultiarchTripleAliases.append(
01265       PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
01266     break;
01267 
01268   default:
01269     // By default, just rely on the standard lib directories and the original
01270     // triple.
01271     break;
01272   }
01273 
01274   // Always append the drivers target triple to the end, in case it doesn't
01275   // match any of our aliases.
01276   TripleAliases.push_back(TargetTriple.str());
01277 
01278   // Also include the multiarch variant if it's different.
01279   if (TargetTriple.str() != MultiarchTriple.str())
01280     MultiarchTripleAliases.push_back(MultiarchTriple.str());
01281 }
01282 
01283 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
01284     llvm::Triple::ArchType TargetArch, const std::string &LibDir,
01285     StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
01286   // There are various different suffixes involving the triple we
01287   // check for. We also record what is necessary to walk from each back
01288   // up to the lib directory.
01289   const std::string LibSuffixes[] = {
01290     "/gcc/" + CandidateTriple.str(),
01291     "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
01292 
01293     // Ubuntu has a strange mis-matched pair of triples that this happens to
01294     // match.
01295     // FIXME: It may be worthwhile to generalize this and look for a second
01296     // triple.
01297     "/i386-linux-gnu/gcc/" + CandidateTriple.str()
01298   };
01299   const std::string InstallSuffixes[] = {
01300     "/../../..",
01301     "/../../../..",
01302     "/../../../.."
01303   };
01304   // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
01305   const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) -
01306                                    (TargetArch != llvm::Triple::x86));
01307   for (unsigned i = 0; i < NumLibSuffixes; ++i) {
01308     StringRef LibSuffix = LibSuffixes[i];
01309     llvm::error_code EC;
01310     for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
01311          !EC && LI != LE; LI = LI.increment(EC)) {
01312       StringRef VersionText = llvm::sys::path::filename(LI->path());
01313       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
01314       static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" };
01315       if (CandidateVersion < MinVersion)
01316         continue;
01317       if (CandidateVersion <= Version)
01318         continue;
01319 
01320       // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
01321       // in what would normally be GCCInstallPath and put the 64-bit
01322       // libs in a subdirectory named 64. The simple logic we follow is that
01323       // *if* there is a subdirectory of the right name with crtbegin.o in it,
01324       // we use that. If not, and if not a multiarch triple, we look for
01325       // crtbegin.o without the subdirectory.
01326       StringRef MultiarchSuffix
01327         = (TargetArch == llvm::Triple::x86_64 ||
01328            TargetArch == llvm::Triple::ppc64 ||
01329            TargetArch == llvm::Triple::mips64 ||
01330            TargetArch == llvm::Triple::mips64el) ? "/64" : "/32";
01331       if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
01332         GCCMultiarchSuffix = MultiarchSuffix.str();
01333       } else {
01334         if (NeedsMultiarchSuffix ||
01335             !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
01336           continue;
01337         GCCMultiarchSuffix.clear();
01338       }
01339 
01340       Version = CandidateVersion;
01341       GCCTriple.setTriple(CandidateTriple);
01342       // FIXME: We hack together the directory name here instead of
01343       // using LI to ensure stable path separators across Windows and
01344       // Linux.
01345       GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str();
01346       GCCParentLibPath = GCCInstallPath + InstallSuffixes[i];
01347       IsValid = true;
01348     }
01349   }
01350 }
01351 
01352 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
01353                          const ArgList &Args)
01354   : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
01355   getProgramPaths().push_back(getDriver().getInstalledDir());
01356   if (getDriver().getInstalledDir() != getDriver().Dir)
01357     getProgramPaths().push_back(getDriver().Dir);
01358 }
01359 
01360 Generic_GCC::~Generic_GCC() {
01361   // Free tool implementations.
01362   for (llvm::DenseMap<unsigned, Tool*>::iterator
01363          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
01364     delete it->second;
01365 }
01366 
01367 Tool &Generic_GCC::SelectTool(const Compilation &C,
01368                               const JobAction &JA,
01369                               const ActionList &Inputs) const {
01370   Action::ActionClass Key;
01371   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01372     Key = Action::AnalyzeJobClass;
01373   else
01374     Key = JA.getKind();
01375 
01376   Tool *&T = Tools[Key];
01377   if (!T) {
01378     switch (Key) {
01379     case Action::InputClass:
01380     case Action::BindArchClass:
01381       llvm_unreachable("Invalid tool kind.");
01382     case Action::PreprocessJobClass:
01383       T = new tools::gcc::Preprocess(*this); break;
01384     case Action::PrecompileJobClass:
01385       T = new tools::gcc::Precompile(*this); break;
01386     case Action::AnalyzeJobClass:
01387     case Action::MigrateJobClass:
01388       T = new tools::Clang(*this); break;
01389     case Action::CompileJobClass:
01390       T = new tools::gcc::Compile(*this); break;
01391     case Action::AssembleJobClass:
01392       T = new tools::gcc::Assemble(*this); break;
01393     case Action::LinkJobClass:
01394       T = new tools::gcc::Link(*this); break;
01395 
01396       // This is a bit ungeneric, but the only platform using a driver
01397       // driver is Darwin.
01398     case Action::LipoJobClass:
01399       T = new tools::darwin::Lipo(*this); break;
01400     case Action::DsymutilJobClass:
01401       T = new tools::darwin::Dsymutil(*this); break;
01402     case Action::VerifyJobClass:
01403       T = new tools::darwin::VerifyDebug(*this); break;
01404     }
01405   }
01406 
01407   return *T;
01408 }
01409 
01410 bool Generic_GCC::IsUnwindTablesDefault() const {
01411   // FIXME: Gross; we should probably have some separate target
01412   // definition, possibly even reusing the one in clang.
01413   return getArchName() == "x86_64";
01414 }
01415 
01416 const char *Generic_GCC::GetDefaultRelocationModel() const {
01417   return "static";
01418 }
01419 
01420 const char *Generic_GCC::GetForcedPicModel() const {
01421   return 0;
01422 }
01423 /// Hexagon Toolchain
01424 
01425 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple)
01426   : ToolChain(D, Triple) {
01427   getProgramPaths().push_back(getDriver().getInstalledDir());
01428   if (getDriver().getInstalledDir() != getDriver().Dir.c_str())
01429     getProgramPaths().push_back(getDriver().Dir);
01430 }
01431 
01432 Hexagon_TC::~Hexagon_TC() {
01433   // Free tool implementations.
01434   for (llvm::DenseMap<unsigned, Tool*>::iterator
01435          it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
01436     delete it->second;
01437 }
01438 
01439 Tool &Hexagon_TC::SelectTool(const Compilation &C,
01440                              const JobAction &JA,
01441                              const ActionList &Inputs) const {
01442   Action::ActionClass Key;
01443   //   if (JA.getKind () == Action::CompileJobClass)
01444   //     Key = JA.getKind ();
01445   //     else
01446 
01447   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01448     Key = Action::AnalyzeJobClass;
01449   else
01450     Key = JA.getKind();
01451   //   if ((JA.getKind () == Action::CompileJobClass)
01452   //     && (JA.getType () != types::TY_LTO_BC)) {
01453   //     Key = JA.getKind ();
01454   //   }
01455 
01456   Tool *&T = Tools[Key];
01457   if (!T) {
01458     switch (Key) {
01459     case Action::InputClass:
01460     case Action::BindArchClass:
01461       assert(0 && "Invalid tool kind.");
01462     case Action::AnalyzeJobClass:
01463       T = new tools::Clang(*this); break;
01464     case Action::AssembleJobClass:
01465       T = new tools::hexagon::Assemble(*this); break;
01466     case Action::LinkJobClass:
01467       T = new tools::hexagon::Link(*this); break;
01468     default:
01469       assert(false && "Unsupported action for Hexagon target.");
01470     }
01471   }
01472 
01473   return *T;
01474 }
01475 
01476 bool Hexagon_TC::IsUnwindTablesDefault() const {
01477   // FIXME: Gross; we should probably have some separate target
01478   // definition, possibly even reusing the one in clang.
01479   return getArchName() == "x86_64";
01480 }
01481 
01482 const char *Hexagon_TC::GetDefaultRelocationModel() const {
01483   return "static";
01484 }
01485 
01486 const char *Hexagon_TC::GetForcedPicModel() const {
01487   return 0;
01488 } // End Hexagon
01489 
01490 
01491 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
01492 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
01493 /// Currently does not support anything else but compilation.
01494 
01495 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
01496   : ToolChain(D, Triple) {
01497   // Path mangling to find libexec
01498   std::string Path(getDriver().Dir);
01499 
01500   Path += "/../libexec";
01501   getProgramPaths().push_back(Path);
01502 }
01503 
01504 TCEToolChain::~TCEToolChain() {
01505   for (llvm::DenseMap<unsigned, Tool*>::iterator
01506            it = Tools.begin(), ie = Tools.end(); it != ie; ++it)
01507       delete it->second;
01508 }
01509 
01510 bool TCEToolChain::IsMathErrnoDefault() const {
01511   return true;
01512 }
01513 
01514 bool TCEToolChain::IsUnwindTablesDefault() const {
01515   return false;
01516 }
01517 
01518 const char *TCEToolChain::GetDefaultRelocationModel() const {
01519   return "static";
01520 }
01521 
01522 const char *TCEToolChain::GetForcedPicModel() const {
01523   return 0;
01524 }
01525 
01526 Tool &TCEToolChain::SelectTool(const Compilation &C,
01527                             const JobAction &JA,
01528                                const ActionList &Inputs) const {
01529   Action::ActionClass Key;
01530   Key = Action::AnalyzeJobClass;
01531 
01532   Tool *&T = Tools[Key];
01533   if (!T) {
01534     switch (Key) {
01535     case Action::PreprocessJobClass:
01536       T = new tools::gcc::Preprocess(*this); break;
01537     case Action::AnalyzeJobClass:
01538       T = new tools::Clang(*this); break;
01539     default:
01540      llvm_unreachable("Unsupported action for TCE target.");
01541     }
01542   }
01543   return *T;
01544 }
01545 
01546 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
01547 
01548 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
01549   : Generic_ELF(D, Triple, Args) {
01550   getFilePaths().push_back(getDriver().Dir + "/../lib");
01551   getFilePaths().push_back("/usr/lib");
01552 }
01553 
01554 Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA,
01555                           const ActionList &Inputs) const {
01556   Action::ActionClass Key;
01557   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01558     Key = Action::AnalyzeJobClass;
01559   else
01560     Key = JA.getKind();
01561 
01562   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
01563                                              options::OPT_no_integrated_as,
01564                                              IsIntegratedAssemblerDefault());
01565 
01566   Tool *&T = Tools[Key];
01567   if (!T) {
01568     switch (Key) {
01569     case Action::AssembleJobClass: {
01570       if (UseIntegratedAs)
01571         T = new tools::ClangAs(*this);
01572       else
01573         T = new tools::openbsd::Assemble(*this);
01574       break;
01575     }
01576     case Action::LinkJobClass:
01577       T = new tools::openbsd::Link(*this); break;
01578     default:
01579       T = &Generic_GCC::SelectTool(C, JA, Inputs);
01580     }
01581   }
01582 
01583   return *T;
01584 }
01585 
01586 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
01587 
01588 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
01589   : Generic_ELF(D, Triple, Args) {
01590 
01591   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
01592   // back to '/usr/lib' if it doesn't exist.
01593   if ((Triple.getArch() == llvm::Triple::x86 ||
01594        Triple.getArch() == llvm::Triple::ppc) &&
01595       llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
01596     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
01597   else
01598     getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
01599 }
01600 
01601 Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
01602                           const ActionList &Inputs) const {
01603   Action::ActionClass Key;
01604   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01605     Key = Action::AnalyzeJobClass;
01606   else
01607     Key = JA.getKind();
01608 
01609   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
01610                                              options::OPT_no_integrated_as,
01611                                              IsIntegratedAssemblerDefault());
01612 
01613   Tool *&T = Tools[Key];
01614   if (!T) {
01615     switch (Key) {
01616     case Action::AssembleJobClass:
01617       if (UseIntegratedAs)
01618         T = new tools::ClangAs(*this);
01619       else
01620         T = new tools::freebsd::Assemble(*this);
01621       break;
01622     case Action::LinkJobClass:
01623       T = new tools::freebsd::Link(*this); break;
01624     default:
01625       T = &Generic_GCC::SelectTool(C, JA, Inputs);
01626     }
01627   }
01628 
01629   return *T;
01630 }
01631 
01632 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
01633 
01634 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
01635   : Generic_ELF(D, Triple, Args) {
01636 
01637   if (getDriver().UseStdLib) {
01638     // When targeting a 32-bit platform, try the special directory used on
01639     // 64-bit hosts, and only fall back to the main library directory if that
01640     // doesn't work.
01641     // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
01642     // what all logic is needed to emulate the '=' prefix here.
01643     if (Triple.getArch() == llvm::Triple::x86)
01644       getFilePaths().push_back("=/usr/lib/i386");
01645 
01646     getFilePaths().push_back("=/usr/lib");
01647   }
01648 }
01649 
01650 Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA,
01651                          const ActionList &Inputs) const {
01652   Action::ActionClass Key;
01653   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01654     Key = Action::AnalyzeJobClass;
01655   else
01656     Key = JA.getKind();
01657 
01658   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
01659                                              options::OPT_no_integrated_as,
01660                                              IsIntegratedAssemblerDefault());
01661 
01662   Tool *&T = Tools[Key];
01663   if (!T) {
01664     switch (Key) {
01665     case Action::AssembleJobClass:
01666       if (UseIntegratedAs)
01667         T = new tools::ClangAs(*this);
01668       else
01669         T = new tools::netbsd::Assemble(*this);
01670       break;
01671     case Action::LinkJobClass:
01672       T = new tools::netbsd::Link(*this);
01673       break;
01674     default:
01675       T = &Generic_GCC::SelectTool(C, JA, Inputs);
01676     }
01677   }
01678 
01679   return *T;
01680 }
01681 
01682 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
01683 
01684 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
01685   : Generic_ELF(D, Triple, Args) {
01686   getFilePaths().push_back(getDriver().Dir + "/../lib");
01687   getFilePaths().push_back("/usr/lib");
01688 }
01689 
01690 Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
01691                         const ActionList &Inputs) const {
01692   Action::ActionClass Key;
01693   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01694     Key = Action::AnalyzeJobClass;
01695   else
01696     Key = JA.getKind();
01697 
01698   Tool *&T = Tools[Key];
01699   if (!T) {
01700     switch (Key) {
01701     case Action::AssembleJobClass:
01702       T = new tools::minix::Assemble(*this); break;
01703     case Action::LinkJobClass:
01704       T = new tools::minix::Link(*this); break;
01705     default:
01706       T = &Generic_GCC::SelectTool(C, JA, Inputs);
01707     }
01708   }
01709 
01710   return *T;
01711 }
01712 
01713 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
01714 
01715 AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
01716                    const ArgList &Args)
01717   : Generic_GCC(D, Triple, Args) {
01718 
01719   getProgramPaths().push_back(getDriver().getInstalledDir());
01720   if (getDriver().getInstalledDir() != getDriver().Dir)
01721     getProgramPaths().push_back(getDriver().Dir);
01722 
01723   getFilePaths().push_back(getDriver().Dir + "/../lib");
01724   getFilePaths().push_back("/usr/lib");
01725   getFilePaths().push_back("/usr/sfw/lib");
01726   getFilePaths().push_back("/opt/gcc4/lib");
01727   getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4");
01728 
01729 }
01730 
01731 Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA,
01732                            const ActionList &Inputs) const {
01733   Action::ActionClass Key;
01734   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01735     Key = Action::AnalyzeJobClass;
01736   else
01737     Key = JA.getKind();
01738 
01739   Tool *&T = Tools[Key];
01740   if (!T) {
01741     switch (Key) {
01742     case Action::AssembleJobClass:
01743       T = new tools::auroraux::Assemble(*this); break;
01744     case Action::LinkJobClass:
01745       T = new tools::auroraux::Link(*this); break;
01746     default:
01747       T = &Generic_GCC::SelectTool(C, JA, Inputs);
01748     }
01749   }
01750 
01751   return *T;
01752 }
01753 
01754 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
01755 
01756 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
01757                  const ArgList &Args)
01758   : Generic_GCC(D, Triple, Args) {
01759 
01760   getProgramPaths().push_back(getDriver().getInstalledDir());
01761   if (getDriver().getInstalledDir() != getDriver().Dir)
01762     getProgramPaths().push_back(getDriver().Dir);
01763 
01764   getFilePaths().push_back(getDriver().Dir + "/../lib");
01765   getFilePaths().push_back("/usr/lib");
01766 }
01767 
01768 Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA,
01769                            const ActionList &Inputs) const {
01770   Action::ActionClass Key;
01771   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
01772     Key = Action::AnalyzeJobClass;
01773   else
01774     Key = JA.getKind();
01775 
01776   Tool *&T = Tools[Key];
01777   if (!T) {
01778     switch (Key) {
01779     case Action::AssembleJobClass:
01780       T = new tools::solaris::Assemble(*this); break;
01781     case Action::LinkJobClass:
01782       T = new tools::solaris::Link(*this); break;
01783     default:
01784       T = &Generic_GCC::SelectTool(C, JA, Inputs);
01785     }
01786   }
01787 
01788   return *T;
01789 }
01790 
01791 /// Linux toolchain (very bare-bones at the moment).
01792 
01793 enum LinuxDistro {
01794   ArchLinux,
01795   DebianLenny,
01796   DebianSqueeze,
01797   DebianWheezy,
01798   Exherbo,
01799   RHEL4,
01800   RHEL5,
01801   RHEL6,
01802   Fedora13,
01803   Fedora14,
01804   Fedora15,
01805   Fedora16,
01806   FedoraRawhide,
01807   OpenSuse11_3,
01808   OpenSuse11_4,
01809   OpenSuse12_1,
01810   OpenSuse12_2,
01811   UbuntuHardy,
01812   UbuntuIntrepid,
01813   UbuntuJaunty,
01814   UbuntuKarmic,
01815   UbuntuLucid,
01816   UbuntuMaverick,
01817   UbuntuNatty,
01818   UbuntuOneiric,
01819   UbuntuPrecise,
01820   UnknownDistro
01821 };
01822 
01823 static bool IsRedhat(enum LinuxDistro Distro) {
01824   return (Distro >= Fedora13 && Distro <= FedoraRawhide) ||
01825          (Distro >= RHEL4    && Distro <= RHEL6);
01826 }
01827 
01828 static bool IsOpenSuse(enum LinuxDistro Distro) {
01829   return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2;
01830 }
01831 
01832 static bool IsDebian(enum LinuxDistro Distro) {
01833   return Distro >= DebianLenny && Distro <= DebianWheezy;
01834 }
01835 
01836 static bool IsUbuntu(enum LinuxDistro Distro) {
01837   return Distro >= UbuntuHardy && Distro <= UbuntuPrecise;
01838 }
01839 
01840 static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
01841   OwningPtr<llvm::MemoryBuffer> File;
01842   if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
01843     StringRef Data = File.get()->getBuffer();
01844     SmallVector<StringRef, 8> Lines;
01845     Data.split(Lines, "\n");
01846     LinuxDistro Version = UnknownDistro;
01847     for (unsigned i = 0, s = Lines.size(); i != s; ++i)
01848       if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME="))
01849         Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
01850           .Case("hardy", UbuntuHardy)
01851           .Case("intrepid", UbuntuIntrepid)
01852           .Case("jaunty", UbuntuJaunty)
01853           .Case("karmic", UbuntuKarmic)
01854           .Case("lucid", UbuntuLucid)
01855           .Case("maverick", UbuntuMaverick)
01856           .Case("natty", UbuntuNatty)
01857           .Case("oneiric", UbuntuOneiric)
01858           .Case("precise", UbuntuPrecise)
01859           .Default(UnknownDistro);
01860     return Version;
01861   }
01862 
01863   if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
01864     StringRef Data = File.get()->getBuffer();
01865     if (Data.startswith("Fedora release 16"))
01866       return Fedora16;
01867     else if (Data.startswith("Fedora release 15"))
01868       return Fedora15;
01869     else if (Data.startswith("Fedora release 14"))
01870       return Fedora14;
01871     else if (Data.startswith("Fedora release 13"))
01872       return Fedora13;
01873     else if (Data.startswith("Fedora release") &&
01874              Data.find("Rawhide") != StringRef::npos)
01875       return FedoraRawhide;
01876     else if (Data.startswith("Red Hat Enterprise Linux") &&
01877              Data.find("release 6") != StringRef::npos)
01878       return RHEL6;
01879     else if ((Data.startswith("Red Hat Enterprise Linux") ||
01880         Data.startswith("CentOS")) &&
01881              Data.find("release 5") != StringRef::npos)
01882       return RHEL5;
01883     else if ((Data.startswith("Red Hat Enterprise Linux") ||
01884         Data.startswith("CentOS")) &&
01885              Data.find("release 4") != StringRef::npos)
01886       return RHEL4;
01887     return UnknownDistro;
01888   }
01889 
01890   if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) {
01891     StringRef Data = File.get()->getBuffer();
01892     if (Data[0] == '5')
01893       return DebianLenny;
01894     else if (Data.startswith("squeeze/sid") || Data[0] == '6')
01895       return DebianSqueeze;
01896     else if (Data.startswith("wheezy/sid")  || Data[0] == '7')
01897       return DebianWheezy;
01898     return UnknownDistro;
01899   }
01900 
01901   if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
01902     return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
01903       .StartsWith("openSUSE 11.3", OpenSuse11_3)
01904       .StartsWith("openSUSE 11.4", OpenSuse11_4)
01905       .StartsWith("openSUSE 12.1", OpenSuse12_1)
01906       .StartsWith("openSUSE 12.2", OpenSuse12_2)
01907       .Default(UnknownDistro);
01908 
01909   bool Exists;
01910   if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
01911     return Exherbo;
01912 
01913   if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists)
01914     return ArchLinux;
01915 
01916   return UnknownDistro;
01917 }
01918 
01919 /// \brief Get our best guess at the multiarch triple for a target.
01920 ///
01921 /// Debian-based systems are starting to use a multiarch setup where they use
01922 /// a target-triple directory in the library and header search paths.
01923 /// Unfortunately, this triple does not align with the vanilla target triple,
01924 /// so we provide a rough mapping here.
01925 static std::string getMultiarchTriple(const llvm::Triple TargetTriple,
01926                                       StringRef SysRoot) {
01927   // For most architectures, just use whatever we have rather than trying to be
01928   // clever.
01929   switch (TargetTriple.getArch()) {
01930   default:
01931     return TargetTriple.str();
01932 
01933     // We use the existence of '/lib/<triple>' as a directory to detect some
01934     // common linux triples that don't quite match the Clang triple for both
01935     // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
01936     // regardless of what the actual target triple is.
01937   case llvm::Triple::x86:
01938     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
01939       return "i386-linux-gnu";
01940     return TargetTriple.str();
01941   case llvm::Triple::x86_64:
01942     if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
01943       return "x86_64-linux-gnu";
01944     return TargetTriple.str();
01945   case llvm::Triple::mips:
01946     if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
01947       return "mips-linux-gnu";
01948     return TargetTriple.str();
01949   case llvm::Triple::mipsel:
01950     if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
01951       return "mipsel-linux-gnu";
01952     return TargetTriple.str();
01953   case llvm::Triple::ppc:
01954     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
01955       return "powerpc-linux-gnu";
01956     return TargetTriple.str();
01957   case llvm::Triple::ppc64:
01958     if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
01959       return "powerpc64-linux-gnu";
01960     return TargetTriple.str();
01961   }
01962 }
01963 
01964 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
01965   if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
01966 }
01967 
01968 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
01969   : Generic_ELF(D, Triple, Args) {
01970   llvm::Triple::ArchType Arch = Triple.getArch();
01971   const std::string &SysRoot = getDriver().SysRoot;
01972 
01973   // OpenSuse stores the linker with the compiler, add that to the search
01974   // path.
01975   ToolChain::path_list &PPaths = getProgramPaths();
01976   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
01977                          GCCInstallation.getTriple().str() + "/bin").str());
01978 
01979   Linker = GetProgramPath("ld");
01980 
01981   LinuxDistro Distro = DetectLinuxDistro(Arch);
01982 
01983   if (IsOpenSuse(Distro) || IsUbuntu(Distro)) {
01984     ExtraOpts.push_back("-z");
01985     ExtraOpts.push_back("relro");
01986   }
01987 
01988   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
01989     ExtraOpts.push_back("-X");
01990 
01991   const bool IsMips = Arch == llvm::Triple::mips ||
01992                       Arch == llvm::Triple::mipsel ||
01993                       Arch == llvm::Triple::mips64 ||
01994                       Arch == llvm::Triple::mips64el;
01995 
01996   const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::ANDROIDEABI;
01997 
01998   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
01999   // and the MIPS ABI require .dynsym to be sorted in different ways.
02000   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
02001   // ABI requires a mapping between the GOT and the symbol table.
02002   // Android loader does not support .gnu.hash.
02003   if (!IsMips && !IsAndroid) {
02004     if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
02005         (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
02006       ExtraOpts.push_back("--hash-style=gnu");
02007 
02008     if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid ||
02009         Distro == UbuntuJaunty || Distro == UbuntuKarmic)
02010       ExtraOpts.push_back("--hash-style=both");
02011   }
02012 
02013   if (IsRedhat(Distro))
02014     ExtraOpts.push_back("--no-add-needed");
02015 
02016   if (Distro == DebianSqueeze || Distro == DebianWheezy ||
02017       IsOpenSuse(Distro) ||
02018       (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
02019       (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
02020     ExtraOpts.push_back("--build-id");
02021 
02022   if (IsOpenSuse(Distro))
02023     ExtraOpts.push_back("--enable-new-dtags");
02024 
02025   // The selection of paths to try here is designed to match the patterns which
02026   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
02027   // This was determined by running GCC in a fake filesystem, creating all
02028   // possible permutations of these directories, and seeing which ones it added
02029   // to the link paths.
02030   path_list &Paths = getFilePaths();
02031 
02032   const std::string Multilib = Triple.isArch32Bit() ? "lib32" : "lib64";
02033   const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot);
02034 
02035   // Add the multilib suffixed paths where they are available.
02036   if (GCCInstallation.isValid()) {
02037     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
02038     const std::string &LibPath = GCCInstallation.getParentLibPath();
02039     addPathIfExists((GCCInstallation.getInstallPath() +
02040                      GCCInstallation.getMultiarchSuffix()),
02041                     Paths);
02042 
02043     // If the GCC installation we found is inside of the sysroot, we want to
02044     // prefer libraries installed in the parent prefix of the GCC installation.
02045     // It is important to *not* use these paths when the GCC installation is
02046     // outside of the system root as that can pick up unintended libraries.
02047     // This usually happens when there is an external cross compiler on the
02048     // host system, and a more minimal sysroot available that is the target of
02049     // the cross.
02050     if (StringRef(LibPath).startswith(SysRoot)) {
02051       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib,
02052                       Paths);
02053       addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
02054       addPathIfExists(LibPath + "/../" + Multilib, Paths);
02055     }
02056   }
02057   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
02058   addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
02059   addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
02060   addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths);
02061 
02062   // Try walking via the GCC triple path in case of multiarch GCC
02063   // installations with strange symlinks.
02064   if (GCCInstallation.isValid())
02065     addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
02066                     "/../../" + Multilib, Paths);
02067 
02068   // Add the non-multilib suffixed paths (if potentially different).
02069   if (GCCInstallation.isValid()) {
02070     const std::string &LibPath = GCCInstallation.getParentLibPath();
02071     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
02072     if (!GCCInstallation.getMultiarchSuffix().empty())
02073       addPathIfExists(GCCInstallation.getInstallPath(), Paths);
02074 
02075     if (StringRef(LibPath).startswith(SysRoot)) {
02076       addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
02077       addPathIfExists(LibPath, Paths);
02078     }
02079   }
02080   addPathIfExists(SysRoot + "/lib", Paths);
02081   addPathIfExists(SysRoot + "/usr/lib", Paths);
02082 }
02083 
02084 bool Linux::HasNativeLLVMSupport() const {
02085   return true;
02086 }
02087 
02088 Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA,
02089                         const ActionList &Inputs) const {
02090   Action::ActionClass Key;
02091   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
02092     Key = Action::AnalyzeJobClass;
02093   else
02094     Key = JA.getKind();
02095 
02096   bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as,
02097                                              options::OPT_no_integrated_as,
02098                                              IsIntegratedAssemblerDefault());
02099 
02100   Tool *&T = Tools[Key];
02101   if (!T) {
02102     switch (Key) {
02103     case Action::AssembleJobClass:
02104       if (UseIntegratedAs)
02105         T = new tools::ClangAs(*this);
02106       else
02107         T = new tools::linuxtools::Assemble(*this);
02108       break;
02109     case Action::LinkJobClass:
02110       T = new tools::linuxtools::Link(*this); break;
02111     default:
02112       T = &Generic_GCC::SelectTool(C, JA, Inputs);
02113     }
02114   }
02115 
02116   return *T;
02117 }
02118 
02119 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
02120                                       ArgStringList &CC1Args) const {
02121   const Driver &D = getDriver();
02122 
02123   if (DriverArgs.hasArg(options::OPT_nostdinc))
02124     return;
02125 
02126   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
02127     addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
02128 
02129   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
02130     llvm::sys::Path P(D.ResourceDir);
02131     P.appendComponent("include");
02132     addSystemInclude(DriverArgs, CC1Args, P.str());
02133   }
02134 
02135   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
02136     return;
02137 
02138   // Check for configure-time C include directories.
02139   StringRef CIncludeDirs(C_INCLUDE_DIRS);
02140   if (CIncludeDirs != "") {
02141     SmallVector<StringRef, 5> dirs;
02142     CIncludeDirs.split(dirs, ":");
02143     for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
02144          I != E; ++I) {
02145       StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
02146       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
02147     }
02148     return;
02149   }
02150 
02151   // Lacking those, try to detect the correct set of system includes for the
02152   // target triple.
02153 
02154   // Implement generic Debian multiarch support.
02155   const StringRef X86_64MultiarchIncludeDirs[] = {
02156     "/usr/include/x86_64-linux-gnu",
02157 
02158     // FIXME: These are older forms of multiarch. It's not clear that they're
02159     // in use in any released version of Debian, so we should consider
02160     // removing them.
02161     "/usr/include/i686-linux-gnu/64",
02162     "/usr/include/i486-linux-gnu/64"
02163   };
02164   const StringRef X86MultiarchIncludeDirs[] = {
02165     "/usr/include/i386-linux-gnu",
02166 
02167     // FIXME: These are older forms of multiarch. It's not clear that they're
02168     // in use in any released version of Debian, so we should consider
02169     // removing them.
02170     "/usr/include/x86_64-linux-gnu/32",
02171     "/usr/include/i686-linux-gnu",
02172     "/usr/include/i486-linux-gnu"
02173   };
02174   const StringRef ARMMultiarchIncludeDirs[] = {
02175     "/usr/include/arm-linux-gnueabi"
02176   };
02177   const StringRef MIPSMultiarchIncludeDirs[] = {
02178     "/usr/include/mips-linux-gnu"
02179   };
02180   const StringRef MIPSELMultiarchIncludeDirs[] = {
02181     "/usr/include/mipsel-linux-gnu"
02182   };
02183   const StringRef PPCMultiarchIncludeDirs[] = {
02184     "/usr/include/powerpc-linux-gnu"
02185   };
02186   const StringRef PPC64MultiarchIncludeDirs[] = {
02187     "/usr/include/powerpc64-linux-gnu"
02188   };
02189   ArrayRef<StringRef> MultiarchIncludeDirs;
02190   if (getTriple().getArch() == llvm::Triple::x86_64) {
02191     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
02192   } else if (getTriple().getArch() == llvm::Triple::x86) {
02193     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
02194   } else if (getTriple().getArch() == llvm::Triple::arm) {
02195     MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
02196   } else if (getTriple().getArch() == llvm::Triple::mips) {
02197     MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
02198   } else if (getTriple().getArch() == llvm::Triple::mipsel) {
02199     MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
02200   } else if (getTriple().getArch() == llvm::Triple::ppc) {
02201     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
02202   } else if (getTriple().getArch() == llvm::Triple::ppc64) {
02203     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
02204   }
02205   for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
02206                                      E = MultiarchIncludeDirs.end();
02207        I != E; ++I) {
02208     if (llvm::sys::fs::exists(D.SysRoot + *I)) {
02209       addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
02210       break;
02211     }
02212   }
02213 
02214   if (getTriple().getOS() == llvm::Triple::RTEMS)
02215     return;
02216 
02217   // Add an include of '/include' directly. This isn't provided by default by
02218   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
02219   // add even when Clang is acting as-if it were a system compiler.
02220   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
02221 
02222   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
02223 }
02224 
02225 /// \brief Helper to add the thre variant paths for a libstdc++ installation.
02226 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
02227                                                 const ArgList &DriverArgs,
02228                                                 ArgStringList &CC1Args) {
02229   if (!llvm::sys::fs::exists(Base))
02230     return false;
02231   addSystemInclude(DriverArgs, CC1Args, Base);
02232   addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir);
02233   addSystemInclude(DriverArgs, CC1Args, Base + "/backward");
02234   return true;
02235 }
02236 
02237 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
02238                                          ArgStringList &CC1Args) const {
02239   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
02240       DriverArgs.hasArg(options::OPT_nostdincxx))
02241     return;
02242 
02243   // Check if libc++ has been enabled and provide its include paths if so.
02244   if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
02245     // libc++ is always installed at a fixed path on Linux currently.
02246     addSystemInclude(DriverArgs, CC1Args,
02247                      getDriver().SysRoot + "/usr/include/c++/v1");
02248     return;
02249   }
02250 
02251   // We need a detected GCC installation on Linux to provide libstdc++'s
02252   // headers. We handled the libc++ case above.
02253   if (!GCCInstallation.isValid())
02254     return;
02255 
02256   // By default, look for the C++ headers in an include directory adjacent to
02257   // the lib directory of the GCC installation. Note that this is expect to be
02258   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
02259   StringRef LibDir = GCCInstallation.getParentLibPath();
02260   StringRef InstallDir = GCCInstallation.getInstallPath();
02261   StringRef Version = GCCInstallation.getVersion();
02262   if (!addLibStdCXXIncludePaths(LibDir + "/../include/c++/" + Version,
02263                                 (GCCInstallation.getTriple().str() +
02264                                  GCCInstallation.getMultiarchSuffix()),
02265                                 DriverArgs, CC1Args)) {
02266     // Gentoo is weird and places its headers inside the GCC install, so if the
02267     // first attempt to find the headers fails, try this pattern.
02268     addLibStdCXXIncludePaths(InstallDir + "/include/g++-v4",
02269                              (GCCInstallation.getTriple().str() +
02270                               GCCInstallation.getMultiarchSuffix()),
02271                              DriverArgs, CC1Args);
02272   }
02273 }
02274 
02275 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
02276 
02277 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
02278   : Generic_ELF(D, Triple, Args) {
02279 
02280   // Path mangling to find libexec
02281   getProgramPaths().push_back(getDriver().getInstalledDir());
02282   if (getDriver().getInstalledDir() != getDriver().Dir)
02283     getProgramPaths().push_back(getDriver().Dir);
02284 
02285   getFilePaths().push_back(getDriver().Dir + "/../lib");
02286   getFilePaths().push_back("/usr/lib");
02287   getFilePaths().push_back("/usr/lib/gcc41");
02288 }
02289 
02290 Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA,
02291                             const ActionList &Inputs) const {
02292   Action::ActionClass Key;
02293   if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
02294     Key = Action::AnalyzeJobClass;
02295   else
02296     Key = JA.getKind();
02297 
02298   Tool *&T = Tools[Key];
02299   if (!T) {
02300     switch (Key) {
02301     case Action::AssembleJobClass:
02302       T = new tools::dragonfly::Assemble(*this); break;
02303     case Action::LinkJobClass:
02304       T = new tools::dragonfly::Link(*this); break;
02305     default:
02306       T = &Generic_GCC::SelectTool(C, JA, Inputs);
02307     }
02308   }
02309 
02310   return *T;
02311 }