Home | History | Annotate | Download | only in Driver
      1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "Tools.h"
     11 #include "clang/Basic/ObjCRuntime.h"
     12 #include "clang/Driver/Action.h"
     13 #include "clang/Driver/Driver.h"
     14 #include "clang/Driver/DriverDiagnostic.h"
     15 #include "clang/Driver/Options.h"
     16 #include "clang/Driver/ToolChain.h"
     17 #include "llvm/ADT/StringSwitch.h"
     18 #include "llvm/Option/Arg.h"
     19 #include "llvm/Option/ArgList.h"
     20 #include "llvm/Option/Option.h"
     21 #include "llvm/Support/ErrorHandling.h"
     22 #include "llvm/Support/FileSystem.h"
     23 using namespace clang::driver;
     24 using namespace clang;
     25 using namespace llvm::opt;
     26 
     27 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
     28                      const ArgList &A)
     29   : D(D), Triple(T), Args(A) {
     30 }
     31 
     32 ToolChain::~ToolChain() {
     33 }
     34 
     35 const Driver &ToolChain::getDriver() const {
     36  return D;
     37 }
     38 
     39 bool ToolChain::useIntegratedAs() const {
     40   return Args.hasFlag(options::OPT_integrated_as,
     41                       options::OPT_no_integrated_as,
     42                       IsIntegratedAssemblerDefault());
     43 }
     44 
     45 std::string ToolChain::getDefaultUniversalArchName() const {
     46   // In universal driver terms, the arch name accepted by -arch isn't exactly
     47   // the same as the ones that appear in the triple. Roughly speaking, this is
     48   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
     49   // only interesting special case is powerpc.
     50   switch (Triple.getArch()) {
     51   case llvm::Triple::ppc:
     52     return "ppc";
     53   case llvm::Triple::ppc64:
     54     return "ppc64";
     55   case llvm::Triple::ppc64le:
     56     return "ppc64le";
     57   default:
     58     return Triple.getArchName();
     59   }
     60 }
     61 
     62 bool ToolChain::IsUnwindTablesDefault() const {
     63   return false;
     64 }
     65 
     66 Tool *ToolChain::getClang() const {
     67   if (!Clang)
     68     Clang.reset(new tools::Clang(*this));
     69   return Clang.get();
     70 }
     71 
     72 Tool *ToolChain::buildAssembler() const {
     73   return new tools::ClangAs(*this);
     74 }
     75 
     76 Tool *ToolChain::buildLinker() const {
     77   llvm_unreachable("Linking is not supported by this toolchain");
     78 }
     79 
     80 Tool *ToolChain::getAssemble() const {
     81   if (!Assemble)
     82     Assemble.reset(buildAssembler());
     83   return Assemble.get();
     84 }
     85 
     86 Tool *ToolChain::getClangAs() const {
     87   if (!Assemble)
     88     Assemble.reset(new tools::ClangAs(*this));
     89   return Assemble.get();
     90 }
     91 
     92 Tool *ToolChain::getLink() const {
     93   if (!Link)
     94     Link.reset(buildLinker());
     95   return Link.get();
     96 }
     97 
     98 Tool *ToolChain::getTool(Action::ActionClass AC) const {
     99   switch (AC) {
    100   case Action::AssembleJobClass:
    101     return getAssemble();
    102 
    103   case Action::LinkJobClass:
    104     return getLink();
    105 
    106   case Action::InputClass:
    107   case Action::BindArchClass:
    108   case Action::LipoJobClass:
    109   case Action::DsymutilJobClass:
    110   case Action::VerifyJobClass:
    111     llvm_unreachable("Invalid tool kind.");
    112 
    113   case Action::CompileJobClass:
    114   case Action::PrecompileJobClass:
    115   case Action::PreprocessJobClass:
    116   case Action::AnalyzeJobClass:
    117   case Action::MigrateJobClass:
    118     return getClang();
    119   }
    120 
    121   llvm_unreachable("Invalid tool kind.");
    122 }
    123 
    124 Tool *ToolChain::SelectTool(const JobAction &JA) const {
    125   if (getDriver().ShouldUseClangCompiler(JA))
    126     return getClang();
    127   Action::ActionClass AC = JA.getKind();
    128   if (AC == Action::AssembleJobClass && useIntegratedAs())
    129     return getClangAs();
    130   return getTool(AC);
    131 }
    132 
    133 std::string ToolChain::GetFilePath(const char *Name) const {
    134   return D.GetFilePath(Name, *this);
    135 
    136 }
    137 
    138 std::string ToolChain::GetProgramPath(const char *Name) const {
    139   return D.GetProgramPath(Name, *this);
    140 }
    141 
    142 types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
    143   return types::lookupTypeForExtension(Ext);
    144 }
    145 
    146 bool ToolChain::HasNativeLLVMSupport() const {
    147   return false;
    148 }
    149 
    150 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
    151   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
    152                      VersionTuple());
    153 }
    154 
    155 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
    156 //
    157 // FIXME: tblgen this.
    158 static const char *getARMTargetCPU(const ArgList &Args,
    159                                    const llvm::Triple &Triple) {
    160   // For Darwin targets, the -arch option (which is translated to a
    161   // corresponding -march option) should determine the architecture
    162   // (and the Mach-O slice) regardless of any -mcpu options.
    163   if (!Triple.isOSDarwin()) {
    164     // FIXME: Warn on inconsistent use of -mcpu and -march.
    165     // If we have -mcpu=, use that.
    166     if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
    167       return A->getValue();
    168   }
    169 
    170   StringRef MArch;
    171   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
    172     // Otherwise, if we have -march= choose the base CPU for that arch.
    173     MArch = A->getValue();
    174   } else {
    175     // Otherwise, use the Arch from the triple.
    176     MArch = Triple.getArchName();
    177   }
    178 
    179   return llvm::StringSwitch<const char *>(MArch)
    180     .Cases("armv2", "armv2a","arm2")
    181     .Case("armv3", "arm6")
    182     .Case("armv3m", "arm7m")
    183     .Case("armv4", "strongarm")
    184     .Case("armv4t", "arm7tdmi")
    185     .Cases("armv5", "armv5t", "arm10tdmi")
    186     .Cases("armv5e", "armv5te", "arm1026ejs")
    187     .Case("armv5tej", "arm926ej-s")
    188     .Cases("armv6", "armv6k", "arm1136jf-s")
    189     .Case("armv6j", "arm1136j-s")
    190     .Cases("armv6z", "armv6zk", "arm1176jzf-s")
    191     .Case("armv6t2", "arm1156t2-s")
    192     .Cases("armv6m", "armv6-m", "cortex-m0")
    193     .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
    194     .Cases("armv7l", "armv7-l", "cortex-a8")
    195     .Cases("armv7f", "armv7-f", "cortex-a9-mp")
    196     .Cases("armv7s", "armv7-s", "swift")
    197     .Cases("armv7r", "armv7-r", "cortex-r4")
    198     .Cases("armv7m", "armv7-m", "cortex-m3")
    199     .Cases("armv7em", "armv7e-m", "cortex-m4")
    200     .Cases("armv8", "armv8a", "armv8-a", "cortex-a53")
    201     .Case("ep9312", "ep9312")
    202     .Case("iwmmxt", "iwmmxt")
    203     .Case("xscale", "xscale")
    204     // If all else failed, return the most base CPU with thumb interworking
    205     // supported by LLVM.
    206     .Default("arm7tdmi");
    207 }
    208 
    209 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
    210 /// CPU.
    211 //
    212 // FIXME: This is redundant with -mcpu, why does LLVM use this.
    213 // FIXME: tblgen this, or kill it!
    214 static const char *getLLVMArchSuffixForARM(StringRef CPU) {
    215   return llvm::StringSwitch<const char *>(CPU)
    216     .Case("strongarm", "v4")
    217     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
    218     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
    219     .Cases("arm920", "arm920t", "arm922t", "v4t")
    220     .Cases("arm940t", "ep9312","v4t")
    221     .Cases("arm10tdmi",  "arm1020t", "v5")
    222     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
    223     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
    224     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
    225     .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
    226     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
    227     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
    228     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
    229     .Cases("cortex-a9", "cortex-a15", "v7")
    230     .Case("cortex-r5", "v7r")
    231     .Case("cortex-m0", "v6m")
    232     .Case("cortex-m3", "v7m")
    233     .Case("cortex-m4", "v7em")
    234     .Case("cortex-a9-mp", "v7f")
    235     .Case("swift", "v7s")
    236     .Case("cortex-a53", "v8")
    237     .Default("");
    238 }
    239 
    240 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
    241                                          types::ID InputType) const {
    242   switch (getTriple().getArch()) {
    243   default:
    244     return getTripleString();
    245 
    246   case llvm::Triple::arm:
    247   case llvm::Triple::thumb: {
    248     // FIXME: Factor into subclasses.
    249     llvm::Triple Triple = getTriple();
    250 
    251     // Thumb2 is the default for V7 on Darwin.
    252     //
    253     // FIXME: Thumb should just be another -target-feaure, not in the triple.
    254     StringRef Suffix =
    255       getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
    256     bool ThumbDefault = Suffix.startswith("v6m") ||
    257       (Suffix.startswith("v7") && getTriple().isOSDarwin());
    258     std::string ArchName = "arm";
    259 
    260     // Assembly files should start in ARM mode.
    261     if (InputType != types::TY_PP_Asm &&
    262         Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
    263       ArchName = "thumb";
    264     Triple.setArchName(ArchName + Suffix.str());
    265 
    266     return Triple.getTriple();
    267   }
    268   }
    269 }
    270 
    271 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
    272                                                    types::ID InputType) const {
    273   // Diagnose use of Darwin OS deployment target arguments on non-Darwin.
    274   if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
    275                                options::OPT_miphoneos_version_min_EQ,
    276                                options::OPT_mios_simulator_version_min_EQ))
    277     getDriver().Diag(diag::err_drv_clang_unsupported)
    278       << A->getAsString(Args);
    279 
    280   return ComputeLLVMTriple(Args, InputType);
    281 }
    282 
    283 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
    284                                           ArgStringList &CC1Args) const {
    285   // Each toolchain should provide the appropriate include flags.
    286 }
    287 
    288 void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
    289                                       ArgStringList &CC1Args) const {
    290 }
    291 
    292 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
    293   const ArgList &Args) const
    294 {
    295   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
    296     StringRef Value = A->getValue();
    297     if (Value == "compiler-rt")
    298       return ToolChain::RLT_CompilerRT;
    299     if (Value == "libgcc")
    300       return ToolChain::RLT_Libgcc;
    301     getDriver().Diag(diag::err_drv_invalid_rtlib_name)
    302       << A->getAsString(Args);
    303   }
    304 
    305   return GetDefaultRuntimeLibType();
    306 }
    307 
    308 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
    309   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
    310     StringRef Value = A->getValue();
    311     if (Value == "libc++")
    312       return ToolChain::CST_Libcxx;
    313     if (Value == "libstdc++")
    314       return ToolChain::CST_Libstdcxx;
    315     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
    316       << A->getAsString(Args);
    317   }
    318 
    319   return ToolChain::CST_Libstdcxx;
    320 }
    321 
    322 /// \brief Utility function to add a system include directory to CC1 arguments.
    323 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
    324                                             ArgStringList &CC1Args,
    325                                             const Twine &Path) {
    326   CC1Args.push_back("-internal-isystem");
    327   CC1Args.push_back(DriverArgs.MakeArgString(Path));
    328 }
    329 
    330 /// \brief Utility function to add a system include directory with extern "C"
    331 /// semantics to CC1 arguments.
    332 ///
    333 /// Note that this should be used rarely, and only for directories that
    334 /// historically and for legacy reasons are treated as having implicit extern
    335 /// "C" semantics. These semantics are *ignored* by and large today, but its
    336 /// important to preserve the preprocessor changes resulting from the
    337 /// classification.
    338 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
    339                                                    ArgStringList &CC1Args,
    340                                                    const Twine &Path) {
    341   CC1Args.push_back("-internal-externc-isystem");
    342   CC1Args.push_back(DriverArgs.MakeArgString(Path));
    343 }
    344 
    345 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
    346                                                 ArgStringList &CC1Args,
    347                                                 const Twine &Path) {
    348   if (llvm::sys::fs::exists(Path))
    349     addExternCSystemInclude(DriverArgs, CC1Args, Path);
    350 }
    351 
    352 /// \brief Utility function to add a list of system include directories to CC1.
    353 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
    354                                              ArgStringList &CC1Args,
    355                                              ArrayRef<StringRef> Paths) {
    356   for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
    357        I != E; ++I) {
    358     CC1Args.push_back("-internal-isystem");
    359     CC1Args.push_back(DriverArgs.MakeArgString(*I));
    360   }
    361 }
    362 
    363 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
    364                                              ArgStringList &CC1Args) const {
    365   // Header search paths should be handled by each of the subclasses.
    366   // Historically, they have not been, and instead have been handled inside of
    367   // the CC1-layer frontend. As the logic is hoisted out, this generic function
    368   // will slowly stop being called.
    369   //
    370   // While it is being called, replicate a bit of a hack to propagate the
    371   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
    372   // header search paths with it. Once all systems are overriding this
    373   // function, the CC1 flag and this line can be removed.
    374   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
    375 }
    376 
    377 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
    378                                     ArgStringList &CmdArgs) const {
    379   CXXStdlibType Type = GetCXXStdlibType(Args);
    380 
    381   switch (Type) {
    382   case ToolChain::CST_Libcxx:
    383     CmdArgs.push_back("-lc++");
    384     break;
    385 
    386   case ToolChain::CST_Libstdcxx:
    387     CmdArgs.push_back("-lstdc++");
    388     break;
    389   }
    390 }
    391 
    392 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
    393                                  ArgStringList &CmdArgs) const {
    394   CmdArgs.push_back("-lcc_kext");
    395 }
    396 
    397 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
    398                                               ArgStringList &CmdArgs) const {
    399   // Check if -ffast-math or -funsafe-math is enabled.
    400   Arg *A = Args.getLastArg(options::OPT_ffast_math,
    401                            options::OPT_fno_fast_math,
    402                            options::OPT_funsafe_math_optimizations,
    403                            options::OPT_fno_unsafe_math_optimizations);
    404 
    405   if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
    406       A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
    407     return false;
    408 
    409   // If crtfastmath.o exists add it to the arguments.
    410   std::string Path = GetFilePath("crtfastmath.o");
    411   if (Path == "crtfastmath.o") // Not found.
    412     return false;
    413 
    414   CmdArgs.push_back(Args.MakeArgString(Path));
    415   return true;
    416 }
    417