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