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
initAsmInfo()45 void LLVMTargetMachine::initAsmInfo() {
46 MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
47 MII = TheTarget.createMCInstrInfo();
48 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
49 // to some backends having subtarget feature dependent module level
50 // code generation. This is similar to the hack in the AsmPrinter for
51 // module level assembly etc.
52 STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
53 getTargetFeatureString());
54
55 MCAsmInfo *TmpAsmInfo =
56 TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
57 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
58 // and if the old one gets included then MCAsmInfo will be NULL and
59 // we'll crash later.
60 // Provide the user with a useful error message about what's wrong.
61 assert(TmpAsmInfo && "MCAsmInfo not initialized. "
62 "Make sure you include the correct TargetSelect.h"
63 "and that InitializeAllTargetMCs() is being invoked!");
64
65 if (Options.DisableIntegratedAS)
66 TmpAsmInfo->setUseIntegratedAssembler(false);
67
68 if (Options.CompressDebugSections)
69 TmpAsmInfo->setCompressDebugSections(true);
70
71 AsmInfo = TmpAsmInfo;
72 }
73
LLVMTargetMachine(const Target & T,StringRef DataLayoutString,const Triple & TT,StringRef CPU,StringRef FS,TargetOptions Options,Reloc::Model RM,CodeModel::Model CM,CodeGenOpt::Level OL)74 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
75 StringRef DataLayoutString,
76 const Triple &TT, StringRef CPU,
77 StringRef FS, TargetOptions Options,
78 Reloc::Model RM, CodeModel::Model CM,
79 CodeGenOpt::Level OL)
80 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
81 CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL);
82 }
83
getTargetIRAnalysis()84 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
85 return TargetIRAnalysis([this](Function &F) {
86 return TargetTransformInfo(BasicTTIImpl(this, F));
87 });
88 }
89
90 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
91 static MCContext *
addPassesToGenerateCode(LLVMTargetMachine * TM,PassManagerBase & PM,bool DisableVerify,AnalysisID StartBefore,AnalysisID StartAfter,AnalysisID StopAfter,MachineFunctionInitializer * MFInitializer=nullptr)92 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
93 bool DisableVerify, AnalysisID StartBefore,
94 AnalysisID StartAfter, AnalysisID StopAfter,
95 MachineFunctionInitializer *MFInitializer = nullptr) {
96
97 // Add internal analysis passes from the target machine.
98 PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
99
100 // Targets may override createPassConfig to provide a target-specific
101 // subclass.
102 TargetPassConfig *PassConfig = TM->createPassConfig(PM);
103 PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
104
105 // Set PassConfig options provided by TargetMachine.
106 PassConfig->setDisableVerify(DisableVerify);
107
108 PM.add(PassConfig);
109
110 PassConfig->addIRPasses();
111
112 PassConfig->addCodeGenPrepare();
113
114 PassConfig->addPassesToHandleExceptions();
115
116 PassConfig->addISelPrepare();
117
118 // Install a MachineModuleInfo class, which is an immutable pass that holds
119 // all the per-module stuff we're generating, including MCContext.
120 MachineModuleInfo *MMI = new MachineModuleInfo(
121 *TM->getMCAsmInfo(), *TM->getMCRegisterInfo(), TM->getObjFileLowering());
122 PM.add(MMI);
123
124 // Set up a MachineFunction for the rest of CodeGen to work on.
125 PM.add(new MachineFunctionAnalysis(*TM, MFInitializer));
126
127 // Enable FastISel with -fast, but allow that to be overridden.
128 if (EnableFastISelOption == cl::BOU_TRUE ||
129 (TM->getOptLevel() == CodeGenOpt::None &&
130 EnableFastISelOption != cl::BOU_FALSE))
131 TM->setFastISel(true);
132
133 // Ask the target for an isel.
134 if (PassConfig->addInstSelector())
135 return nullptr;
136
137 PassConfig->addMachinePasses();
138
139 PassConfig->setInitialized();
140
141 return &MMI->getContext();
142 }
143
addPassesToEmitFile(PassManagerBase & PM,raw_pwrite_stream & Out,CodeGenFileType FileType,bool DisableVerify,AnalysisID StartBefore,AnalysisID StartAfter,AnalysisID StopAfter,MachineFunctionInitializer * MFInitializer)144 bool LLVMTargetMachine::addPassesToEmitFile(
145 PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
146 bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
147 AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
148 // Add common CodeGen passes.
149 MCContext *Context =
150 addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
151 StopAfter, MFInitializer);
152 if (!Context)
153 return true;
154
155 if (StopAfter) {
156 PM.add(createPrintMIRPass(outs()));
157 return false;
158 }
159
160 if (Options.MCOptions.MCSaveTempLabels)
161 Context->setAllowTemporaryLabels(false);
162
163 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
164 const MCAsmInfo &MAI = *getMCAsmInfo();
165 const MCRegisterInfo &MRI = *getMCRegisterInfo();
166 const MCInstrInfo &MII = *getMCInstrInfo();
167
168 std::unique_ptr<MCStreamer> AsmStreamer;
169
170 switch (FileType) {
171 case CGFT_AssemblyFile: {
172 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
173 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
174
175 // Create a code emitter if asked to show the encoding.
176 MCCodeEmitter *MCE = nullptr;
177 if (Options.MCOptions.ShowMCEncoding)
178 MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
179
180 MCAsmBackend *MAB =
181 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
182 auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
183 MCStreamer *S = getTarget().createAsmStreamer(
184 *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
185 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
186 Options.MCOptions.ShowMCInst);
187 AsmStreamer.reset(S);
188 break;
189 }
190 case CGFT_ObjectFile: {
191 // Create the code emitter for the target if it exists. If not, .o file
192 // emission fails.
193 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
194 MCAsmBackend *MAB =
195 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
196 if (!MCE || !MAB)
197 return true;
198
199 // Don't waste memory on names of temp labels.
200 Context->setUseNamesOnTempLabels(false);
201
202 Triple T(getTargetTriple().str());
203 AsmStreamer.reset(getTarget().createMCObjectStreamer(
204 T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
205 /*DWARFMustBeAtTheEnd*/ true));
206 break;
207 }
208 case CGFT_Null:
209 // The Null output is intended for use for performance analysis and testing,
210 // not real users.
211 AsmStreamer.reset(getTarget().createNullStreamer(*Context));
212 break;
213 }
214
215 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
216 FunctionPass *Printer =
217 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
218 if (!Printer)
219 return true;
220
221 PM.add(Printer);
222
223 return false;
224 }
225
226 /// addPassesToEmitMC - Add passes to the specified pass manager to get
227 /// machine code emitted with the MCJIT. This method returns true if machine
228 /// code is not supported. It fills the MCContext Ctx pointer which can be
229 /// used to build custom MCStreamer.
230 ///
addPassesToEmitMC(PassManagerBase & PM,MCContext * & Ctx,raw_pwrite_stream & Out,bool DisableVerify)231 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
232 raw_pwrite_stream &Out,
233 bool DisableVerify) {
234 // Add common CodeGen passes.
235 Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
236 nullptr);
237 if (!Ctx)
238 return true;
239
240 if (Options.MCOptions.MCSaveTempLabels)
241 Ctx->setAllowTemporaryLabels(false);
242
243 // Create the code emitter for the target if it exists. If not, .o file
244 // emission fails.
245 const MCRegisterInfo &MRI = *getMCRegisterInfo();
246 MCCodeEmitter *MCE =
247 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
248 MCAsmBackend *MAB =
249 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
250 if (!MCE || !MAB)
251 return true;
252
253 const Triple &T = getTargetTriple();
254 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
255 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
256 T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
257 /*DWARFMustBeAtTheEnd*/ true));
258
259 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
260 FunctionPass *Printer =
261 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
262 if (!Printer)
263 return true;
264
265 PM.add(Printer);
266
267 return false; // success!
268 }
269