Pass a MCSubtargetInfo down to the TargetStreamer creation.
[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/ADT/OwningPtr.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IR/IRPrintingPasses.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include "llvm/Transforms/Scalar.h"
38 using namespace llvm;
39
40 // Enable or disable FastISel. Both options are needed, because
41 // FastISel is enabled by default with -fast, and we wish to be
42 // able to enable or disable fast-isel independently from -O0.
43 static cl::opt<cl::boolOrDefault>
44 EnableFastISelOption("fast-isel", cl::Hidden,
45   cl::desc("Enable the \"fast\" instruction selector"));
46
47 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
48     cl::desc("Show encoding in .s output"));
49 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
50     cl::desc("Show instruction structure in .s output"));
51
52 static cl::opt<cl::boolOrDefault>
53 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
54            cl::init(cl::BOU_UNSET));
55
56 static bool getVerboseAsm() {
57   switch (AsmVerbose) {
58   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
59   case cl::BOU_TRUE:  return true;
60   case cl::BOU_FALSE: return false;
61   }
62   llvm_unreachable("Invalid verbose asm state");
63 }
64
65 void LLVMTargetMachine::initAsmInfo() {
66   AsmInfo = TheTarget.createMCAsmInfo(*getRegisterInfo(), TargetTriple);
67   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
68   // and if the old one gets included then MCAsmInfo will be NULL and
69   // we'll crash later.
70   // Provide the user with a useful error message about what's wrong.
71   assert(AsmInfo && "MCAsmInfo not initialized. "
72          "Make sure you include the correct TargetSelect.h"
73          "and that InitializeAllTargetMCs() is being invoked!");
74 }
75
76 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
77                                      StringRef CPU, StringRef FS,
78                                      TargetOptions Options,
79                                      Reloc::Model RM, CodeModel::Model CM,
80                                      CodeGenOpt::Level OL)
81   : TargetMachine(T, Triple, CPU, FS, Options) {
82   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
83 }
84
85 void LLVMTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
86   PM.add(createBasicTargetTransformInfoPass(this));
87 }
88
89 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
90 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
91                                           PassManagerBase &PM,
92                                           bool DisableVerify,
93                                           AnalysisID StartAfter,
94                                           AnalysisID StopAfter) {
95   // Add internal analysis passes from the target machine.
96   TM->addAnalysisPasses(PM);
97
98   // Targets may override createPassConfig to provide a target-specific sublass.
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 =
118     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
119                           &TM->getTargetLowering()->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 NULL;
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 (hasMCSaveTempLabels())
165     Context->setAllowTemporaryLabels(false);
166
167   const MCAsmInfo &MAI = *getMCAsmInfo();
168   const MCRegisterInfo &MRI = *getRegisterInfo();
169   const MCInstrInfo &MII = *getInstrInfo();
170   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
171   OwningPtr<MCStreamer> AsmStreamer;
172
173   switch (FileType) {
174   case CGFT_AssemblyFile: {
175     MCInstPrinter *InstPrinter =
176       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
177                                       MII, MRI, STI);
178
179     // Create a code emitter if asked to show the encoding.
180     MCCodeEmitter *MCE = 0;
181     if (ShowMCEncoding)
182       MCE = getTarget().createMCCodeEmitter(MII, MRI, STI, *Context);
183
184     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
185                                                        TargetCPU);
186     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
187                                                   getVerboseAsm(),
188                                                   hasMCUseLoc(),
189                                                   hasMCUseCFI(),
190                                                   hasMCUseDwarfDirectory(),
191                                                   InstPrinter,
192                                                   MCE, MAB,
193                                                   ShowMCInst);
194     AsmStreamer.reset(S);
195     break;
196   }
197   case CGFT_ObjectFile: {
198     // Create the code emitter for the target if it exists.  If not, .o file
199     // emission fails.
200     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, STI,
201                                                          *Context);
202     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
203                                                        TargetCPU);
204     if (MCE == 0 || MAB == 0)
205       return true;
206
207     AsmStreamer.reset(getTarget().createMCObjectStreamer(
208         getTargetTriple(), *Context, *MAB, Out, MCE, STI, hasMCRelaxAll(),
209         hasMCNoExecStack()));
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(createNullStreamer(*Context));
216     break;
217   }
218
219   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
220   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
221   if (Printer == 0)
222     return true;
223
224   // If successful, createAsmPrinter took ownership of AsmStreamer.
225   AsmStreamer.take();
226
227   PM.add(Printer);
228
229   return false;
230 }
231
232 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
233 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
234 /// actually outputting the machine code and resolving things like the address
235 /// of functions.  This method should return true if machine code emission is
236 /// not supported.
237 ///
238 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
239                                                    JITCodeEmitter &JCE,
240                                                    bool DisableVerify) {
241   // Add common CodeGen passes.
242   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
243   if (!Context)
244     return true;
245
246   addCodeEmitter(PM, JCE);
247
248   return false; // success!
249 }
250
251 /// addPassesToEmitMC - Add passes to the specified pass manager to get
252 /// machine code emitted with the MCJIT. This method returns true if machine
253 /// code is not supported. It fills the MCContext Ctx pointer which can be
254 /// used to build custom MCStreamer.
255 ///
256 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
257                                           MCContext *&Ctx,
258                                           raw_ostream &Out,
259                                           bool DisableVerify) {
260   // Add common CodeGen passes.
261   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
262   if (!Ctx)
263     return true;
264
265   if (hasMCSaveTempLabels())
266     Ctx->setAllowTemporaryLabels(false);
267
268   // Create the code emitter for the target if it exists.  If not, .o file
269   // emission fails.
270   const MCRegisterInfo &MRI = *getRegisterInfo();
271   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
272   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
273                                                        STI, *Ctx);
274   MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
275                                                      TargetCPU);
276   if (MCE == 0 || MAB == 0)
277     return true;
278
279   OwningPtr<MCStreamer> AsmStreamer;
280   AsmStreamer.reset(getTarget().createMCObjectStreamer(
281       getTargetTriple(), *Ctx, *MAB, Out, MCE, STI, hasMCRelaxAll(),
282       hasMCNoExecStack()));
283
284   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
285   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
286   if (Printer == 0)
287     return true;
288
289   // If successful, createAsmPrinter took ownership of AsmStreamer.
290   AsmStreamer.take();
291
292   PM.add(Printer);
293
294   return false; // success!
295 }