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