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