fix an ugly wart in the MCInstPrinter api where the
[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/PassManager.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FormattedStream.h"
33 using namespace llvm;
34
35 namespace llvm {
36   bool EnableFastISel;
37 }
38
39 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
40     cl::desc("Disable Post Regalloc"));
41 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
42     cl::desc("Disable branch folding"));
43 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
44     cl::desc("Disable tail duplication"));
45 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
46     cl::desc("Disable pre-register allocation tail duplication"));
47 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
48     cl::desc("Disable code placement"));
49 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
50     cl::desc("Disable Stack Slot Coloring"));
51 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
52     cl::desc("Disable Machine LICM"));
53 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
54     cl::desc("Disable Machine Sinking"));
55 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
56     cl::desc("Disable Loop Strength Reduction Pass"));
57 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
58     cl::desc("Disable Codegen Prepare"));
59 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
60     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
61 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
62     cl::desc("Print LLVM IR input to isel pass"));
63 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
64     cl::desc("Dump garbage collector data"));
65 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
66     cl::desc("Verify generated machine code"),
67     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
68
69 static cl::opt<cl::boolOrDefault>
70 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
71            cl::init(cl::BOU_UNSET));
72
73 static bool getVerboseAsm() {
74   switch (AsmVerbose) {
75   default:
76   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
77   case cl::BOU_TRUE:  return true;
78   case cl::BOU_FALSE: return false;
79   }      
80 }
81
82 // Enable or disable FastISel. Both options are needed, because
83 // FastISel is enabled by default with -fast, and we wish to be
84 // able to enable or disable fast-isel independently from -O0.
85 static cl::opt<cl::boolOrDefault>
86 EnableFastISelOption("fast-isel", cl::Hidden,
87   cl::desc("Enable the \"fast\" instruction selector"));
88
89 // Enable or disable an experimental optimization to split GEPs
90 // and run a special GVN pass which does not examine loads, in
91 // an effort to factor out redundancy implicit in complex GEPs.
92 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
93     cl::desc("Split GEPs and run no-load GVN"));
94
95 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
96                                      const std::string &Triple)
97   : TargetMachine(T), TargetTriple(Triple) {
98   AsmInfo = T.createAsmInfo(TargetTriple);
99 }
100
101 // Set the default code model for the JIT for a generic target.
102 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
103 void LLVMTargetMachine::setCodeModelForJIT() {
104   setCodeModel(CodeModel::Small);
105 }
106
107 // Set the default code model for static compilation for a generic target.
108 void LLVMTargetMachine::setCodeModelForStatic() {
109   setCodeModel(CodeModel::Small);
110 }
111
112 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
113                                             formatted_raw_ostream &Out,
114                                             CodeGenFileType FileType,
115                                             CodeGenOpt::Level OptLevel,
116                                             bool DisableVerify) {
117   // Add common CodeGen passes.
118   MCContext *Context = 0;
119   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
120     return true;
121   assert(Context != 0 && "Failed to get MCContext");
122
123   const MCAsmInfo &MAI = *getMCAsmInfo();
124   OwningPtr<MCStreamer> AsmStreamer;
125
126   formatted_raw_ostream *LegacyOutput;
127   switch (FileType) {
128   default: return true;
129   case CGFT_AssemblyFile: {
130     MCInstPrinter *InstPrinter =
131       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
132     AsmStreamer.reset(createAsmStreamer(*Context, Out,
133                                         getTargetData()->isLittleEndian(),
134                                         getVerboseAsm(), InstPrinter,
135                                         /*codeemitter*/0));
136     // Set the AsmPrinter's "O" to the output file.
137     LegacyOutput = &Out;
138     break;
139   }
140   case CGFT_ObjectFile: {
141     // Create the code emitter for the target if it exists.  If not, .o file
142     // emission fails.
143     MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
144     TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
145     if (MCE == 0 || TAB == 0)
146       return true;
147     
148     AsmStreamer.reset(createMachOStreamer(*Context, *TAB, Out, MCE));
149     
150     // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
151     // force it to come out stderr.
152     // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
153     // asmprinter.
154     LegacyOutput = new formatted_raw_ostream(errs());
155     break;
156   }
157   case CGFT_Null:
158     // The Null output is intended for use for performance analysis and testing,
159     // not real users.
160     AsmStreamer.reset(createNullStreamer(*Context));
161     // Any output to the asmprinter's "O" stream is bad and needs to be fixed,
162     // force it to come out stderr.
163     // FIXME: this is horrible and leaks, eventually remove the raw_ostream from
164     // asmprinter.
165     LegacyOutput = new formatted_raw_ostream(errs());
166     break;
167   }
168   
169   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
170   FunctionPass *Printer =
171     getTarget().createAsmPrinter(*LegacyOutput, *this, *AsmStreamer);
172   if (Printer == 0)
173     return true;
174   
175   // If successful, createAsmPrinter took ownership of AsmStreamer.
176   AsmStreamer.take();
177   
178   PM.add(Printer);
179   
180   // Make sure the code model is set.
181   setCodeModelForStatic();
182   PM.add(createGCInfoDeleter());
183   return false;
184 }
185
186 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
187 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
188 /// actually outputting the machine code and resolving things like the address
189 /// of functions.  This method should returns true if machine code emission is
190 /// not supported.
191 ///
192 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
193                                                    JITCodeEmitter &JCE,
194                                                    CodeGenOpt::Level OptLevel,
195                                                    bool DisableVerify) {
196   // Make sure the code model is set.
197   setCodeModelForJIT();
198   
199   // Add common CodeGen passes.
200   MCContext *Ctx = 0;
201   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
202     return true;
203
204   addCodeEmitter(PM, OptLevel, JCE);
205   PM.add(createGCInfoDeleter());
206
207   return false; // success!
208 }
209
210 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
211   if (PrintMachineCode)
212     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
213 }
214
215 static void printAndVerify(PassManagerBase &PM,
216                            const char *Banner,
217                            bool allowDoubleDefs = false) {
218   if (PrintMachineCode)
219     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
220
221   if (VerifyMachineCode)
222     PM.add(createMachineVerifierPass(allowDoubleDefs));
223 }
224
225 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
226 /// emitting to assembly files or machine code output.
227 ///
228 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
229                                                CodeGenOpt::Level OptLevel,
230                                                bool DisableVerify,
231                                                MCContext *&OutContext) {
232   // Standard LLVM-Level Passes.
233
234   // Before running any passes, run the verifier to determine if the input
235   // coming from the front-end and/or optimizer is valid.
236   if (!DisableVerify)
237     PM.add(createVerifierPass());
238
239   // Optionally, tun split-GEPs and no-load GVN.
240   if (EnableSplitGEPGVN) {
241     PM.add(createGEPSplitterPass());
242     PM.add(createGVNPass(/*NoLoads=*/true));
243   }
244
245   // Run loop strength reduction before anything else.
246   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
247     PM.add(createLoopStrengthReducePass(getTargetLowering()));
248     if (PrintLSR)
249       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
250   }
251
252   // Turn exception handling constructs into something the code generators can
253   // handle.
254   switch (getMCAsmInfo()->getExceptionHandlingType()) {
255   case ExceptionHandling::SjLj:
256     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
257     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
258     // catch info can get misplaced when a selector ends up more than one block
259     // removed from the parent invoke(s). This could happen when a landing
260     // pad is shared by multiple invokes and is also a target of a normal
261     // edge from elsewhere.
262     PM.add(createSjLjEHPass(getTargetLowering()));
263     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
264     break;
265   case ExceptionHandling::Dwarf:
266     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
267     break;
268   case ExceptionHandling::None:
269     PM.add(createLowerInvokePass(getTargetLowering()));
270     break;
271   }
272
273   PM.add(createGCLoweringPass());
274
275   // Make sure that no unreachable blocks are instruction selected.
276   PM.add(createUnreachableBlockEliminationPass());
277
278   if (OptLevel != CodeGenOpt::None && !DisableCGP)
279     PM.add(createCodeGenPreparePass(getTargetLowering()));
280
281   PM.add(createStackProtectorPass(getTargetLowering()));
282
283   if (PrintISelInput)
284     PM.add(createPrintFunctionPass("\n\n"
285                                    "*** Final LLVM Code input to ISel ***\n",
286                                    &dbgs()));
287
288   // All passes which modify the LLVM IR are now complete; run the verifier
289   // to ensure that the IR is valid.
290   if (!DisableVerify)
291     PM.add(createVerifierPass());
292
293   // Standard Lower-Level Passes.
294   
295   // Install a MachineModuleInfo class, which is an immutable pass that holds
296   // all the per-module stuff we're generating, including MCContext.
297   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo());
298   PM.add(MMI);
299   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
300   
301
302   // Set up a MachineFunction for the rest of CodeGen to work on.
303   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
304
305   // Enable FastISel with -fast, but allow that to be overridden.
306   if (EnableFastISelOption == cl::BOU_TRUE ||
307       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
308     EnableFastISel = true;
309
310   // Ask the target for an isel.
311   if (addInstSelector(PM, OptLevel))
312     return true;
313
314   // Print the instruction selected machine code...
315   printAndVerify(PM, "After Instruction Selection",
316                  /* allowDoubleDefs= */ true);
317
318   // Optimize PHIs before DCE: removing dead PHI cycles may make more
319   // instructions dead.
320   if (OptLevel != CodeGenOpt::None)
321     PM.add(createOptimizePHIsPass());
322
323   // Delete dead machine instructions regardless of optimization level.
324   PM.add(createDeadMachineInstructionElimPass());
325   printAndVerify(PM, "After codegen DCE pass",
326                  /* allowDoubleDefs= */ true);
327
328   if (OptLevel != CodeGenOpt::None) {
329     PM.add(createOptimizeExtsPass());
330     if (!DisableMachineLICM)
331       PM.add(createMachineLICMPass());
332     PM.add(createMachineCSEPass());
333     if (!DisableMachineSink)
334       PM.add(createMachineSinkingPass());
335     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes",
336                    /* allowDoubleDefs= */ true);
337   }
338
339   // Pre-ra tail duplication.
340   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
341     PM.add(createTailDuplicatePass(true));
342     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
343                    /* allowDoubleDefs= */ true);
344   }
345
346   // Run pre-ra passes.
347   if (addPreRegAlloc(PM, OptLevel))
348     printAndVerify(PM, "After PreRegAlloc passes",
349                    /* allowDoubleDefs= */ true);
350
351   // Perform register allocation.
352   PM.add(createRegisterAllocator());
353   printAndVerify(PM, "After Register Allocation");
354
355   // Perform stack slot coloring.
356   if (OptLevel != CodeGenOpt::None && !DisableSSC) {
357     // FIXME: Re-enable coloring with register when it's capable of adding
358     // kill markers.
359     PM.add(createStackSlotColoringPass(false));
360     printAndVerify(PM, "After StackSlotColoring");
361   }
362
363   // Run post-ra passes.
364   if (addPostRegAlloc(PM, OptLevel))
365     printAndVerify(PM, "After PostRegAlloc passes");
366
367   PM.add(createLowerSubregsPass());
368   printAndVerify(PM, "After LowerSubregs");
369
370   // Insert prolog/epilog code.  Eliminate abstract frame index references...
371   PM.add(createPrologEpilogCodeInserter());
372   printAndVerify(PM, "After PrologEpilogCodeInserter");
373
374   // Run pre-sched2 passes.
375   if (addPreSched2(PM, OptLevel))
376     printAndVerify(PM, "After PreSched2 passes");
377
378   // Second pass scheduler.
379   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
380     PM.add(createPostRAScheduler(OptLevel));
381     printAndVerify(PM, "After PostRAScheduler");
382   }
383
384   // Branch folding must be run after regalloc and prolog/epilog insertion.
385   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
386     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
387     printNoVerify(PM, "After BranchFolding");
388   }
389
390   // Tail duplication.
391   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
392     PM.add(createTailDuplicatePass(false));
393     printNoVerify(PM, "After TailDuplicate");
394   }
395
396   PM.add(createGCMachineCodeAnalysisPass());
397
398   if (PrintGCInfo)
399     PM.add(createGCInfoPrinter(dbgs()));
400
401   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
402     PM.add(createCodePlacementOptPass());
403     printNoVerify(PM, "After CodePlacementOpt");
404   }
405
406   if (addPreEmitPass(PM, OptLevel))
407     printNoVerify(PM, "After PreEmit passes");
408
409   return false;
410 }