Home | History | Annotate | Download | only in llc
      1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
      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 // This is the llc code generator driver. It provides a convenient
     11 // command-line interface for generating native assembly-language code
     12 // or C code, given LLVM bitcode.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "llvm/LLVMContext.h"
     17 #include "llvm/Module.h"
     18 #include "llvm/PassManager.h"
     19 #include "llvm/Pass.h"
     20 #include "llvm/ADT/Triple.h"
     21 #include "llvm/Support/IRReader.h"
     22 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
     23 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
     24 #include "llvm/Config/config.h"
     25 #include "llvm/MC/SubtargetFeature.h"
     26 #include "llvm/Support/CommandLine.h"
     27 #include "llvm/Support/Debug.h"
     28 #include "llvm/Support/FormattedStream.h"
     29 #include "llvm/Support/ManagedStatic.h"
     30 #include "llvm/Support/PluginLoader.h"
     31 #include "llvm/Support/PrettyStackTrace.h"
     32 #include "llvm/Support/ToolOutputFile.h"
     33 #include "llvm/Support/Host.h"
     34 #include "llvm/Support/Signals.h"
     35 #include "llvm/Support/TargetRegistry.h"
     36 #include "llvm/Support/TargetSelect.h"
     37 #include "llvm/Target/TargetData.h"
     38 #include "llvm/Target/TargetMachine.h"
     39 #include <memory>
     40 using namespace llvm;
     41 
     42 // General options for llc.  Other pass-specific options are specified
     43 // within the corresponding llc passes, and target-specific options
     44 // and back-end code generation options are specified with the target machine.
     45 //
     46 static cl::opt<std::string>
     47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
     48 
     49 static cl::opt<std::string>
     50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
     51 
     52 // Determine optimization level.
     53 static cl::opt<char>
     54 OptLevel("O",
     55          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
     56                   "(default = '-O2')"),
     57          cl::Prefix,
     58          cl::ZeroOrMore,
     59          cl::init(' '));
     60 
     61 static cl::opt<std::string>
     62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
     63 
     64 static cl::opt<std::string>
     65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
     66 
     67 static cl::opt<std::string>
     68 MCPU("mcpu",
     69   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
     70   cl::value_desc("cpu-name"),
     71   cl::init(""));
     72 
     73 static cl::list<std::string>
     74 MAttrs("mattr",
     75   cl::CommaSeparated,
     76   cl::desc("Target specific attributes (-mattr=help for details)"),
     77   cl::value_desc("a1,+a2,-a3,..."));
     78 
     79 static cl::opt<Reloc::Model>
     80 RelocModel("relocation-model",
     81              cl::desc("Choose relocation model"),
     82              cl::init(Reloc::Default),
     83              cl::values(
     84             clEnumValN(Reloc::Default, "default",
     85                        "Target default relocation model"),
     86             clEnumValN(Reloc::Static, "static",
     87                        "Non-relocatable code"),
     88             clEnumValN(Reloc::PIC_, "pic",
     89                        "Fully relocatable, position independent code"),
     90             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
     91                        "Relocatable external references, non-relocatable code"),
     92             clEnumValEnd));
     93 
     94 static cl::opt<llvm::CodeModel::Model>
     95 CMModel("code-model",
     96         cl::desc("Choose code model"),
     97         cl::init(CodeModel::Default),
     98         cl::values(clEnumValN(CodeModel::Default, "default",
     99                               "Target default code model"),
    100                    clEnumValN(CodeModel::Small, "small",
    101                               "Small code model"),
    102                    clEnumValN(CodeModel::Kernel, "kernel",
    103                               "Kernel code model"),
    104                    clEnumValN(CodeModel::Medium, "medium",
    105                               "Medium code model"),
    106                    clEnumValN(CodeModel::Large, "large",
    107                               "Large code model"),
    108                    clEnumValEnd));
    109 
    110 static cl::opt<bool>
    111 RelaxAll("mc-relax-all",
    112   cl::desc("When used with filetype=obj, "
    113            "relax all fixups in the emitted object file"));
    114 
    115 cl::opt<TargetMachine::CodeGenFileType>
    116 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
    117   cl::desc("Choose a file type (not all types are supported by all targets):"),
    118   cl::values(
    119        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
    120                   "Emit an assembly ('.s') file"),
    121        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
    122                   "Emit a native object ('.o') file [experimental]"),
    123        clEnumValN(TargetMachine::CGFT_Null, "null",
    124                   "Emit nothing, for performance testing"),
    125        clEnumValEnd));
    126 
    127 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
    128                        cl::desc("Do not verify input module"));
    129 
    130 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
    131                             cl::desc("Do not use .loc entries"));
    132 
    133 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
    134                          cl::desc("Do not use .cfi_* directives"));
    135 
    136 cl::opt<bool> DisableDwarfDirectory("disable-dwarf-directory", cl::Hidden,
    137     cl::desc("Do not use file directives with an explicit directory."));
    138 
    139 static cl::opt<bool>
    140 DisableRedZone("disable-red-zone",
    141   cl::desc("Do not emit code that uses the red zone."),
    142   cl::init(false));
    143 
    144 // GetFileNameRoot - Helper function to get the basename of a filename.
    145 static inline std::string
    146 GetFileNameRoot(const std::string &InputFilename) {
    147   std::string IFN = InputFilename;
    148   std::string outputFilename;
    149   int Len = IFN.length();
    150   if ((Len > 2) &&
    151       IFN[Len-3] == '.' &&
    152       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
    153        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    154     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
    155   } else {
    156     outputFilename = IFN;
    157   }
    158   return outputFilename;
    159 }
    160 
    161 static tool_output_file *GetOutputStream(const char *TargetName,
    162                                          Triple::OSType OS,
    163                                          const char *ProgName) {
    164   // If we don't yet have an output filename, make one.
    165   if (OutputFilename.empty()) {
    166     if (InputFilename == "-")
    167       OutputFilename = "-";
    168     else {
    169       OutputFilename = GetFileNameRoot(InputFilename);
    170 
    171       switch (FileType) {
    172       default: assert(0 && "Unknown file type");
    173       case TargetMachine::CGFT_AssemblyFile:
    174         if (TargetName[0] == 'c') {
    175           if (TargetName[1] == 0)
    176             OutputFilename += ".cbe.c";
    177           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
    178             OutputFilename += ".cpp";
    179           else
    180             OutputFilename += ".s";
    181         } else
    182           OutputFilename += ".s";
    183         break;
    184       case TargetMachine::CGFT_ObjectFile:
    185         if (OS == Triple::Win32)
    186           OutputFilename += ".obj";
    187         else
    188           OutputFilename += ".o";
    189         break;
    190       case TargetMachine::CGFT_Null:
    191         OutputFilename += ".null";
    192         break;
    193       }
    194     }
    195   }
    196 
    197   // Decide if we need "binary" output.
    198   bool Binary = false;
    199   switch (FileType) {
    200   default: assert(0 && "Unknown file type");
    201   case TargetMachine::CGFT_AssemblyFile:
    202     break;
    203   case TargetMachine::CGFT_ObjectFile:
    204   case TargetMachine::CGFT_Null:
    205     Binary = true;
    206     break;
    207   }
    208 
    209   // Open the file.
    210   std::string error;
    211   unsigned OpenFlags = 0;
    212   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
    213   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
    214                                                  OpenFlags);
    215   if (!error.empty()) {
    216     errs() << error << '\n';
    217     delete FDOut;
    218     return 0;
    219   }
    220 
    221   return FDOut;
    222 }
    223 
    224 // main - Entry point for the llc compiler.
    225 //
    226 int main(int argc, char **argv) {
    227   sys::PrintStackTraceOnErrorSignal();
    228   PrettyStackTraceProgram X(argc, argv);
    229 
    230   // Enable debug stream buffering.
    231   EnableDebugBuffering = true;
    232 
    233   LLVMContext &Context = getGlobalContext();
    234   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
    235 
    236   // Initialize targets first, so that --version shows registered targets.
    237   InitializeAllTargets();
    238   InitializeAllTargetMCs();
    239   InitializeAllAsmPrinters();
    240   InitializeAllAsmParsers();
    241 
    242   // Register the target printer for --version.
    243   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
    244 
    245   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
    246 
    247   // Load the module to be compiled...
    248   SMDiagnostic Err;
    249   std::auto_ptr<Module> M;
    250 
    251   M.reset(ParseIRFile(InputFilename, Err, Context));
    252   if (M.get() == 0) {
    253     Err.print(argv[0], errs());
    254     return 1;
    255   }
    256   Module &mod = *M.get();
    257 
    258   // If we are supposed to override the target triple, do so now.
    259   if (!TargetTriple.empty())
    260     mod.setTargetTriple(Triple::normalize(TargetTriple));
    261 
    262   Triple TheTriple(mod.getTargetTriple());
    263   if (TheTriple.getTriple().empty())
    264     TheTriple.setTriple(sys::getHostTriple());
    265 
    266   // Allocate target machine.  First, check whether the user has explicitly
    267   // specified an architecture to compile for. If so we have to look it up by
    268   // name, because it might be a backend that has no mapping to a target triple.
    269   const Target *TheTarget = 0;
    270   if (!MArch.empty()) {
    271     for (TargetRegistry::iterator it = TargetRegistry::begin(),
    272            ie = TargetRegistry::end(); it != ie; ++it) {
    273       if (MArch == it->getName()) {
    274         TheTarget = &*it;
    275         break;
    276       }
    277     }
    278 
    279     if (!TheTarget) {
    280       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
    281       return 1;
    282     }
    283 
    284     // Adjust the triple to match (if known), otherwise stick with the
    285     // module/host triple.
    286     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    287     if (Type != Triple::UnknownArch)
    288       TheTriple.setArch(Type);
    289   } else {
    290     std::string Err;
    291     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    292     if (TheTarget == 0) {
    293       errs() << argv[0] << ": error auto-selecting target for module '"
    294              << Err << "'.  Please use the -march option to explicitly "
    295              << "pick a target.\n";
    296       return 1;
    297     }
    298   }
    299 
    300   // Package up features to be passed to target/subtarget
    301   std::string FeaturesStr;
    302   if (MAttrs.size()) {
    303     SubtargetFeatures Features;
    304     for (unsigned i = 0; i != MAttrs.size(); ++i)
    305       Features.AddFeature(MAttrs[i]);
    306     FeaturesStr = Features.getString();
    307   }
    308 
    309   std::auto_ptr<TargetMachine>
    310     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
    311                                           MCPU, FeaturesStr,
    312                                           RelocModel, CMModel));
    313   assert(target.get() && "Could not allocate target machine!");
    314   TargetMachine &Target = *target.get();
    315 
    316   if (DisableDotLoc)
    317     Target.setMCUseLoc(false);
    318 
    319   if (DisableCFI)
    320     Target.setMCUseCFI(false);
    321 
    322   if (DisableDwarfDirectory)
    323     Target.setMCUseDwarfDirectory(false);
    324 
    325   // Disable .loc support for older OS X versions.
    326   if (TheTriple.isMacOSX() &&
    327       TheTriple.isMacOSXVersionLT(10, 6))
    328     Target.setMCUseLoc(false);
    329 
    330   // Figure out where we are going to send the output...
    331   OwningPtr<tool_output_file> Out
    332     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
    333   if (!Out) return 1;
    334 
    335   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
    336   switch (OptLevel) {
    337   default:
    338     errs() << argv[0] << ": invalid optimization level.\n";
    339     return 1;
    340   case ' ': break;
    341   case '0': OLvl = CodeGenOpt::None; break;
    342   case '1': OLvl = CodeGenOpt::Less; break;
    343   case '2': OLvl = CodeGenOpt::Default; break;
    344   case '3': OLvl = CodeGenOpt::Aggressive; break;
    345   }
    346 
    347   // Build up all of the passes that we want to do to the module.
    348   PassManager PM;
    349 
    350   // Add the target data from the target machine, if it exists, or the module.
    351   if (const TargetData *TD = Target.getTargetData())
    352     PM.add(new TargetData(*TD));
    353   else
    354     PM.add(new TargetData(&mod));
    355 
    356   // Override default to generate verbose assembly.
    357   Target.setAsmVerbosityDefault(true);
    358 
    359   if (RelaxAll) {
    360     if (FileType != TargetMachine::CGFT_ObjectFile)
    361       errs() << argv[0]
    362              << ": warning: ignoring -mc-relax-all because filetype != obj";
    363     else
    364       Target.setMCRelaxAll(true);
    365   }
    366 
    367   {
    368     formatted_raw_ostream FOS(Out->os());
    369 
    370     // Ask the target to add backend passes as necessary.
    371     if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
    372       errs() << argv[0] << ": target does not support generation of this"
    373              << " file type!\n";
    374       return 1;
    375     }
    376 
    377     // Before executing passes, print the final values of the LLVM options.
    378     cl::PrintOptionValues();
    379 
    380     PM.run(mod);
    381   }
    382 
    383   // Declare success.
    384   Out->keep();
    385 
    386   return 0;
    387 }
    388