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