1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the LLVMTargetMachine class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/Passes.h" 14 #include "llvm/CodeGen/AsmPrinter.h" 15 #include "llvm/CodeGen/BasicTTIImpl.h" 16 #include "llvm/CodeGen/MachineModuleInfo.h" 17 #include "llvm/CodeGen/Passes.h" 18 #include "llvm/CodeGen/TargetPassConfig.h" 19 #include "llvm/IR/LegacyPassManager.h" 20 #include "llvm/MC/MCAsmBackend.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 #include "llvm/MC/MCCodeEmitter.h" 23 #include "llvm/MC/MCContext.h" 24 #include "llvm/MC/MCInstrInfo.h" 25 #include "llvm/MC/MCObjectWriter.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/MC/MCSubtargetInfo.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/FormattedStream.h" 31 #include "llvm/Support/TargetRegistry.h" 32 #include "llvm/Target/TargetLoweringObjectFile.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Target/TargetOptions.h" 35 using namespace llvm; 36 37 static cl::opt<bool> EnableTrapUnreachable("trap-unreachable", 38 cl::Hidden, cl::ZeroOrMore, cl::init(false), 39 cl::desc("Enable generating trap for unreachable")); 40 41 void LLVMTargetMachine::initAsmInfo() { 42 MRI.reset(TheTarget.createMCRegInfo(getTargetTriple().str())); 43 assert(MRI && "Unable to create reg info"); 44 MII.reset(TheTarget.createMCInstrInfo()); 45 assert(MII && "Unable to create instruction info"); 46 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due 47 // to some backends having subtarget feature dependent module level 48 // code generation. This is similar to the hack in the AsmPrinter for 49 // module level assembly etc. 50 STI.reset(TheTarget.createMCSubtargetInfo( 51 getTargetTriple().str(), getTargetCPU(), getTargetFeatureString())); 52 assert(STI && "Unable to create subtarget info"); 53 54 MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo( 55 *MRI, getTargetTriple().str(), Options.MCOptions); 56 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0, 57 // and if the old one gets included then MCAsmInfo will be NULL and 58 // we'll crash later. 59 // Provide the user with a useful error message about what's wrong. 60 assert(TmpAsmInfo && "MCAsmInfo not initialized. " 61 "Make sure you include the correct TargetSelect.h" 62 "and that InitializeAllTargetMCs() is being invoked!"); 63 64 if (Options.DisableIntegratedAS) 65 TmpAsmInfo->setUseIntegratedAssembler(false); 66 67 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments); 68 69 TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections); 70 71 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations); 72 73 if (Options.ExceptionModel != ExceptionHandling::None) 74 TmpAsmInfo->setExceptionsType(Options.ExceptionModel); 75 76 AsmInfo.reset(TmpAsmInfo); 77 } 78 79 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 80 StringRef DataLayoutString, 81 const Triple &TT, StringRef CPU, 82 StringRef FS, const TargetOptions &Options, 83 Reloc::Model RM, CodeModel::Model CM, 84 CodeGenOpt::Level OL) 85 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) { 86 this->RM = RM; 87 this->CMModel = CM; 88 this->OptLevel = OL; 89 90 if (EnableTrapUnreachable) 91 this->Options.TrapUnreachable = true; 92 } 93 94 TargetTransformInfo 95 LLVMTargetMachine::getTargetTransformInfo(const Function &F) { 96 return TargetTransformInfo(BasicTTIImpl(this, F)); 97 } 98 99 /// addPassesToX helper drives creation and initialization of TargetPassConfig. 100 static TargetPassConfig * 101 addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM, 102 bool DisableVerify, 103 MachineModuleInfoWrapperPass &MMIWP) { 104 // Targets may override createPassConfig to provide a target-specific 105 // subclass. 106 TargetPassConfig *PassConfig = TM.createPassConfig(PM); 107 // Set PassConfig options provided by TargetMachine. 108 PassConfig->setDisableVerify(DisableVerify); 109 PM.add(PassConfig); 110 PM.add(&MMIWP); 111 112 if (PassConfig->addISelPasses()) 113 return nullptr; 114 PassConfig->addMachinePasses(); 115 PassConfig->setInitialized(); 116 return PassConfig; 117 } 118 119 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM, 120 raw_pwrite_stream &Out, 121 raw_pwrite_stream *DwoOut, 122 CodeGenFileType FileType, 123 MCContext &Context) { 124 if (Options.MCOptions.MCSaveTempLabels) 125 Context.setAllowTemporaryLabels(false); 126 127 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 128 const MCAsmInfo &MAI = *getMCAsmInfo(); 129 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 130 const MCInstrInfo &MII = *getMCInstrInfo(); 131 132 std::unique_ptr<MCStreamer> AsmStreamer; 133 134 switch (FileType) { 135 case CGFT_AssemblyFile: { 136 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter( 137 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI); 138 139 // Create a code emitter if asked to show the encoding. 140 std::unique_ptr<MCCodeEmitter> MCE; 141 if (Options.MCOptions.ShowMCEncoding) 142 MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context)); 143 144 std::unique_ptr<MCAsmBackend> MAB( 145 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions)); 146 auto FOut = std::make_unique<formatted_raw_ostream>(Out); 147 MCStreamer *S = getTarget().createAsmStreamer( 148 Context, std::move(FOut), Options.MCOptions.AsmVerbose, 149 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE), 150 std::move(MAB), Options.MCOptions.ShowMCInst); 151 AsmStreamer.reset(S); 152 break; 153 } 154 case CGFT_ObjectFile: { 155 // Create the code emitter for the target if it exists. If not, .o file 156 // emission fails. 157 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context); 158 MCAsmBackend *MAB = 159 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions); 160 if (!MCE || !MAB) 161 return true; 162 163 Triple T(getTargetTriple().str()); 164 AsmStreamer.reset(getTarget().createMCObjectStreamer( 165 T, Context, std::unique_ptr<MCAsmBackend>(MAB), 166 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut) 167 : MAB->createObjectWriter(Out), 168 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll, 169 Options.MCOptions.MCIncrementalLinkerCompatible, 170 /*DWARFMustBeAtTheEnd*/ true)); 171 break; 172 } 173 case CGFT_Null: 174 // The Null output is intended for use for performance analysis and testing, 175 // not real users. 176 AsmStreamer.reset(getTarget().createNullStreamer(Context)); 177 break; 178 } 179 180 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 181 FunctionPass *Printer = 182 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 183 if (!Printer) 184 return true; 185 186 PM.add(Printer); 187 return false; 188 } 189 190 bool LLVMTargetMachine::addPassesToEmitFile( 191 PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, 192 CodeGenFileType FileType, bool DisableVerify, 193 MachineModuleInfoWrapperPass *MMIWP) { 194 // Add common CodeGen passes. 195 if (!MMIWP) 196 MMIWP = new MachineModuleInfoWrapperPass(this); 197 TargetPassConfig *PassConfig = 198 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP); 199 if (!PassConfig) 200 return true; 201 202 if (TargetPassConfig::willCompleteCodeGenPipeline()) { 203 if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext())) 204 return true; 205 } else { 206 // MIR printing is redundant with -filetype=null. 207 if (FileType != CGFT_Null) 208 PM.add(createPrintMIRPass(Out)); 209 } 210 211 PM.add(createFreeMachineFunctionPass()); 212 return false; 213 } 214 215 /// addPassesToEmitMC - Add passes to the specified pass manager to get 216 /// machine code emitted with the MCJIT. This method returns true if machine 217 /// code is not supported. It fills the MCContext Ctx pointer which can be 218 /// used to build custom MCStreamer. 219 /// 220 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 221 raw_pwrite_stream &Out, 222 bool DisableVerify) { 223 // Add common CodeGen passes. 224 MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this); 225 TargetPassConfig *PassConfig = 226 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP); 227 if (!PassConfig) 228 return true; 229 assert(TargetPassConfig::willCompleteCodeGenPipeline() && 230 "Cannot emit MC with limited codegen pipeline"); 231 232 Ctx = &MMIWP->getMMI().getContext(); 233 if (Options.MCOptions.MCSaveTempLabels) 234 Ctx->setAllowTemporaryLabels(false); 235 236 // Create the code emitter for the target if it exists. If not, .o file 237 // emission fails. 238 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 239 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 240 MCCodeEmitter *MCE = 241 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 242 MCAsmBackend *MAB = 243 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions); 244 if (!MCE || !MAB) 245 return true; 246 247 const Triple &T = getTargetTriple(); 248 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 249 T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out), 250 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll, 251 Options.MCOptions.MCIncrementalLinkerCompatible, 252 /*DWARFMustBeAtTheEnd*/ true)); 253 254 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 255 FunctionPass *Printer = 256 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 257 if (!Printer) 258 return true; 259 260 PM.add(Printer); 261 PM.add(createFreeMachineFunctionPass()); 262 263 return false; // success! 264 } 265