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   } else if (PassConfig->addInstSelector())
172     return nullptr;
173 
174   PassConfig->addMachinePasses();
175 
176   PassConfig->setInitialized();
177 
178   return &MMI->getContext();
179 }
180 
181 bool LLVMTargetMachine::addPassesToEmitFile(
182     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
183     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
184     AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
185   // Add common CodeGen passes.
186   MCContext *Context =
187       addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
188                               StopAfter, MFInitializer);
189   if (!Context)
190     return true;
191 
192   if (StopAfter) {
193     PM.add(createPrintMIRPass(Out));
194     return false;
195   }
196 
197   if (Options.MCOptions.MCSaveTempLabels)
198     Context->setAllowTemporaryLabels(false);
199 
200   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
201   const MCAsmInfo &MAI = *getMCAsmInfo();
202   const MCRegisterInfo &MRI = *getMCRegisterInfo();
203   const MCInstrInfo &MII = *getMCInstrInfo();
204 
205   std::unique_ptr<MCStreamer> AsmStreamer;
206 
207   switch (FileType) {
208   case CGFT_AssemblyFile: {
209     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
210         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
211 
212     // Create a code emitter if asked to show the encoding.
213     MCCodeEmitter *MCE = nullptr;
214     if (Options.MCOptions.ShowMCEncoding)
215       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
216 
217     MCAsmBackend *MAB =
218         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
219                                        Options.MCOptions);
220     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
221     MCStreamer *S = getTarget().createAsmStreamer(
222         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
223         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
224         Options.MCOptions.ShowMCInst);
225     AsmStreamer.reset(S);
226     break;
227   }
228   case CGFT_ObjectFile: {
229     // Create the code emitter for the target if it exists.  If not, .o file
230     // emission fails.
231     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
232     MCAsmBackend *MAB =
233         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
234                                        Options.MCOptions);
235     if (!MCE || !MAB)
236       return true;
237 
238     // Don't waste memory on names of temp labels.
239     Context->setUseNamesOnTempLabels(false);
240 
241     Triple T(getTargetTriple().str());
242     AsmStreamer.reset(getTarget().createMCObjectStreamer(
243         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
244         Options.MCOptions.MCIncrementalLinkerCompatible,
245         /*DWARFMustBeAtTheEnd*/ true));
246     break;
247   }
248   case CGFT_Null:
249     // The Null output is intended for use for performance analysis and testing,
250     // not real users.
251     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
252     break;
253   }
254 
255   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
256   FunctionPass *Printer =
257       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
258   if (!Printer)
259     return true;
260 
261   PM.add(Printer);
262   PM.add(createFreeMachineFunctionPass());
263 
264   return false;
265 }
266 
267 /// addPassesToEmitMC - Add passes to the specified pass manager to get
268 /// machine code emitted with the MCJIT. This method returns true if machine
269 /// code is not supported. It fills the MCContext Ctx pointer which can be
270 /// used to build custom MCStreamer.
271 ///
272 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
273                                           raw_pwrite_stream &Out,
274                                           bool DisableVerify) {
275   // Add common CodeGen passes.
276   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
277                                 nullptr);
278   if (!Ctx)
279     return true;
280 
281   if (Options.MCOptions.MCSaveTempLabels)
282     Ctx->setAllowTemporaryLabels(false);
283 
284   // Create the code emitter for the target if it exists.  If not, .o file
285   // emission fails.
286   const MCRegisterInfo &MRI = *getMCRegisterInfo();
287   MCCodeEmitter *MCE =
288       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
289   MCAsmBackend *MAB =
290       getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
291                                      Options.MCOptions);
292   if (!MCE || !MAB)
293     return true;
294 
295   const Triple &T = getTargetTriple();
296   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
297   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
298       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
299       Options.MCOptions.MCIncrementalLinkerCompatible,
300       /*DWARFMustBeAtTheEnd*/ true));
301 
302   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
303   FunctionPass *Printer =
304       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
305   if (!Printer)
306     return true;
307 
308   PM.add(Printer);
309   PM.add(createFreeMachineFunctionPass());
310 
311   return false; // success!
312 }
313