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 PassConfig->addPreLegalizeMachineIR(); 169 170 if (PassConfig->addLegalizeMachineIR()) 171 return nullptr; 172 173 // Before running the register bank selector, ask the target if it 174 // wants to run some passes. 175 PassConfig->addPreRegBankSelect(); 176 177 if (PassConfig->addRegBankSelect()) 178 return nullptr; 179 180 } else if (PassConfig->addInstSelector()) 181 return nullptr; 182 183 PassConfig->addMachinePasses(); 184 185 PassConfig->setInitialized(); 186 187 return &MMI.getContext(); 188 } 189 190 bool LLVMTargetMachine::addPassesToEmitFile( 191 PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, 192 bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, 193 AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) { 194 // Add common CodeGen passes. 195 MCContext *Context = 196 addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter, 197 StopAfter, MFInitializer); 198 if (!Context) 199 return true; 200 201 if (StopAfter) { 202 PM.add(createPrintMIRPass(Out)); 203 return false; 204 } 205 206 if (Options.MCOptions.MCSaveTempLabels) 207 Context->setAllowTemporaryLabels(false); 208 209 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 210 const MCAsmInfo &MAI = *getMCAsmInfo(); 211 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 212 const MCInstrInfo &MII = *getMCInstrInfo(); 213 214 std::unique_ptr<MCStreamer> AsmStreamer; 215 216 switch (FileType) { 217 case CGFT_AssemblyFile: { 218 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter( 219 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI); 220 221 // Create a code emitter if asked to show the encoding. 222 MCCodeEmitter *MCE = nullptr; 223 if (Options.MCOptions.ShowMCEncoding) 224 MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 225 226 MCAsmBackend *MAB = 227 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 228 auto FOut = llvm::make_unique<formatted_raw_ostream>(Out); 229 MCStreamer *S = getTarget().createAsmStreamer( 230 *Context, std::move(FOut), Options.MCOptions.AsmVerbose, 231 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB, 232 Options.MCOptions.ShowMCInst); 233 AsmStreamer.reset(S); 234 break; 235 } 236 case CGFT_ObjectFile: { 237 // Create the code emitter for the target if it exists. If not, .o file 238 // emission fails. 239 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 240 MCAsmBackend *MAB = 241 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 242 if (!MCE || !MAB) 243 return true; 244 245 // Don't waste memory on names of temp labels. 246 Context->setUseNamesOnTempLabels(false); 247 248 Triple T(getTargetTriple().str()); 249 AsmStreamer.reset(getTarget().createMCObjectStreamer( 250 T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 251 Options.MCOptions.MCIncrementalLinkerCompatible, 252 /*DWARFMustBeAtTheEnd*/ true)); 253 break; 254 } 255 case CGFT_Null: 256 // The Null output is intended for use for performance analysis and testing, 257 // not real users. 258 AsmStreamer.reset(getTarget().createNullStreamer(*Context)); 259 break; 260 } 261 262 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 263 FunctionPass *Printer = 264 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 265 if (!Printer) 266 return true; 267 268 PM.add(Printer); 269 270 return false; 271 } 272 273 /// addPassesToEmitMC - Add passes to the specified pass manager to get 274 /// machine code emitted with the MCJIT. This method returns true if machine 275 /// code is not supported. It fills the MCContext Ctx pointer which can be 276 /// used to build custom MCStreamer. 277 /// 278 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 279 raw_pwrite_stream &Out, 280 bool DisableVerify) { 281 // Add common CodeGen passes. 282 Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr, 283 nullptr); 284 if (!Ctx) 285 return true; 286 287 if (Options.MCOptions.MCSaveTempLabels) 288 Ctx->setAllowTemporaryLabels(false); 289 290 // Create the code emitter for the target if it exists. If not, .o file 291 // emission fails. 292 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 293 MCCodeEmitter *MCE = 294 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 295 MCAsmBackend *MAB = 296 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 297 if (!MCE || !MAB) 298 return true; 299 300 const Triple &T = getTargetTriple(); 301 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 302 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 303 T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 304 Options.MCOptions.MCIncrementalLinkerCompatible, 305 /*DWARFMustBeAtTheEnd*/ true)); 306 307 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 308 FunctionPass *Printer = 309 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 310 if (!Printer) 311 return true; 312 313 PM.add(Printer); 314 315 return false; // success! 316 } 317