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/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"
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<cl::boolOrDefault>
55 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
56 cl::desc("Enable optimized register allocation compilation path."));
57 static cl::opt<cl::boolOrDefault>
58 EnableMachineSched("enable-misched", cl::Hidden,
59 cl::desc("Enable the machine instruction scheduling pass."));
60 static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
61 cl::desc("Use strong PHI elimination."));
62 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
64 cl::desc("Disable Machine LICM"));
65 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
66 cl::desc("Disable Machine Sinking"));
67 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
68 cl::desc("Disable Loop Strength Reduction Pass"));
69 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
70 cl::desc("Disable Codegen Prepare"));
71 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
72 cl::desc("Disable Copy Propagation pass"));
73 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
74 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
75 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
76 cl::desc("Print LLVM IR input to isel pass"));
77 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
78 cl::desc("Dump garbage collector data"));
79 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
80 cl::desc("Verify generated machine code"),
81 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
83 // Allow Pass selection to be overriden by command line options.
85 // DefaultID is the default pass to run which may be NoPassID, or may be
86 // overriden by the target.
88 // OptionalID is a pass that may be forcibly enabled by the user when the
89 // default is NoPassID.
90 char &enablePass(char &DefaultID, cl::boolOrDefault Override,
91 char *OptionalIDPtr = &NoPassID) {
96 if (&DefaultID != &NoPassID)
98 if (OptionalIDPtr == &NoPassID)
99 report_fatal_error("Target cannot enable pass");
100 return *OptionalIDPtr;
104 llvm_unreachable("Invalid command line option state");
107 //===---------------------------------------------------------------------===//
109 //===---------------------------------------------------------------------===//
111 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
112 "Target Pass Configuration", false, false)
113 char TargetPassConfig::ID = 0;
115 static char NoPassIDAnchor = 0;
116 char &llvm::NoPassID = NoPassIDAnchor;
119 class PassConfigImpl {
121 // List of passes explicitly substituted by this target. Normally this is
122 // empty, but it is a convenient way to suppress or replace specific passes
123 // that are part of a standard pass pipeline without overridding the entire
124 // pipeline. This mechanism allows target options to inherit a standard pass's
125 // user interface. For example, a target may disable a standard pass by
126 // default by substituting NoPass, and the user may still enable that standard
127 // pass with an explicit command line option.
128 DenseMap<AnalysisID,AnalysisID> TargetPasses;
132 // Out of line virtual method.
133 TargetPassConfig::~TargetPassConfig() {
137 // Out of line constructor provides default values for pass options and
138 // registers all common codegen passes.
139 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
140 : ImmutablePass(ID), TM(tm), PM(pm), Impl(0), Initialized(false),
141 DisableVerify(false),
142 EnableTailMerge(true) {
144 Impl = new PassConfigImpl();
146 // Register all target independent codegen passes to activate their PassIDs,
147 // including this pass itself.
148 initializeCodeGen(*PassRegistry::getPassRegistry());
151 /// createPassConfig - Create a pass configuration object to be used by
152 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
154 /// Targets may override this to extend TargetPassConfig.
155 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
156 return new TargetPassConfig(this, PM);
159 TargetPassConfig::TargetPassConfig()
160 : ImmutablePass(ID), PM(*(PassManagerBase*)0) {
161 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
164 // Helper to verify the analysis is really immutable.
165 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
166 assert(!Initialized && "PassConfig is immutable");
170 void TargetPassConfig::substitutePass(char &StandardID, char &TargetID) {
171 Impl->TargetPasses[&StandardID] = &TargetID;
174 AnalysisID TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
175 DenseMap<AnalysisID, AnalysisID>::const_iterator
176 I = Impl->TargetPasses.find(ID);
177 if (I == Impl->TargetPasses.end())
182 /// Add a CodeGen pass at this point in the pipeline after checking for target
183 /// and command line overrides.
184 AnalysisID TargetPassConfig::addPass(char &ID) {
185 assert(!Initialized && "PassConfig is immutable");
187 AnalysisID FinalID = getPassSubstitution(&ID);
188 // FIXME: check user overrides
189 if (FinalID == &NoPassID)
192 Pass *P = Pass::createPass(FinalID);
194 llvm_unreachable("Pass ID not registered");
199 void TargetPassConfig::printNoVerify(const char *Banner) const {
200 if (TM->shouldPrintMachineCode())
201 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
204 void TargetPassConfig::printAndVerify(const char *Banner) const {
205 if (TM->shouldPrintMachineCode())
206 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
208 if (VerifyMachineCode)
209 PM.add(createMachineVerifierPass(Banner));
212 /// Add common target configurable passes that perform LLVM IR to IR transforms
213 /// following machine independent optimization.
214 void TargetPassConfig::addIRPasses() {
215 // Basic AliasAnalysis support.
216 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
217 // BasicAliasAnalysis wins if they disagree. This is intended to help
218 // support "obvious" type-punning idioms.
219 PM.add(createTypeBasedAliasAnalysisPass());
220 PM.add(createBasicAliasAnalysisPass());
222 // Before running any passes, run the verifier to determine if the input
223 // coming from the front-end and/or optimizer is valid.
225 PM.add(createVerifierPass());
227 // Run loop strength reduction before anything else.
228 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
229 PM.add(createLoopStrengthReducePass(getTargetLowering()));
231 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
234 PM.add(createGCLoweringPass());
236 // Make sure that no unreachable blocks are instruction selected.
237 PM.add(createUnreachableBlockEliminationPass());
240 /// Add common passes that perform LLVM IR to IR transforms in preparation for
241 /// instruction selection.
242 void TargetPassConfig::addISelPrepare() {
243 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
244 PM.add(createCodeGenPreparePass(getTargetLowering()));
246 PM.add(createStackProtectorPass(getTargetLowering()));
251 PM.add(createPrintFunctionPass("\n\n"
252 "*** Final LLVM Code input to ISel ***\n",
255 // All passes which modify the LLVM IR are now complete; run the verifier
256 // to ensure that the IR is valid.
258 PM.add(createVerifierPass());
261 /// Add the complete set of target-independent postISel code generator passes.
263 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
264 /// with nontrivial configuration or multiple passes are broken out below in
265 /// add%Stage routines.
267 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
268 /// addPre/Post methods with empty header implementations allow injecting
269 /// target-specific fixups just before or after major stages. Additionally,
270 /// targets have the flexibility to change pass order within a stage by
271 /// overriding default implementation of add%Stage routines below. Each
272 /// technique has maintainability tradeoffs because alternate pass orders are
273 /// not well supported. addPre/Post works better if the target pass is easily
274 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
275 /// the target should override the stage instead.
277 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
278 /// before/after any target-independent pass. But it's currently overkill.
279 void TargetPassConfig::addMachinePasses() {
280 // Print the instruction selected machine code...
281 printAndVerify("After Instruction Selection");
283 // Expand pseudo-instructions emitted by ISel.
284 addPass(ExpandISelPseudosID);
286 // Add passes that optimize machine instructions in SSA form.
287 if (getOptLevel() != CodeGenOpt::None) {
288 addMachineSSAOptimization();
291 // If the target requests it, assign local variables to stack slots relative
292 // to one another and simplify frame index references where possible.
293 addPass(LocalStackSlotAllocationID);
296 // Run pre-ra passes.
297 if (addPreRegAlloc())
298 printAndVerify("After PreRegAlloc passes");
300 // Run register allocation and passes that are tightly coupled with it,
301 // including phi elimination and scheduling.
302 if (getOptimizeRegAlloc())
303 addOptimizedRegAlloc(createRegAllocPass(true));
305 addFastRegAlloc(createRegAllocPass(false));
307 // Run post-ra passes.
308 if (addPostRegAlloc())
309 printAndVerify("After PostRegAlloc passes");
311 // Insert prolog/epilog code. Eliminate abstract frame index references...
312 addPass(PrologEpilogCodeInserterID);
313 printAndVerify("After PrologEpilogCodeInserter");
315 /// Add passes that optimize machine instructions after register allocation.
316 if (getOptLevel() != CodeGenOpt::None)
317 addMachineLateOptimization();
319 // Expand pseudo instructions before second scheduling pass.
320 addPass(ExpandPostRAPseudosID);
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 addPass(PostRASchedulerID);
330 printNoVerify("After PostRAScheduler");
334 addPass(GCMachineCodeAnalysisID);
336 PM.add(createGCInfoPrinter(dbgs()));
338 // Basic block placement.
339 if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace)
342 if (addPreEmitPass())
343 printNoVerify("After PreEmit passes");
346 /// Add passes that optimize machine instructions in SSA form.
347 void TargetPassConfig::addMachineSSAOptimization() {
348 // Pre-ra tail duplication.
349 if (!DisableEarlyTailDup) {
350 addPass(TailDuplicateID);
351 printAndVerify("After Pre-RegAlloc TailDuplicate");
354 // Optimize PHIs before DCE: removing dead PHI cycles may make more
355 // instructions dead.
356 addPass(OptimizePHIsID);
358 // If the target requests it, assign local variables to stack slots relative
359 // to one another and simplify frame index references where possible.
360 addPass(LocalStackSlotAllocationID);
362 // With optimization, dead code should already be eliminated. However
363 // there is one known exception: lowered code for arguments that are only
364 // used by tail calls, where the tail calls reuse the incoming stack
365 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
366 if (!DisableMachineDCE)
367 addPass(DeadMachineInstructionElimID);
368 printAndVerify("After codegen DCE pass");
370 if (!DisableMachineLICM)
371 addPass(MachineLICMID);
372 if (!DisableMachineCSE)
373 addPass(MachineCSEID);
374 if (!DisableMachineSink)
375 addPass(MachineSinkingID);
376 printAndVerify("After Machine LICM, CSE and Sinking passes");
378 addPass(PeepholeOptimizerID);
379 printAndVerify("After codegen peephole optimization pass");
382 //===---------------------------------------------------------------------===//
383 /// Register Allocation Pass Configuration
384 //===---------------------------------------------------------------------===//
386 bool TargetPassConfig::getOptimizeRegAlloc() const {
387 switch (OptimizeRegAlloc) {
388 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
389 case cl::BOU_TRUE: return true;
390 case cl::BOU_FALSE: return false;
392 llvm_unreachable("Invalid optimize-regalloc state");
395 /// RegisterRegAlloc's global Registry tracks allocator registration.
396 MachinePassRegistry RegisterRegAlloc::Registry;
398 /// A dummy default pass factory indicates whether the register allocator is
399 /// overridden on the command line.
400 static FunctionPass *useDefaultRegisterAllocator() { return 0; }
401 static RegisterRegAlloc
402 defaultRegAlloc("default",
403 "pick register allocator based on -O option",
404 useDefaultRegisterAllocator);
406 /// -regalloc=... command line option.
407 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
408 RegisterPassParser<RegisterRegAlloc> >
410 cl::init(&useDefaultRegisterAllocator),
411 cl::desc("Register allocator to use"));
414 /// Instantiate the default register allocator pass for this target for either
415 /// the optimized or unoptimized allocation path. This will be added to the pass
416 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
417 /// in the optimized case.
419 /// A target that uses the standard regalloc pass order for fast or optimized
420 /// allocation may still override this for per-target regalloc
421 /// selection. But -regalloc=... always takes precedence.
422 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
424 return createGreedyRegisterAllocator();
426 return createFastRegisterAllocator();
429 /// Find and instantiate the register allocation pass requested by this target
430 /// at the current optimization level. Different register allocators are
431 /// defined as separate passes because they may require different analysis.
433 /// This helper ensures that the regalloc= option is always available,
434 /// even for targets that override the default allocator.
436 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
437 /// this can be folded into addPass.
438 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
439 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
441 // Initialize the global default.
444 RegisterRegAlloc::setDefault(RegAlloc);
446 if (Ctor != useDefaultRegisterAllocator)
449 // With no -regalloc= override, ask the target for a regalloc pass.
450 return createTargetRegisterAllocator(Optimized);
453 /// Add the minimum set of target-independent passes that are required for
454 /// register allocation. No coalescing or scheduling.
455 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
456 addPass(PHIEliminationID);
457 addPass(TwoAddressInstructionPassID);
459 PM.add(RegAllocPass);
460 printAndVerify("After Register Allocation");
463 /// Add standard target-independent passes that are tightly coupled with
464 /// optimized register allocation, including coalescing, machine instruction
465 /// scheduling, and register allocation itself.
466 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
467 // LiveVariables currently requires pure SSA form.
469 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
470 // LiveVariables can be removed completely, and LiveIntervals can be directly
471 // computed. (We still either need to regenerate kill flags after regalloc, or
472 // preferably fix the scavenger to not depend on them).
473 addPass(LiveVariablesID);
475 // Add passes that move from transformed SSA into conventional SSA. This is a
476 // "copy coalescing" problem.
478 if (!EnableStrongPHIElim) {
479 // Edge splitting is smarter with machine loop info.
480 addPass(MachineLoopInfoID);
481 addPass(PHIEliminationID);
483 addPass(TwoAddressInstructionPassID);
485 // FIXME: Either remove this pass completely, or fix it so that it works on
486 // SSA form. We could modify LiveIntervals to be independent of this pass, But
487 // it would be even better to simply eliminate *all* IMPLICIT_DEFs before
489 addPass(ProcessImplicitDefsID);
491 if (EnableStrongPHIElim)
492 addPass(StrongPHIEliminationID);
494 addPass(RegisterCoalescerID);
496 // PreRA instruction scheduling.
497 addPass(enablePass(getSchedPass(), EnableMachineSched, &MachineSchedulerID));
499 // Add the selected register allocation pass.
500 PM.add(RegAllocPass);
501 printAndVerify("After Register Allocation");
503 // FinalizeRegAlloc is convenient until MachineInstrBundles is more mature,
504 // but eventually, all users of it should probably be moved to addPostRA and
505 // it can go away. Currently, it's the intended place for targets to run
506 // FinalizeMachineBundles, because passes other than MachineScheduling an
507 // RegAlloc itself may not be aware of bundles.
508 if (addFinalizeRegAlloc())
509 printAndVerify("After RegAlloc finalization");
511 // Perform stack slot coloring and post-ra machine LICM.
513 // FIXME: Re-enable coloring with register when it's capable of adding
516 addPass(StackSlotColoringID);
518 // Run post-ra machine LICM to hoist reloads / remats.
520 // FIXME: can this move into MachineLateOptimization?
521 if (!DisablePostRAMachineLICM)
522 addPass(MachineLICMID);
524 printAndVerify("After StackSlotColoring and postra Machine LICM");
527 //===---------------------------------------------------------------------===//
528 /// Post RegAlloc Pass Configuration
529 //===---------------------------------------------------------------------===//
531 /// Add passes that optimize machine instructions after register allocation.
532 void TargetPassConfig::addMachineLateOptimization() {
533 // Branch folding must be run after regalloc and prolog/epilog insertion.
534 if (!DisableBranchFold) {
535 addPass(BranchFolderPassID);
536 printNoVerify("After BranchFolding");
540 if (!DisableTailDuplicate) {
541 addPass(TailDuplicateID);
542 printNoVerify("After TailDuplicate");
546 if (!DisableCopyProp) {
547 addPass(MachineCopyPropagationID);
548 printNoVerify("After copy propagation pass");
552 /// Add standard basic block placement passes.
553 void TargetPassConfig::addBlockPlacement() {
554 if (EnableBlockPlacement) {
555 // MachineBlockPlacement is an experimental pass which is disabled by
556 // default currently. Eventually it should subsume CodePlacementOpt, so
557 // when enabled, the other is disabled.
558 addPass(MachineBlockPlacementID);
559 printNoVerify("After MachineBlockPlacement");
561 addPass(CodePlacementOptID);
562 printNoVerify("After CodePlacementOpt");
565 // Run a separate pass to collect block placement statistics.
566 if (EnableBlockPlacementStats) {
567 addPass(MachineBlockPlacementStatsID);
568 printNoVerify("After MachineBlockPlacementStats");