1 //===-- Passes.cpp - Target independent code generation passes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
13 //===---------------------------------------------------------------------===//
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/MachineFunctionAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/Assembly/PrintModulePass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
37 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
38 cl::desc("Disable Post Regalloc"));
39 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
40 cl::desc("Disable branch folding"));
41 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
42 cl::desc("Disable tail duplication"));
43 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
44 cl::desc("Disable pre-register allocation tail duplication"));
45 static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
46 cl::Hidden, cl::desc("Enable probability-driven block placement"));
47 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
48 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
49 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
50 cl::desc("Disable code placement"));
51 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
52 cl::desc("Disable Stack Slot Coloring"));
53 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
54 cl::desc("Disable Machine Dead Code Elimination"));
55 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
56 cl::desc("Disable Machine LICM"));
57 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
58 cl::desc("Disable Machine Common Subexpression Elimination"));
59 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
61 cl::desc("Disable Machine LICM"));
62 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
63 cl::desc("Disable Machine Sinking"));
64 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
65 cl::desc("Disable Loop Strength Reduction Pass"));
66 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
67 cl::desc("Disable Codegen Prepare"));
68 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
69 cl::desc("Disable Copy Propagation pass"));
70 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
71 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
72 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
73 cl::desc("Print LLVM IR input to isel pass"));
74 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
75 cl::desc("Dump garbage collector data"));
76 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
77 cl::desc("Verify generated machine code"),
78 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
80 // Enable or disable FastISel. Both options are needed, because
81 // FastISel is enabled by default with -fast, and we wish to be
82 // able to enable or disable fast-isel independently from -O0.
83 static cl::opt<cl::boolOrDefault>
84 EnableFastISelOption("fast-isel", cl::Hidden,
85 cl::desc("Enable the \"fast\" instruction selector"));
87 //===---------------------------------------------------------------------===//
89 //===---------------------------------------------------------------------===//
91 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
92 "Target Pass Configuration", false, false)
93 char TargetPassConfig::ID = 0;
95 // Out of line virtual method.
96 TargetPassConfig::~TargetPassConfig() {}
98 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm,
99 bool DisableVerifyFlag)
100 : ImmutablePass(ID), TM(tm), PM(pm), DisableVerify(DisableVerifyFlag) {
101 // Register all target independent codegen passes to activate their PassIDs,
102 // including this pass itself.
103 initializeCodeGen(*PassRegistry::getPassRegistry());
106 /// createPassConfig - Create a pass configuration object to be used by
107 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
109 /// Targets may override this to extend TargetPassConfig.
110 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM,
111 bool DisableVerify) {
112 return new TargetPassConfig(this, PM, DisableVerify);
115 TargetPassConfig::TargetPassConfig()
116 : ImmutablePass(ID), PM(*(PassManagerBase*)0) {
117 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
121 void TargetPassConfig::printNoVerify(const char *Banner) const {
122 if (TM->shouldPrintMachineCode())
123 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
126 void TargetPassConfig::printAndVerify(const char *Banner) const {
127 if (TM->shouldPrintMachineCode())
128 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
130 if (VerifyMachineCode)
131 PM.add(createMachineVerifierPass(Banner));
134 /// addCodeGenPasses - Add standard LLVM codegen passes used for both
135 /// emitting to assembly files or machine code output.
137 bool TargetPassConfig::addCodeGenPasses(MCContext *&OutContext) {
138 // Standard LLVM-Level Passes.
140 // Basic AliasAnalysis support.
141 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
142 // BasicAliasAnalysis wins if they disagree. This is intended to help
143 // support "obvious" type-punning idioms.
144 PM.add(createTypeBasedAliasAnalysisPass());
145 PM.add(createBasicAliasAnalysisPass());
147 // Before running any passes, run the verifier to determine if the input
148 // coming from the front-end and/or optimizer is valid.
150 PM.add(createVerifierPass());
152 // Run loop strength reduction before anything else.
153 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
154 PM.add(createLoopStrengthReducePass(getTargetLowering()));
156 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
159 PM.add(createGCLoweringPass());
161 // Make sure that no unreachable blocks are instruction selected.
162 PM.add(createUnreachableBlockEliminationPass());
164 // Turn exception handling constructs into something the code generators can
166 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
167 case ExceptionHandling::SjLj:
168 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
169 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
170 // catch info can get misplaced when a selector ends up more than one block
171 // removed from the parent invoke(s). This could happen when a landing
172 // pad is shared by multiple invokes and is also a target of a normal
173 // edge from elsewhere.
174 PM.add(createSjLjEHPass(getTargetLowering()));
176 case ExceptionHandling::DwarfCFI:
177 case ExceptionHandling::ARM:
178 case ExceptionHandling::Win64:
179 PM.add(createDwarfEHPass(TM));
181 case ExceptionHandling::None:
182 PM.add(createLowerInvokePass(getTargetLowering()));
184 // The lower invoke pass may create unreachable code. Remove it.
185 PM.add(createUnreachableBlockEliminationPass());
189 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
190 PM.add(createCodeGenPreparePass(getTargetLowering()));
192 PM.add(createStackProtectorPass(getTargetLowering()));
197 PM.add(createPrintFunctionPass("\n\n"
198 "*** Final LLVM Code input to ISel ***\n",
201 // All passes which modify the LLVM IR are now complete; run the verifier
202 // to ensure that the IR is valid.
204 PM.add(createVerifierPass());
206 // Standard Lower-Level Passes.
208 // Install a MachineModuleInfo class, which is an immutable pass that holds
209 // all the per-module stuff we're generating, including MCContext.
210 MachineModuleInfo *MMI =
211 new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
212 &getTargetLowering()->getObjFileLowering());
214 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
216 // Set up a MachineFunction for the rest of CodeGen to work on.
217 PM.add(new MachineFunctionAnalysis(*TM));
219 // Enable FastISel with -fast, but allow that to be overridden.
220 if (EnableFastISelOption == cl::BOU_TRUE ||
221 (getOptLevel() == CodeGenOpt::None &&
222 EnableFastISelOption != cl::BOU_FALSE))
223 TM->setFastISel(true);
225 // Ask the target for an isel.
226 if (addInstSelector())
229 // Print the instruction selected machine code...
230 printAndVerify("After Instruction Selection");
232 // Expand pseudo-instructions emitted by ISel.
233 PM.add(createExpandISelPseudosPass());
235 // Pre-ra tail duplication.
236 if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
237 PM.add(createTailDuplicatePass(true));
238 printAndVerify("After Pre-RegAlloc TailDuplicate");
241 // Optimize PHIs before DCE: removing dead PHI cycles may make more
242 // instructions dead.
243 if (getOptLevel() != CodeGenOpt::None)
244 PM.add(createOptimizePHIsPass());
246 // If the target requests it, assign local variables to stack slots relative
247 // to one another and simplify frame index references where possible.
248 PM.add(createLocalStackSlotAllocationPass());
250 if (getOptLevel() != CodeGenOpt::None) {
251 // With optimization, dead code should already be eliminated. However
252 // there is one known exception: lowered code for arguments that are only
253 // used by tail calls, where the tail calls reuse the incoming stack
254 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
255 if (!DisableMachineDCE)
256 PM.add(createDeadMachineInstructionElimPass());
257 printAndVerify("After codegen DCE pass");
259 if (!DisableMachineLICM)
260 PM.add(createMachineLICMPass());
261 if (!DisableMachineCSE)
262 PM.add(createMachineCSEPass());
263 if (!DisableMachineSink)
264 PM.add(createMachineSinkingPass());
265 printAndVerify("After Machine LICM, CSE and Sinking passes");
267 PM.add(createPeepholeOptimizerPass());
268 printAndVerify("After codegen peephole optimization pass");
271 // Run pre-ra passes.
272 if (addPreRegAlloc())
273 printAndVerify("After PreRegAlloc passes");
275 // Perform register allocation.
276 PM.add(createRegisterAllocator(getOptLevel()));
277 printAndVerify("After Register Allocation");
279 // Perform stack slot coloring and post-ra machine LICM.
280 if (getOptLevel() != CodeGenOpt::None) {
281 // FIXME: Re-enable coloring with register when it's capable of adding
284 PM.add(createStackSlotColoringPass(false));
286 // Run post-ra machine LICM to hoist reloads / remats.
287 if (!DisablePostRAMachineLICM)
288 PM.add(createMachineLICMPass(false));
290 printAndVerify("After StackSlotColoring and postra Machine LICM");
293 // Run post-ra passes.
294 if (addPostRegAlloc())
295 printAndVerify("After PostRegAlloc passes");
297 // Insert prolog/epilog code. Eliminate abstract frame index references...
298 PM.add(createPrologEpilogCodeInserter());
299 printAndVerify("After PrologEpilogCodeInserter");
301 // Branch folding must be run after regalloc and prolog/epilog insertion.
302 if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
303 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
304 printNoVerify("After BranchFolding");
308 if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
309 PM.add(createTailDuplicatePass(false));
310 printNoVerify("After TailDuplicate");
314 if (getOptLevel() != CodeGenOpt::None && !DisableCopyProp) {
315 PM.add(createMachineCopyPropagationPass());
316 printNoVerify("After copy propagation pass");
319 // Expand pseudo instructions before second scheduling pass.
320 PM.add(createExpandPostRAPseudosPass());
321 printNoVerify("After ExpandPostRAPseudos");
323 // Run pre-sched2 passes.
325 printNoVerify("After PreSched2 passes");
327 // Second pass scheduler.
328 if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
329 PM.add(createPostRAScheduler(getOptLevel()));
330 printNoVerify("After PostRAScheduler");
333 PM.add(createGCMachineCodeAnalysisPass());
336 PM.add(createGCInfoPrinter(dbgs()));
338 if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
339 if (EnableBlockPlacement) {
340 // MachineBlockPlacement is an experimental pass which is disabled by
341 // default currently. Eventually it should subsume CodePlacementOpt, so
342 // when enabled, the other is disabled.
343 PM.add(createMachineBlockPlacementPass());
344 printNoVerify("After MachineBlockPlacement");
346 PM.add(createCodePlacementOptPass());
347 printNoVerify("After CodePlacementOpt");
350 // Run a separate pass to collect block placement statistics.
351 if (EnableBlockPlacementStats) {
352 PM.add(createMachineBlockPlacementStatsPass());
353 printNoVerify("After MachineBlockPlacementStats");
357 if (addPreEmitPass())
358 printNoVerify("After PreEmit passes");
363 //===---------------------------------------------------------------------===//
365 /// RegisterRegAlloc class - Track the registration of register allocators.
367 //===---------------------------------------------------------------------===//
368 MachinePassRegistry RegisterRegAlloc::Registry;
370 static FunctionPass *createDefaultRegisterAllocator() { return 0; }
371 static RegisterRegAlloc
372 defaultRegAlloc("default",
373 "pick register allocator based on -O option",
374 createDefaultRegisterAllocator);
376 //===---------------------------------------------------------------------===//
378 /// RegAlloc command line options.
380 //===---------------------------------------------------------------------===//
381 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
382 RegisterPassParser<RegisterRegAlloc> >
384 cl::init(&createDefaultRegisterAllocator),
385 cl::desc("Register allocator to use"));
388 //===---------------------------------------------------------------------===//
390 /// createRegisterAllocator - choose the appropriate register allocator.
392 //===---------------------------------------------------------------------===//
393 FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
394 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
398 RegisterRegAlloc::setDefault(RegAlloc);
401 if (Ctor != createDefaultRegisterAllocator)
404 // When the 'default' allocator is requested, pick one based on OptLevel.
406 case CodeGenOpt::None:
407 return createFastRegisterAllocator();
409 return createGreedyRegisterAllocator();