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->getMCRegisterInfo(), TM->getObjFileLowering());
119   PM.add(MMI);
120
121   // Set up a MachineFunction for the rest of CodeGen to work on.
122   PM.add(new MachineFunctionAnalysis(*TM));
123
124   // Enable FastISel with -fast, but allow that to be overridden.
125   if (EnableFastISelOption == cl::BOU_TRUE ||
126       (TM->getOptLevel() == CodeGenOpt::None &&
127        EnableFastISelOption != cl::BOU_FALSE))
128     TM->setFastISel(true);
129
130   // Ask the target for an isel.
131   if (PassConfig->addInstSelector())
132     return nullptr;
133
134   PassConfig->addMachinePasses();
135
136   PassConfig->setInitialized();
137
138   return &MMI->getContext();
139 }
140
141 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
142                                             formatted_raw_ostream &Out,
143                                             CodeGenFileType FileType,
144                                             bool DisableVerify,
145                                             AnalysisID StartAfter,
146                                             AnalysisID StopAfter) {
147   // Add common CodeGen passes.
148   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
149                                                StartAfter, StopAfter);
150   if (!Context)
151     return true;
152
153   if (StopAfter) {
154     // FIXME: The intent is that this should eventually write out a YAML file,
155     // containing the LLVM IR, the machine-level IR (when stopping after a
156     // machine-level pass), and whatever other information is needed to
157     // deserialize the code and resume compilation.  For now, just write the
158     // LLVM IR.
159     PM.add(createPrintModulePass(Out));
160     return false;
161   }
162
163   if (Options.MCOptions.MCSaveTempLabels)
164     Context->setAllowTemporaryLabels(false);
165
166   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
167   const MCAsmInfo &MAI = *getMCAsmInfo();
168   const MCRegisterInfo &MRI = *getMCRegisterInfo();
169   const MCInstrInfo &MII = *getMCInstrInfo();
170
171   std::unique_ptr<MCStreamer> AsmStreamer;
172
173   switch (FileType) {
174   case CGFT_AssemblyFile: {
175     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
176         MAI.getAssemblerDialect(), MAI, MII, MRI, STI);
177
178     // Create a code emitter if asked to show the encoding.
179     MCCodeEmitter *MCE = nullptr;
180     if (Options.MCOptions.ShowMCEncoding)
181       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
182
183     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
184                                                        TargetCPU);
185     MCStreamer *S = getTarget().createAsmStreamer(
186         *Context, Out, Options.MCOptions.AsmVerbose,
187         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
188         Options.MCOptions.ShowMCInst);
189     AsmStreamer.reset(S);
190     break;
191   }
192   case CGFT_ObjectFile: {
193     // Create the code emitter for the target if it exists.  If not, .o file
194     // emission fails.
195     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
196     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
197                                                        TargetCPU);
198     if (!MCE || !MAB)
199       return true;
200
201     Triple T(getTargetTriple());
202     AsmStreamer.reset(getTarget().createMCObjectStreamer(
203         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll));
204     break;
205   }
206   case CGFT_Null:
207     // The Null output is intended for use for performance analysis and testing,
208     // not real users.
209     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
210     break;
211   }
212
213   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
214   FunctionPass *Printer =
215       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
216   if (!Printer)
217     return true;
218
219   PM.add(Printer);
220
221   return false;
222 }
223
224 /// addPassesToEmitMC - Add passes to the specified pass manager to get
225 /// machine code emitted with the MCJIT. This method returns true if machine
226 /// code is not supported. It fills the MCContext Ctx pointer which can be
227 /// used to build custom MCStreamer.
228 ///
229 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
230                                           MCContext *&Ctx,
231                                           raw_ostream &Out,
232                                           bool DisableVerify) {
233   // Add common CodeGen passes.
234   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr);
235   if (!Ctx)
236     return true;
237
238   if (Options.MCOptions.MCSaveTempLabels)
239     Ctx->setAllowTemporaryLabels(false);
240
241   // Create the code emitter for the target if it exists.  If not, .o file
242   // emission fails.
243   const MCRegisterInfo &MRI = *getMCRegisterInfo();
244   MCCodeEmitter *MCE =
245       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
246   MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
247                                                      TargetCPU);
248   if (!MCE || !MAB)
249     return true;
250
251   Triple T(getTargetTriple());
252   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
253   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
254       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll));
255
256   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
257   FunctionPass *Printer =
258       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
259   if (!Printer)
260     return true;
261
262   PM.add(Printer);
263
264   return false; // success!
265 }