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