2877cf165b6bd4e257be3c8bd274abf58647f2d5
[oota-llvm.git] / lib / CodeGen / Passes.cpp
1 //===-- Passes.cpp - Target independent code generation passes ------------===//
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 defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
12 //
13 //===---------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/Passes.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/GCStrategy.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Assembly/PrintModulePass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29
30 using namespace llvm;
31
32 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
33     cl::desc("Disable Post Regalloc"));
34 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
35     cl::desc("Disable branch folding"));
36 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
37     cl::desc("Disable tail duplication"));
38 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
39     cl::desc("Disable pre-register allocation tail duplication"));
40 static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
41     cl::Hidden, cl::desc("Enable probability-driven block placement"));
42 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
43     cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
44 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
45     cl::desc("Disable code placement"));
46 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
47     cl::desc("Disable Stack Slot Coloring"));
48 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
49     cl::desc("Disable Machine Dead Code Elimination"));
50 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
51     cl::desc("Disable Machine LICM"));
52 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
53     cl::desc("Disable Machine Common Subexpression Elimination"));
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> DisableCopyProp("disable-copyprop", cl::Hidden,
64     cl::desc("Disable Copy Propagation pass"));
65 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
66     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
67 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
68     cl::desc("Print LLVM IR input to isel pass"));
69 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
70     cl::desc("Dump garbage collector data"));
71 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
72     cl::desc("Verify generated machine code"),
73     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
74
75 //===---------------------------------------------------------------------===//
76 /// TargetPassConfig
77 //===---------------------------------------------------------------------===//
78
79 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
80                 "Target Pass Configuration", false, false)
81 char TargetPassConfig::ID = 0;
82
83 // Out of line virtual method.
84 TargetPassConfig::~TargetPassConfig() {}
85
86 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
87   : ImmutablePass(ID), TM(tm), PM(pm), DisableVerify(false) {
88   // Register all target independent codegen passes to activate their PassIDs,
89   // including this pass itself.
90   initializeCodeGen(*PassRegistry::getPassRegistry());
91 }
92
93 /// createPassConfig - Create a pass configuration object to be used by
94 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
95 ///
96 /// Targets may override this to extend TargetPassConfig.
97 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
98   return new TargetPassConfig(this, PM);
99 }
100
101 TargetPassConfig::TargetPassConfig()
102   : ImmutablePass(ID), PM(*(PassManagerBase*)0) {
103   llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
104 }
105
106 void TargetPassConfig::addPass(char &ID) {
107   // FIXME: check user overrides
108   Pass *P = Pass::createPass(ID);
109   if (!P)
110     llvm_unreachable("Pass ID not registered");
111   PM.add(P);
112 }
113
114 void TargetPassConfig::printNoVerify(const char *Banner) const {
115   if (TM->shouldPrintMachineCode())
116     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
117 }
118
119 void TargetPassConfig::printAndVerify(const char *Banner) const {
120   if (TM->shouldPrintMachineCode())
121     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
122
123   if (VerifyMachineCode)
124     PM.add(createMachineVerifierPass(Banner));
125 }
126
127 /// Add common target configurable passes that perform LLVM IR to IR transforms
128 /// following machine independent optimization.
129 void TargetPassConfig::addIRPasses() {
130   // Basic AliasAnalysis support.
131   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
132   // BasicAliasAnalysis wins if they disagree. This is intended to help
133   // support "obvious" type-punning idioms.
134   PM.add(createTypeBasedAliasAnalysisPass());
135   PM.add(createBasicAliasAnalysisPass());
136
137   // Before running any passes, run the verifier to determine if the input
138   // coming from the front-end and/or optimizer is valid.
139   if (!DisableVerify)
140     PM.add(createVerifierPass());
141
142   // Run loop strength reduction before anything else.
143   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
144     PM.add(createLoopStrengthReducePass(getTargetLowering()));
145     if (PrintLSR)
146       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
147   }
148
149   PM.add(createGCLoweringPass());
150
151   // Make sure that no unreachable blocks are instruction selected.
152   PM.add(createUnreachableBlockEliminationPass());
153 }
154
155 /// Add common passes that perform LLVM IR to IR transforms in preparation for
156 /// instruction selection.
157 void TargetPassConfig::addISelPrepare() {
158   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
159     PM.add(createCodeGenPreparePass(getTargetLowering()));
160
161   PM.add(createStackProtectorPass(getTargetLowering()));
162
163   addPreISel();
164
165   if (PrintISelInput)
166     PM.add(createPrintFunctionPass("\n\n"
167                                    "*** Final LLVM Code input to ISel ***\n",
168                                    &dbgs()));
169
170   // All passes which modify the LLVM IR are now complete; run the verifier
171   // to ensure that the IR is valid.
172   if (!DisableVerify)
173     PM.add(createVerifierPass());
174 }
175
176 void TargetPassConfig::addMachinePasses() {
177   // Print the instruction selected machine code...
178   printAndVerify("After Instruction Selection");
179
180   // Expand pseudo-instructions emitted by ISel.
181   PM.add(createExpandISelPseudosPass());
182
183   // Pre-ra tail duplication.
184   if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
185     PM.add(createTailDuplicatePass());
186     printAndVerify("After Pre-RegAlloc TailDuplicate");
187   }
188
189   // Optimize PHIs before DCE: removing dead PHI cycles may make more
190   // instructions dead.
191   if (getOptLevel() != CodeGenOpt::None)
192     PM.add(createOptimizePHIsPass());
193
194   // If the target requests it, assign local variables to stack slots relative
195   // to one another and simplify frame index references where possible.
196   PM.add(createLocalStackSlotAllocationPass());
197
198   if (getOptLevel() != CodeGenOpt::None) {
199     // With optimization, dead code should already be eliminated. However
200     // there is one known exception: lowered code for arguments that are only
201     // used by tail calls, where the tail calls reuse the incoming stack
202     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
203     if (!DisableMachineDCE)
204       PM.add(createDeadMachineInstructionElimPass());
205     printAndVerify("After codegen DCE pass");
206
207     if (!DisableMachineLICM)
208       PM.add(createMachineLICMPass());
209     if (!DisableMachineCSE)
210       PM.add(createMachineCSEPass());
211     if (!DisableMachineSink)
212       PM.add(createMachineSinkingPass());
213     printAndVerify("After Machine LICM, CSE and Sinking passes");
214
215     PM.add(createPeepholeOptimizerPass());
216     printAndVerify("After codegen peephole optimization pass");
217   }
218
219   // Run pre-ra passes.
220   if (addPreRegAlloc())
221     printAndVerify("After PreRegAlloc passes");
222
223   // Perform register allocation.
224   PM.add(createRegisterAllocator(getOptLevel()));
225   printAndVerify("After Register Allocation");
226
227   // Perform stack slot coloring and post-ra machine LICM.
228   if (getOptLevel() != CodeGenOpt::None) {
229     // FIXME: Re-enable coloring with register when it's capable of adding
230     // kill markers.
231     if (!DisableSSC)
232       PM.add(createStackSlotColoringPass(false));
233
234     // Run post-ra machine LICM to hoist reloads / remats.
235     if (!DisablePostRAMachineLICM)
236       PM.add(createMachineLICMPass(false));
237
238     printAndVerify("After StackSlotColoring and postra Machine LICM");
239   }
240
241   // Run post-ra passes.
242   if (addPostRegAlloc())
243     printAndVerify("After PostRegAlloc passes");
244
245   // Insert prolog/epilog code.  Eliminate abstract frame index references...
246   PM.add(createPrologEpilogCodeInserter());
247   printAndVerify("After PrologEpilogCodeInserter");
248
249   // Branch folding must be run after regalloc and prolog/epilog insertion.
250   if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
251     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
252     printNoVerify("After BranchFolding");
253   }
254
255   // Tail duplication.
256   if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
257     PM.add(createTailDuplicatePass());
258     printNoVerify("After TailDuplicate");
259   }
260
261   // Copy propagation.
262   if (getOptLevel() != CodeGenOpt::None && !DisableCopyProp) {
263     PM.add(createMachineCopyPropagationPass());
264     printNoVerify("After copy propagation pass");
265   }
266
267   // Expand pseudo instructions before second scheduling pass.
268   PM.add(createExpandPostRAPseudosPass());
269   printNoVerify("After ExpandPostRAPseudos");
270
271   // Run pre-sched2 passes.
272   if (addPreSched2())
273     printNoVerify("After PreSched2 passes");
274
275   // Second pass scheduler.
276   if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
277     PM.add(createPostRAScheduler(getOptLevel()));
278     printNoVerify("After PostRAScheduler");
279   }
280
281   PM.add(createGCMachineCodeAnalysisPass());
282
283   if (PrintGCInfo)
284     PM.add(createGCInfoPrinter(dbgs()));
285
286   if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
287     if (EnableBlockPlacement) {
288       // MachineBlockPlacement is an experimental pass which is disabled by
289       // default currently. Eventually it should subsume CodePlacementOpt, so
290       // when enabled, the other is disabled.
291       PM.add(createMachineBlockPlacementPass());
292       printNoVerify("After MachineBlockPlacement");
293     } else {
294       PM.add(createCodePlacementOptPass());
295       printNoVerify("After CodePlacementOpt");
296     }
297
298     // Run a separate pass to collect block placement statistics.
299     if (EnableBlockPlacementStats) {
300       PM.add(createMachineBlockPlacementStatsPass());
301       printNoVerify("After MachineBlockPlacementStats");
302     }
303   }
304
305   if (addPreEmitPass())
306     printNoVerify("After PreEmit passes");
307 }
308
309 //===---------------------------------------------------------------------===//
310 ///
311 /// RegisterRegAlloc class - Track the registration of register allocators.
312 ///
313 //===---------------------------------------------------------------------===//
314 MachinePassRegistry RegisterRegAlloc::Registry;
315
316 static FunctionPass *createDefaultRegisterAllocator() { return 0; }
317 static RegisterRegAlloc
318 defaultRegAlloc("default",
319                 "pick register allocator based on -O option",
320                 createDefaultRegisterAllocator);
321
322 //===---------------------------------------------------------------------===//
323 ///
324 /// RegAlloc command line options.
325 ///
326 //===---------------------------------------------------------------------===//
327 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
328                RegisterPassParser<RegisterRegAlloc> >
329 RegAlloc("regalloc",
330          cl::init(&createDefaultRegisterAllocator),
331          cl::desc("Register allocator to use"));
332
333
334 //===---------------------------------------------------------------------===//
335 ///
336 /// createRegisterAllocator - choose the appropriate register allocator.
337 ///
338 //===---------------------------------------------------------------------===//
339 FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
340   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
341
342   if (!Ctor) {
343     Ctor = RegAlloc;
344     RegisterRegAlloc::setDefault(RegAlloc);
345   }
346
347   if (Ctor != createDefaultRegisterAllocator)
348     return Ctor();
349
350   // When the 'default' allocator is requested, pick one based on OptLevel.
351   switch (OptLevel) {
352   case CodeGenOpt::None:
353     return createFastRegisterAllocator();
354   default:
355     return createGreedyRegisterAllocator();
356   }
357 }