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