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/MachineModuleInfo.h" 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/CodeGen/TargetPassConfig.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 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments); 73 74 if (Options.CompressDebugSections) 75 TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu); 76 77 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations); 78 79 if (Options.ExceptionModel != ExceptionHandling::None) 80 TmpAsmInfo->setExceptionsType(Options.ExceptionModel); 81 82 AsmInfo = TmpAsmInfo; 83 } 84 85 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 86 StringRef DataLayoutString, 87 const Triple &TT, StringRef CPU, 88 StringRef FS, TargetOptions Options, 89 Reloc::Model RM, CodeModel::Model CM, 90 CodeGenOpt::Level OL) 91 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) { 92 T.adjustCodeGenOpts(TT, RM, CM); 93 this->RM = RM; 94 this->CMModel = CM; 95 this->OptLevel = OL; 96 } 97 98 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() { 99 return TargetIRAnalysis([this](const Function &F) { 100 return TargetTransformInfo(BasicTTIImpl(this, F)); 101 }); 102 } 103 104 /// addPassesToX helper drives creation and initialization of TargetPassConfig. 105 static MCContext * 106 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM, 107 bool DisableVerify, AnalysisID StartBefore, 108 AnalysisID StartAfter, AnalysisID StopAfter, 109 MachineFunctionInitializer *MFInitializer = nullptr) { 110 111 // When in emulated TLS mode, add the LowerEmuTLS pass. 112 if (TM->Options.EmulatedTLS) 113 PM.add(createLowerEmuTLSPass(TM)); 114 115 PM.add(createPreISelIntrinsicLoweringPass()); 116 117 // Add internal analysis passes from the target machine. 118 PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 119 120 // Targets may override createPassConfig to provide a target-specific 121 // subclass. 122 TargetPassConfig *PassConfig = TM->createPassConfig(PM); 123 PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter); 124 125 // Set PassConfig options provided by TargetMachine. 126 PassConfig->setDisableVerify(DisableVerify); 127 128 PM.add(PassConfig); 129 130 PassConfig->addIRPasses(); 131 132 PassConfig->addCodeGenPrepare(); 133 134 PassConfig->addPassesToHandleExceptions(); 135 136 PassConfig->addISelPrepare(); 137 138 MachineModuleInfo *MMI = new MachineModuleInfo(TM); 139 MMI->setMachineFunctionInitializer(MFInitializer); 140 PM.add(MMI); 141 142 // Enable FastISel with -fast, but allow that to be overridden. 143 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 144 if (EnableFastISelOption == cl::BOU_TRUE || 145 (TM->getOptLevel() == CodeGenOpt::None && 146 TM->getO0WantsFastISel())) 147 TM->setFastISel(true); 148 149 // Ask the target for an isel. 150 if (LLVM_UNLIKELY(EnableGlobalISel)) { 151 if (PassConfig->addIRTranslator()) 152 return nullptr; 153 154 PassConfig->addPreLegalizeMachineIR(); 155 156 if (PassConfig->addLegalizeMachineIR()) 157 return nullptr; 158 159 // Before running the register bank selector, ask the target if it 160 // wants to run some passes. 161 PassConfig->addPreRegBankSelect(); 162 163 if (PassConfig->addRegBankSelect()) 164 return nullptr; 165 166 PassConfig->addPreGlobalInstructionSelect(); 167 168 if (PassConfig->addGlobalInstructionSelect()) 169 return nullptr; 170 171 // Pass to reset the MachineFunction if the ISel failed. 172 PM.add(createResetMachineFunctionPass()); 173 174 // Provide a fallback path when we do not want to abort on 175 // not-yet-supported input. 176 if (LLVM_UNLIKELY(!PassConfig->isGlobalISelAbortEnabled()) && 177 PassConfig->addInstSelector()) 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 Options.MCOptions); 229 auto FOut = llvm::make_unique<formatted_raw_ostream>(Out); 230 MCStreamer *S = getTarget().createAsmStreamer( 231 *Context, std::move(FOut), Options.MCOptions.AsmVerbose, 232 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB, 233 Options.MCOptions.ShowMCInst); 234 AsmStreamer.reset(S); 235 break; 236 } 237 case CGFT_ObjectFile: { 238 // Create the code emitter for the target if it exists. If not, .o file 239 // emission fails. 240 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 241 MCAsmBackend *MAB = 242 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU, 243 Options.MCOptions); 244 if (!MCE || !MAB) 245 return true; 246 247 // Don't waste memory on names of temp labels. 248 Context->setUseNamesOnTempLabels(false); 249 250 Triple T(getTargetTriple().str()); 251 AsmStreamer.reset(getTarget().createMCObjectStreamer( 252 T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 253 Options.MCOptions.MCIncrementalLinkerCompatible, 254 /*DWARFMustBeAtTheEnd*/ true)); 255 break; 256 } 257 case CGFT_Null: 258 // The Null output is intended for use for performance analysis and testing, 259 // not real users. 260 AsmStreamer.reset(getTarget().createNullStreamer(*Context)); 261 break; 262 } 263 264 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 265 FunctionPass *Printer = 266 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 267 if (!Printer) 268 return true; 269 270 PM.add(Printer); 271 PM.add(createFreeMachineFunctionPass()); 272 273 return false; 274 } 275 276 /// addPassesToEmitMC - Add passes to the specified pass manager to get 277 /// machine code emitted with the MCJIT. This method returns true if machine 278 /// code is not supported. It fills the MCContext Ctx pointer which can be 279 /// used to build custom MCStreamer. 280 /// 281 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 282 raw_pwrite_stream &Out, 283 bool DisableVerify) { 284 // Add common CodeGen passes. 285 Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr, 286 nullptr); 287 if (!Ctx) 288 return true; 289 290 if (Options.MCOptions.MCSaveTempLabels) 291 Ctx->setAllowTemporaryLabels(false); 292 293 // Create the code emitter for the target if it exists. If not, .o file 294 // emission fails. 295 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 296 MCCodeEmitter *MCE = 297 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 298 MCAsmBackend *MAB = 299 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU, 300 Options.MCOptions); 301 if (!MCE || !MAB) 302 return true; 303 304 const Triple &T = getTargetTriple(); 305 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 306 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 307 T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 308 Options.MCOptions.MCIncrementalLinkerCompatible, 309 /*DWARFMustBeAtTheEnd*/ true)); 310 311 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 312 FunctionPass *Printer = 313 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 314 if (!Printer) 315 return true; 316 317 PM.add(Printer); 318 PM.add(createFreeMachineFunctionPass()); 319 320 return false; // success! 321 } 322