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