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