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