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 if (Options.CompressDebugSections) 74 TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu); 75 76 AsmInfo = TmpAsmInfo; 77 } 78 79 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 80 StringRef DataLayoutString, 81 const Triple &TT, StringRef CPU, 82 StringRef FS, TargetOptions Options, 83 Reloc::Model RM, CodeModel::Model CM, 84 CodeGenOpt::Level OL) 85 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) { 86 CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL); 87 } 88 89 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() { 90 return TargetIRAnalysis([this](const Function &F) { 91 return TargetTransformInfo(BasicTTIImpl(this, F)); 92 }); 93 } 94 95 MachineModuleInfo & 96 LLVMTargetMachine::addMachineModuleInfo(PassManagerBase &PM) const { 97 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), 98 *getMCRegisterInfo(), 99 getObjFileLowering()); 100 PM.add(MMI); 101 return *MMI; 102 } 103 104 void LLVMTargetMachine::addMachineFunctionAnalysis(PassManagerBase &PM, 105 MachineFunctionInitializer *MFInitializer) const { 106 PM.add(new MachineFunctionAnalysis(*this, MFInitializer)); 107 } 108 109 /// addPassesToX helper drives creation and initialization of TargetPassConfig. 110 static MCContext * 111 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM, 112 bool DisableVerify, AnalysisID StartBefore, 113 AnalysisID StartAfter, AnalysisID StopAfter, 114 MachineFunctionInitializer *MFInitializer = nullptr) { 115 116 // When in emulated TLS mode, add the LowerEmuTLS pass. 117 if (TM->Options.EmulatedTLS) 118 PM.add(createLowerEmuTLSPass(TM)); 119 120 PM.add(createPreISelIntrinsicLoweringPass()); 121 122 // Add internal analysis passes from the target machine. 123 PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 124 125 // Targets may override createPassConfig to provide a target-specific 126 // subclass. 127 TargetPassConfig *PassConfig = TM->createPassConfig(PM); 128 PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter); 129 130 // Set PassConfig options provided by TargetMachine. 131 PassConfig->setDisableVerify(DisableVerify); 132 133 PM.add(PassConfig); 134 135 PassConfig->addIRPasses(); 136 137 PassConfig->addCodeGenPrepare(); 138 139 PassConfig->addPassesToHandleExceptions(); 140 141 PassConfig->addISelPrepare(); 142 143 MachineModuleInfo &MMI = TM->addMachineModuleInfo(PM); 144 TM->addMachineFunctionAnalysis(PM, MFInitializer); 145 146 // Enable FastISel with -fast, but allow that to be overridden. 147 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 148 if (EnableFastISelOption == cl::BOU_TRUE || 149 (TM->getOptLevel() == CodeGenOpt::None && 150 TM->getO0WantsFastISel())) 151 TM->setFastISel(true); 152 153 // Ask the target for an isel. 154 if (LLVM_UNLIKELY(EnableGlobalISel)) { 155 if (PassConfig->addIRTranslator()) 156 return nullptr; 157 158 // Before running the register bank selector, ask the target if it 159 // wants to run some passes. 160 PassConfig->addPreRegBankSelect(); 161 162 if (PassConfig->addRegBankSelect()) 163 return nullptr; 164 165 } else if (PassConfig->addInstSelector()) 166 return nullptr; 167 168 PassConfig->addMachinePasses(); 169 170 PassConfig->setInitialized(); 171 172 return &MMI.getContext(); 173 } 174 175 bool LLVMTargetMachine::addPassesToEmitFile( 176 PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, 177 bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, 178 AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) { 179 // Add common CodeGen passes. 180 MCContext *Context = 181 addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter, 182 StopAfter, MFInitializer); 183 if (!Context) 184 return true; 185 186 if (StopAfter) { 187 PM.add(createPrintMIRPass(errs())); 188 return false; 189 } 190 191 if (Options.MCOptions.MCSaveTempLabels) 192 Context->setAllowTemporaryLabels(false); 193 194 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 195 const MCAsmInfo &MAI = *getMCAsmInfo(); 196 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 197 const MCInstrInfo &MII = *getMCInstrInfo(); 198 199 std::unique_ptr<MCStreamer> AsmStreamer; 200 201 switch (FileType) { 202 case CGFT_AssemblyFile: { 203 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter( 204 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI); 205 206 // Create a code emitter if asked to show the encoding. 207 MCCodeEmitter *MCE = nullptr; 208 if (Options.MCOptions.ShowMCEncoding) 209 MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 210 211 MCAsmBackend *MAB = 212 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 213 auto FOut = llvm::make_unique<formatted_raw_ostream>(Out); 214 MCStreamer *S = getTarget().createAsmStreamer( 215 *Context, std::move(FOut), Options.MCOptions.AsmVerbose, 216 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB, 217 Options.MCOptions.ShowMCInst); 218 AsmStreamer.reset(S); 219 break; 220 } 221 case CGFT_ObjectFile: { 222 // Create the code emitter for the target if it exists. If not, .o file 223 // emission fails. 224 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 225 MCAsmBackend *MAB = 226 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 227 if (!MCE || !MAB) 228 return true; 229 230 // Don't waste memory on names of temp labels. 231 Context->setUseNamesOnTempLabels(false); 232 233 Triple T(getTargetTriple().str()); 234 AsmStreamer.reset(getTarget().createMCObjectStreamer( 235 T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 236 Options.MCOptions.MCIncrementalLinkerCompatible, 237 /*DWARFMustBeAtTheEnd*/ true)); 238 break; 239 } 240 case CGFT_Null: 241 // The Null output is intended for use for performance analysis and testing, 242 // not real users. 243 AsmStreamer.reset(getTarget().createNullStreamer(*Context)); 244 break; 245 } 246 247 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 248 FunctionPass *Printer = 249 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 250 if (!Printer) 251 return true; 252 253 PM.add(Printer); 254 255 return false; 256 } 257 258 /// addPassesToEmitMC - Add passes to the specified pass manager to get 259 /// machine code emitted with the MCJIT. This method returns true if machine 260 /// code is not supported. It fills the MCContext Ctx pointer which can be 261 /// used to build custom MCStreamer. 262 /// 263 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 264 raw_pwrite_stream &Out, 265 bool DisableVerify) { 266 // Add common CodeGen passes. 267 Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr, 268 nullptr); 269 if (!Ctx) 270 return true; 271 272 if (Options.MCOptions.MCSaveTempLabels) 273 Ctx->setAllowTemporaryLabels(false); 274 275 // Create the code emitter for the target if it exists. If not, .o file 276 // emission fails. 277 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 278 MCCodeEmitter *MCE = 279 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 280 MCAsmBackend *MAB = 281 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 282 if (!MCE || !MAB) 283 return true; 284 285 const Triple &T = getTargetTriple(); 286 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 287 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 288 T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 289 Options.MCOptions.MCIncrementalLinkerCompatible, 290 /*DWARFMustBeAtTheEnd*/ true)); 291 292 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 293 FunctionPass *Printer = 294 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 295 if (!Printer) 296 return true; 297 298 PM.add(Printer); 299 300 return false; // success! 301 } 302