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/CodeGen/TargetPassConfig.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Scalar.h"
37 using namespace llvm;
38 
39 // Enable or disable FastISel. Both options are needed, because
40 // FastISel is enabled by default with -fast, and we wish to be
41 // able to enable or disable fast-isel independently from -O0.
42 static cl::opt<cl::boolOrDefault>
43 EnableFastISelOption("fast-isel", cl::Hidden,
44   cl::desc("Enable the \"fast\" instruction selector"));
45 
46 static cl::opt<bool>
47     EnableGlobalISel("global-isel", cl::Hidden, cl::init(false),
48                      cl::desc("Enable the \"global\" instruction selector"));
49 
50 void LLVMTargetMachine::initAsmInfo() {
51   MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
52   MII = TheTarget.createMCInstrInfo();
53   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
54   // to some backends having subtarget feature dependent module level
55   // code generation. This is similar to the hack in the AsmPrinter for
56   // module level assembly etc.
57   STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
58                                         getTargetFeatureString());
59 
60   MCAsmInfo *TmpAsmInfo =
61       TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
62   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
63   // and if the old one gets included then MCAsmInfo will be NULL and
64   // we'll crash later.
65   // Provide the user with a useful error message about what's wrong.
66   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
67          "Make sure you include the correct TargetSelect.h"
68          "and that InitializeAllTargetMCs() is being invoked!");
69 
70   if (Options.DisableIntegratedAS)
71     TmpAsmInfo->setUseIntegratedAssembler(false);
72 
73   TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
74 
75   if (Options.CompressDebugSections)
76     TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
77 
78   TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
79 
80   if (Options.ExceptionModel != ExceptionHandling::None)
81     TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
82 
83   AsmInfo = TmpAsmInfo;
84 }
85 
86 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
87                                      StringRef DataLayoutString,
88                                      const Triple &TT, StringRef CPU,
89                                      StringRef FS, TargetOptions Options,
90                                      Reloc::Model RM, CodeModel::Model CM,
91                                      CodeGenOpt::Level OL)
92     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
93   T.adjustCodeGenOpts(TT, RM, CM);
94   this->RM = RM;
95   this->CMModel = CM;
96   this->OptLevel = OL;
97 }
98 
99 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
100   return TargetIRAnalysis([this](const Function &F) {
101     return TargetTransformInfo(BasicTTIImpl(this, F));
102   });
103 }
104 
105 MachineModuleInfo &
106 LLVMTargetMachine::addMachineModuleInfo(PassManagerBase &PM) const {
107   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
108                                                  *getMCRegisterInfo(),
109                                                  getObjFileLowering());
110   PM.add(MMI);
111   return *MMI;
112 }
113 
114 void LLVMTargetMachine::addMachineFunctionAnalysis(PassManagerBase &PM,
115     MachineFunctionInitializer *MFInitializer) const {
116   PM.add(new MachineFunctionAnalysis(*this, MFInitializer));
117 }
118 
119 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
120 static MCContext *
121 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
122                         bool DisableVerify, AnalysisID StartBefore,
123                         AnalysisID StartAfter, AnalysisID StopAfter,
124                         MachineFunctionInitializer *MFInitializer = nullptr) {
125 
126   // When in emulated TLS mode, add the LowerEmuTLS pass.
127   if (TM->Options.EmulatedTLS)
128     PM.add(createLowerEmuTLSPass(TM));
129 
130   PM.add(createPreISelIntrinsicLoweringPass());
131 
132   // Add internal analysis passes from the target machine.
133   PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
134 
135   // Targets may override createPassConfig to provide a target-specific
136   // subclass.
137   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
138   PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
139 
140   // Set PassConfig options provided by TargetMachine.
141   PassConfig->setDisableVerify(DisableVerify);
142 
143   PM.add(PassConfig);
144 
145   PassConfig->addIRPasses();
146 
147   PassConfig->addCodeGenPrepare();
148 
149   PassConfig->addPassesToHandleExceptions();
150 
151   PassConfig->addISelPrepare();
152 
153   MachineModuleInfo &MMI = TM->addMachineModuleInfo(PM);
154   TM->addMachineFunctionAnalysis(PM, MFInitializer);
155 
156   // Enable FastISel with -fast, but allow that to be overridden.
157   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
158   if (EnableFastISelOption == cl::BOU_TRUE ||
159       (TM->getOptLevel() == CodeGenOpt::None &&
160        TM->getO0WantsFastISel()))
161     TM->setFastISel(true);
162 
163   // Ask the target for an isel.
164   if (LLVM_UNLIKELY(EnableGlobalISel)) {
165     if (PassConfig->addIRTranslator())
166       return nullptr;
167 
168     PassConfig->addPreLegalizeMachineIR();
169 
170     if (PassConfig->addLegalizeMachineIR())
171       return nullptr;
172 
173     // Before running the register bank selector, ask the target if it
174     // wants to run some passes.
175     PassConfig->addPreRegBankSelect();
176 
177     if (PassConfig->addRegBankSelect())
178       return nullptr;
179 
180     PassConfig->addPreGlobalInstructionSelect();
181 
182     if (PassConfig->addGlobalInstructionSelect())
183       return nullptr;
184 
185   } else if (PassConfig->addInstSelector())
186     return nullptr;
187 
188   PassConfig->addMachinePasses();
189 
190   PassConfig->setInitialized();
191 
192   return &MMI.getContext();
193 }
194 
195 bool LLVMTargetMachine::addPassesToEmitFile(
196     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
197     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
198     AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
199   // Add common CodeGen passes.
200   MCContext *Context =
201       addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
202                               StopAfter, MFInitializer);
203   if (!Context)
204     return true;
205 
206   if (StopAfter) {
207     PM.add(createPrintMIRPass(Out));
208     return false;
209   }
210 
211   if (Options.MCOptions.MCSaveTempLabels)
212     Context->setAllowTemporaryLabels(false);
213 
214   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
215   const MCAsmInfo &MAI = *getMCAsmInfo();
216   const MCRegisterInfo &MRI = *getMCRegisterInfo();
217   const MCInstrInfo &MII = *getMCInstrInfo();
218 
219   std::unique_ptr<MCStreamer> AsmStreamer;
220 
221   switch (FileType) {
222   case CGFT_AssemblyFile: {
223     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
224         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
225 
226     // Create a code emitter if asked to show the encoding.
227     MCCodeEmitter *MCE = nullptr;
228     if (Options.MCOptions.ShowMCEncoding)
229       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
230 
231     MCAsmBackend *MAB =
232         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
233                                        Options.MCOptions);
234     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
235     MCStreamer *S = getTarget().createAsmStreamer(
236         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
237         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
238         Options.MCOptions.ShowMCInst);
239     AsmStreamer.reset(S);
240     break;
241   }
242   case CGFT_ObjectFile: {
243     // Create the code emitter for the target if it exists.  If not, .o file
244     // emission fails.
245     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
246     MCAsmBackend *MAB =
247         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
248                                        Options.MCOptions);
249     if (!MCE || !MAB)
250       return true;
251 
252     // Don't waste memory on names of temp labels.
253     Context->setUseNamesOnTempLabels(false);
254 
255     Triple T(getTargetTriple().str());
256     AsmStreamer.reset(getTarget().createMCObjectStreamer(
257         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
258         Options.MCOptions.MCIncrementalLinkerCompatible,
259         /*DWARFMustBeAtTheEnd*/ true));
260     break;
261   }
262   case CGFT_Null:
263     // The Null output is intended for use for performance analysis and testing,
264     // not real users.
265     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
266     break;
267   }
268 
269   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
270   FunctionPass *Printer =
271       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
272   if (!Printer)
273     return true;
274 
275   PM.add(Printer);
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);
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 
323   return false; // success!
324 }
325