Home | History | Annotate | Download | only in CodeGen
      1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
      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 file implements the LLVMTargetMachine class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/Target/TargetMachine.h"
     15 #include "llvm/Analysis/Passes.h"
     16 #include "llvm/CodeGen/AsmPrinter.h"
     17 #include "llvm/CodeGen/BasicTTIImpl.h"
     18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
     19 #include "llvm/CodeGen/MachineModuleInfo.h"
     20 #include "llvm/CodeGen/Passes.h"
     21 #include "llvm/CodeGen/TargetPassConfig.h"
     22 #include "llvm/IR/IRPrintingPasses.h"
     23 #include "llvm/IR/LegacyPassManager.h"
     24 #include "llvm/IR/Verifier.h"
     25 #include "llvm/MC/MCAsmInfo.h"
     26 #include "llvm/MC/MCContext.h"
     27 #include "llvm/MC/MCInstrInfo.h"
     28 #include "llvm/MC/MCStreamer.h"
     29 #include "llvm/MC/MCSubtargetInfo.h"
     30 #include "llvm/Support/CommandLine.h"
     31 #include "llvm/Support/ErrorHandling.h"
     32 #include "llvm/Support/FormattedStream.h"
     33 #include "llvm/Support/TargetRegistry.h"
     34 #include "llvm/Target/TargetLoweringObjectFile.h"
     35 #include "llvm/Target/TargetOptions.h"
     36 #include "llvm/Transforms/Scalar.h"
     37 using namespace llvm;
     38 
     39 // Enable or disable FastISel. Both options are needed, because
     40 // FastISel is enabled by default with -fast, and we wish to be
     41 // able to enable or disable fast-isel independently from -O0.
     42 static cl::opt<cl::boolOrDefault>
     43 EnableFastISelOption("fast-isel", cl::Hidden,
     44   cl::desc("Enable the \"fast\" instruction selector"));
     45 
     46 static cl::opt<bool>
     47     EnableGlobalISel("global-isel", cl::Hidden, cl::init(false),
     48                      cl::desc("Enable the \"global\" instruction selector"));
     49 
     50 void LLVMTargetMachine::initAsmInfo() {
     51   MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
     52   MII = TheTarget.createMCInstrInfo();
     53   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
     54   // to some backends having subtarget feature dependent module level
     55   // code generation. This is similar to the hack in the AsmPrinter for
     56   // module level assembly etc.
     57   STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
     58                                         getTargetFeatureString());
     59 
     60   MCAsmInfo *TmpAsmInfo =
     61       TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
     62   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
     63   // and if the old one gets included then MCAsmInfo will be NULL and
     64   // we'll crash later.
     65   // Provide the user with a useful error message about what's wrong.
     66   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
     67          "Make sure you include the correct TargetSelect.h"
     68          "and that InitializeAllTargetMCs() is being invoked!");
     69 
     70   if (Options.DisableIntegratedAS)
     71     TmpAsmInfo->setUseIntegratedAssembler(false);
     72 
     73   TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
     74 
     75   if (Options.CompressDebugSections)
     76     TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
     77 
     78   TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
     79 
     80   if (Options.ExceptionModel != ExceptionHandling::None)
     81     TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
     82 
     83   AsmInfo = TmpAsmInfo;
     84 }
     85 
     86 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
     87                                      StringRef DataLayoutString,
     88                                      const Triple &TT, StringRef CPU,
     89                                      StringRef FS, TargetOptions Options,
     90                                      Reloc::Model RM, CodeModel::Model CM,
     91                                      CodeGenOpt::Level OL)
     92     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
     93   T.adjustCodeGenOpts(TT, RM, CM);
     94   this->RM = RM;
     95   this->CMModel = CM;
     96   this->OptLevel = OL;
     97 }
     98 
     99 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
    100   return TargetIRAnalysis([this](const Function &F) {
    101     return TargetTransformInfo(BasicTTIImpl(this, F));
    102   });
    103 }
    104 
    105 MachineModuleInfo &
    106 LLVMTargetMachine::addMachineModuleInfo(PassManagerBase &PM) const {
    107   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
    108                                                  *getMCRegisterInfo(),
    109                                                  getObjFileLowering());
    110   PM.add(MMI);
    111   return *MMI;
    112 }
    113 
    114 void LLVMTargetMachine::addMachineFunctionAnalysis(PassManagerBase &PM,
    115     MachineFunctionInitializer *MFInitializer) const {
    116   PM.add(new MachineFunctionAnalysis(*this, MFInitializer));
    117 }
    118 
    119 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
    120 static MCContext *
    121 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
    122                         bool DisableVerify, AnalysisID StartBefore,
    123                         AnalysisID StartAfter, AnalysisID StopAfter,
    124                         MachineFunctionInitializer *MFInitializer = nullptr) {
    125 
    126   // When in emulated TLS mode, add the LowerEmuTLS pass.
    127   if (TM->Options.EmulatedTLS)
    128     PM.add(createLowerEmuTLSPass(TM));
    129 
    130   PM.add(createPreISelIntrinsicLoweringPass());
    131 
    132   // Add internal analysis passes from the target machine.
    133   PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
    134 
    135   // Targets may override createPassConfig to provide a target-specific
    136   // subclass.
    137   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
    138   PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
    139 
    140   // Set PassConfig options provided by TargetMachine.
    141   PassConfig->setDisableVerify(DisableVerify);
    142 
    143   PM.add(PassConfig);
    144 
    145   PassConfig->addIRPasses();
    146 
    147   PassConfig->addCodeGenPrepare();
    148 
    149   PassConfig->addPassesToHandleExceptions();
    150 
    151   PassConfig->addISelPrepare();
    152 
    153   MachineModuleInfo &MMI = TM->addMachineModuleInfo(PM);
    154   TM->addMachineFunctionAnalysis(PM, MFInitializer);
    155 
    156   // Enable FastISel with -fast, but allow that to be overridden.
    157   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
    158   if (EnableFastISelOption == cl::BOU_TRUE ||
    159       (TM->getOptLevel() == CodeGenOpt::None &&
    160        TM->getO0WantsFastISel()))
    161     TM->setFastISel(true);
    162 
    163   // Ask the target for an isel.
    164   if (LLVM_UNLIKELY(EnableGlobalISel)) {
    165     if (PassConfig->addIRTranslator())
    166       return nullptr;
    167 
    168     // Before running the register bank selector, ask the target if it
    169     // wants to run some passes.
    170     PassConfig->addPreRegBankSelect();
    171 
    172     if (PassConfig->addRegBankSelect())
    173       return nullptr;
    174 
    175   } else if (PassConfig->addInstSelector())
    176     return nullptr;
    177 
    178   PassConfig->addMachinePasses();
    179 
    180   PassConfig->setInitialized();
    181 
    182   return &MMI.getContext();
    183 }
    184 
    185 bool LLVMTargetMachine::addPassesToEmitFile(
    186     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
    187     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
    188     AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
    189   // Add common CodeGen passes.
    190   MCContext *Context =
    191       addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
    192                               StopAfter, MFInitializer);
    193   if (!Context)
    194     return true;
    195 
    196   if (StopAfter) {
    197     PM.add(createPrintMIRPass(Out));
    198     return false;
    199   }
    200 
    201   if (Options.MCOptions.MCSaveTempLabels)
    202     Context->setAllowTemporaryLabels(false);
    203 
    204   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
    205   const MCAsmInfo &MAI = *getMCAsmInfo();
    206   const MCRegisterInfo &MRI = *getMCRegisterInfo();
    207   const MCInstrInfo &MII = *getMCInstrInfo();
    208 
    209   std::unique_ptr<MCStreamer> AsmStreamer;
    210 
    211   switch (FileType) {
    212   case CGFT_AssemblyFile: {
    213     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
    214         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
    215 
    216     // Create a code emitter if asked to show the encoding.
    217     MCCodeEmitter *MCE = nullptr;
    218     if (Options.MCOptions.ShowMCEncoding)
    219       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
    220 
    221     MCAsmBackend *MAB =
    222         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
    223     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
    224     MCStreamer *S = getTarget().createAsmStreamer(
    225         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
    226         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
    227         Options.MCOptions.ShowMCInst);
    228     AsmStreamer.reset(S);
    229     break;
    230   }
    231   case CGFT_ObjectFile: {
    232     // Create the code emitter for the target if it exists.  If not, .o file
    233     // emission fails.
    234     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
    235     MCAsmBackend *MAB =
    236         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
    237     if (!MCE || !MAB)
    238       return true;
    239 
    240     // Don't waste memory on names of temp labels.
    241     Context->setUseNamesOnTempLabels(false);
    242 
    243     Triple T(getTargetTriple().str());
    244     AsmStreamer.reset(getTarget().createMCObjectStreamer(
    245         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
    246         Options.MCOptions.MCIncrementalLinkerCompatible,
    247         /*DWARFMustBeAtTheEnd*/ true));
    248     break;
    249   }
    250   case CGFT_Null:
    251     // The Null output is intended for use for performance analysis and testing,
    252     // not real users.
    253     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
    254     break;
    255   }
    256 
    257   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
    258   FunctionPass *Printer =
    259       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
    260   if (!Printer)
    261     return true;
    262 
    263   PM.add(Printer);
    264 
    265   return false;
    266 }
    267 
    268 /// addPassesToEmitMC - Add passes to the specified pass manager to get
    269 /// machine code emitted with the MCJIT. This method returns true if machine
    270 /// code is not supported. It fills the MCContext Ctx pointer which can be
    271 /// used to build custom MCStreamer.
    272 ///
    273 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
    274                                           raw_pwrite_stream &Out,
    275                                           bool DisableVerify) {
    276   // Add common CodeGen passes.
    277   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
    278                                 nullptr);
    279   if (!Ctx)
    280     return true;
    281 
    282   if (Options.MCOptions.MCSaveTempLabels)
    283     Ctx->setAllowTemporaryLabels(false);
    284 
    285   // Create the code emitter for the target if it exists.  If not, .o file
    286   // emission fails.
    287   const MCRegisterInfo &MRI = *getMCRegisterInfo();
    288   MCCodeEmitter *MCE =
    289       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
    290   MCAsmBackend *MAB =
    291       getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
    292   if (!MCE || !MAB)
    293     return true;
    294 
    295   const Triple &T = getTargetTriple();
    296   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
    297   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
    298       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
    299       Options.MCOptions.MCIncrementalLinkerCompatible,
    300       /*DWARFMustBeAtTheEnd*/ true));
    301 
    302   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
    303   FunctionPass *Printer =
    304       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
    305   if (!Printer)
    306     return true;
    307 
    308   PM.add(Printer);
    309 
    310   return false; // success!
    311 }
    312