b7cac3ba381057b029d71965a1cc4a63e6ac5799
[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/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 void LLVMTargetMachine::initAsmInfo() {
46   MRI = TheTarget.createMCRegInfo(getTargetTriple());
47   MII = TheTarget.createMCInstrInfo();
48   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
49   // to some backends having subtarget feature dependent module level
50   // code generation. This is similar to the hack in the AsmPrinter for
51   // module level assembly etc.
52   STI = TheTarget.createMCSubtargetInfo(getTargetTriple(), getTargetCPU(),
53                                         getTargetFeatureString());
54
55   MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(*MRI, getTargetTriple());
56   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
57   // and if the old one gets included then MCAsmInfo will be NULL and
58   // we'll crash later.
59   // Provide the user with a useful error message about what's wrong.
60   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
61          "Make sure you include the correct TargetSelect.h"
62          "and that InitializeAllTargetMCs() is being invoked!");
63
64   if (Options.DisableIntegratedAS)
65     TmpAsmInfo->setUseIntegratedAssembler(false);
66
67   if (Options.CompressDebugSections)
68     TmpAsmInfo->setCompressDebugSections(true);
69
70   AsmInfo = TmpAsmInfo;
71 }
72
73 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
74                                      StringRef DataLayoutString,
75                                      const Triple &TT, StringRef CPU,
76                                      StringRef FS, TargetOptions Options,
77                                      Reloc::Model RM, CodeModel::Model CM,
78                                      CodeGenOpt::Level OL)
79     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
80   CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL);
81 }
82
83 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
84   return TargetIRAnalysis([this](Function &F) {
85     return TargetTransformInfo(BasicTTIImpl(this, F));
86   });
87 }
88
89 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
90 static MCContext *
91 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
92                         bool DisableVerify, AnalysisID StartAfter,
93                         AnalysisID StopAfter,
94                         MachineFunctionInitializer *MFInitializer = nullptr) {
95
96   // Add internal analysis passes from the target machine.
97   PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
98
99   // Targets may override createPassConfig to provide a target-specific
100   // subclass.
101   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
102   PassConfig->setStartStopPasses(StartAfter, StopAfter);
103
104   // Set PassConfig options provided by TargetMachine.
105   PassConfig->setDisableVerify(DisableVerify);
106
107   PM.add(PassConfig);
108
109   PassConfig->addIRPasses();
110
111   PassConfig->addCodeGenPrepare();
112
113   PassConfig->addPassesToHandleExceptions();
114
115   PassConfig->addISelPrepare();
116
117   // Install a MachineModuleInfo class, which is an immutable pass that holds
118   // all the per-module stuff we're generating, including MCContext.
119   MachineModuleInfo *MMI = new MachineModuleInfo(
120       *TM->getMCAsmInfo(), *TM->getMCRegisterInfo(), TM->getObjFileLowering());
121   PM.add(MMI);
122
123   // Set up a MachineFunction for the rest of CodeGen to work on.
124   PM.add(new MachineFunctionAnalysis(*TM, MFInitializer));
125
126   // Enable FastISel with -fast, but allow that to be overridden.
127   if (EnableFastISelOption == cl::BOU_TRUE ||
128       (TM->getOptLevel() == CodeGenOpt::None &&
129        EnableFastISelOption != cl::BOU_FALSE))
130     TM->setFastISel(true);
131
132   // Ask the target for an isel.
133   if (PassConfig->addInstSelector())
134     return nullptr;
135
136   PassConfig->addMachinePasses();
137
138   PassConfig->setInitialized();
139
140   return &MMI->getContext();
141 }
142
143 bool LLVMTargetMachine::addPassesToEmitFile(
144     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
145     bool DisableVerify, AnalysisID StartAfter, AnalysisID StopAfter,
146     MachineFunctionInitializer *MFInitializer) {
147   // Add common CodeGen passes.
148   MCContext *Context = addPassesToGenerateCode(
149       this, PM, DisableVerify, StartAfter, StopAfter, MFInitializer);
150   if (!Context)
151     return true;
152
153   if (StopAfter) {
154     PM.add(createPrintMIRPass(outs()));
155     return false;
156   }
157
158   if (Options.MCOptions.MCSaveTempLabels)
159     Context->setAllowTemporaryLabels(false);
160
161   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
162   const MCAsmInfo &MAI = *getMCAsmInfo();
163   const MCRegisterInfo &MRI = *getMCRegisterInfo();
164   const MCInstrInfo &MII = *getMCInstrInfo();
165
166   std::unique_ptr<MCStreamer> AsmStreamer;
167
168   switch (FileType) {
169   case CGFT_AssemblyFile: {
170     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
171         Triple(getTargetTriple()), MAI.getAssemblerDialect(), MAI, MII, MRI);
172
173     // Create a code emitter if asked to show the encoding.
174     MCCodeEmitter *MCE = nullptr;
175     if (Options.MCOptions.ShowMCEncoding)
176       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
177
178     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
179                                                        TargetCPU);
180     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
181     MCStreamer *S = getTarget().createAsmStreamer(
182         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
183         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
184         Options.MCOptions.ShowMCInst);
185     AsmStreamer.reset(S);
186     break;
187   }
188   case CGFT_ObjectFile: {
189     // Create the code emitter for the target if it exists.  If not, .o file
190     // emission fails.
191     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
192     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
193                                                        TargetCPU);
194     if (!MCE || !MAB)
195       return true;
196
197     // Don't waste memory on names of temp labels.
198     Context->setUseNamesOnTempLabels(false);
199
200     Triple T(getTargetTriple());
201     AsmStreamer.reset(getTarget().createMCObjectStreamer(
202         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
203         /*DWARFMustBeAtTheEnd*/ true));
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, MCContext *&Ctx,
230                                           raw_pwrite_stream &Out,
231                                           bool DisableVerify) {
232   // Add common CodeGen passes.
233   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr);
234   if (!Ctx)
235     return true;
236
237   if (Options.MCOptions.MCSaveTempLabels)
238     Ctx->setAllowTemporaryLabels(false);
239
240   // Create the code emitter for the target if it exists.  If not, .o file
241   // emission fails.
242   const MCRegisterInfo &MRI = *getMCRegisterInfo();
243   MCCodeEmitter *MCE =
244       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
245   MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
246                                                      TargetCPU);
247   if (!MCE || !MAB)
248     return true;
249
250   Triple T(getTargetTriple());
251   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
252   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
253       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
254       /*DWARFMustBeAtTheEnd*/ true));
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 }