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<cl::boolOrDefault>
46     EnableGlobalISel("global-isel", cl::Hidden,
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, const 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   // Enable GlobalISel if the target wants to, but allow that to be overriden.
153   if (EnableGlobalISel == cl::BOU_TRUE || (EnableGlobalISel == cl::BOU_UNSET &&
154                                            PassConfig->isGlobalISelEnabled())) {
155     if (PassConfig->addIRTranslator())
156       return nullptr;
157 
158     PassConfig->addPreLegalizeMachineIR();
159 
160     if (PassConfig->addLegalizeMachineIR())
161       return nullptr;
162 
163     // Before running the register bank selector, ask the target if it
164     // wants to run some passes.
165     PassConfig->addPreRegBankSelect();
166 
167     if (PassConfig->addRegBankSelect())
168       return nullptr;
169 
170     PassConfig->addPreGlobalInstructionSelect();
171 
172     if (PassConfig->addGlobalInstructionSelect())
173       return nullptr;
174 
175     // Pass to reset the MachineFunction if the ISel failed.
176     PM.add(createResetMachineFunctionPass(
177         PassConfig->reportDiagnosticWhenGlobalISelFallback(),
178         PassConfig->isGlobalISelAbortEnabled()));
179 
180     // Provide a fallback path when we do not want to abort on
181     // not-yet-supported input.
182     if (!PassConfig->isGlobalISelAbortEnabled() &&
183         PassConfig->addInstSelector())
184       return nullptr;
185 
186   } else if (PassConfig->addInstSelector())
187     return nullptr;
188 
189   PassConfig->addMachinePasses();
190 
191   PassConfig->setInitialized();
192 
193   return &MMI->getContext();
194 }
195 
196 bool LLVMTargetMachine::addPassesToEmitFile(
197     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
198     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
199     AnalysisID StopBefore, AnalysisID StopAfter,
200     MachineFunctionInitializer *MFInitializer) {
201   // Add common CodeGen passes.
202   MCContext *Context =
203       addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
204                               StopBefore, StopAfter, MFInitializer);
205   if (!Context)
206     return true;
207 
208   if (StopBefore || StopAfter) {
209     PM.add(createPrintMIRPass(Out));
210     return false;
211   }
212 
213   if (Options.MCOptions.MCSaveTempLabels)
214     Context->setAllowTemporaryLabels(false);
215 
216   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
217   const MCAsmInfo &MAI = *getMCAsmInfo();
218   const MCRegisterInfo &MRI = *getMCRegisterInfo();
219   const MCInstrInfo &MII = *getMCInstrInfo();
220 
221   std::unique_ptr<MCStreamer> AsmStreamer;
222 
223   switch (FileType) {
224   case CGFT_AssemblyFile: {
225     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
226         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
227 
228     // Create a code emitter if asked to show the encoding.
229     MCCodeEmitter *MCE = nullptr;
230     if (Options.MCOptions.ShowMCEncoding)
231       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
232 
233     MCAsmBackend *MAB =
234         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
235                                        Options.MCOptions);
236     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
237     MCStreamer *S = getTarget().createAsmStreamer(
238         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
239         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
240         Options.MCOptions.ShowMCInst);
241     AsmStreamer.reset(S);
242     break;
243   }
244   case CGFT_ObjectFile: {
245     // Create the code emitter for the target if it exists.  If not, .o file
246     // emission fails.
247     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
248     MCAsmBackend *MAB =
249         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
250                                        Options.MCOptions);
251     if (!MCE || !MAB)
252       return true;
253 
254     // Don't waste memory on names of temp labels.
255     Context->setUseNamesOnTempLabels(false);
256 
257     Triple T(getTargetTriple().str());
258     AsmStreamer.reset(getTarget().createMCObjectStreamer(
259         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
260         Options.MCOptions.MCIncrementalLinkerCompatible,
261         /*DWARFMustBeAtTheEnd*/ true));
262     break;
263   }
264   case CGFT_Null:
265     // The Null output is intended for use for performance analysis and testing,
266     // not real users.
267     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
268     break;
269   }
270 
271   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
272   FunctionPass *Printer =
273       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
274   if (!Printer)
275     return true;
276 
277   PM.add(Printer);
278   PM.add(createFreeMachineFunctionPass());
279 
280   return false;
281 }
282 
283 /// addPassesToEmitMC - Add passes to the specified pass manager to get
284 /// machine code emitted with the MCJIT. This method returns true if machine
285 /// code is not supported. It fills the MCContext Ctx pointer which can be
286 /// used to build custom MCStreamer.
287 ///
288 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
289                                           raw_pwrite_stream &Out,
290                                           bool DisableVerify) {
291   // Add common CodeGen passes.
292   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
293                                 nullptr, nullptr);
294   if (!Ctx)
295     return true;
296 
297   if (Options.MCOptions.MCSaveTempLabels)
298     Ctx->setAllowTemporaryLabels(false);
299 
300   // Create the code emitter for the target if it exists.  If not, .o file
301   // emission fails.
302   const MCRegisterInfo &MRI = *getMCRegisterInfo();
303   MCCodeEmitter *MCE =
304       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
305   MCAsmBackend *MAB =
306       getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
307                                      Options.MCOptions);
308   if (!MCE || !MAB)
309     return true;
310 
311   const Triple &T = getTargetTriple();
312   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
313   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
314       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
315       Options.MCOptions.MCIncrementalLinkerCompatible,
316       /*DWARFMustBeAtTheEnd*/ true));
317 
318   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
319   FunctionPass *Printer =
320       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
321   if (!Printer)
322     return true;
323 
324   PM.add(Printer);
325   PM.add(createFreeMachineFunctionPass());
326 
327   return false; // success!
328 }
329