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