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> DisableBlockPlacement("disable-block-placement",
41 cl::Hidden, cl::desc("Disable the probability-driven block placement, and "
42 "re-enable the old code placement pass"));
43 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
44 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
45 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
46 cl::desc("Disable code placement"));
47 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
48 cl::desc("Disable Stack Slot Coloring"));
49 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
50 cl::desc("Disable Machine Dead Code Elimination"));
51 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
52 cl::desc("Disable Machine LICM"));
53 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
54 cl::desc("Disable Machine Common Subexpression Elimination"));
55 static cl::opt<cl::boolOrDefault>
56 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
57 cl::desc("Enable optimized register allocation compilation path."));
58 static cl::opt<cl::boolOrDefault>
59 EnableMachineSched("enable-misched", cl::Hidden,
60 cl::desc("Enable the machine instruction scheduling pass."));
61 static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
62 cl::desc("Use strong PHI elimination."));
63 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
65 cl::desc("Disable Machine LICM"));
66 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
67 cl::desc("Disable Machine Sinking"));
68 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
69 cl::desc("Disable Loop Strength Reduction Pass"));
70 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
71 cl::desc("Disable Codegen Prepare"));
72 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
73 cl::desc("Disable Copy Propagation pass"));
74 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
75 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
76 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
77 cl::desc("Print LLVM IR input to isel pass"));
78 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
79 cl::desc("Dump garbage collector data"));
80 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
81 cl::desc("Verify generated machine code"),
82 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
84 /// Allow standard passes to be disabled by command line options. This supports
85 /// simple binary flags that either suppress the pass or do nothing.
86 /// i.e. -disable-mypass=false has no effect.
87 /// These should be converted to boolOrDefault in order to use applyOverride.
88 static AnalysisID applyDisable(AnalysisID ID, bool Override) {
94 /// Allow Pass selection to be overriden by command line options. This supports
95 /// flags with ternary conditions. TargetID is passed through by default. The
96 /// pass is suppressed when the option is false. When the option is true, the
97 /// StandardID is selected if the target provides no default.
98 static AnalysisID applyOverride(AnalysisID TargetID, cl::boolOrDefault Override,
99 AnalysisID StandardID) {
104 if (TargetID != &NoPassID)
106 if (StandardID == &NoPassID)
107 report_fatal_error("Target cannot enable pass");
112 llvm_unreachable("Invalid command line option state");
115 /// Allow standard passes to be disabled by the command line, regardless of who
116 /// is adding the pass.
118 /// StandardID is the pass identified in the standard pass pipeline and provided
119 /// to addPass(). It may be a target-specific ID in the case that the target
120 /// directly adds its own pass, but in that case we harmlessly fall through.
122 /// TargetID is the pass that the target has configured to override StandardID.
124 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
125 /// pass to run. This allows multiple options to control a single pass depending
126 /// on where in the pipeline that pass is added.
127 static AnalysisID overridePass(AnalysisID StandardID, AnalysisID TargetID) {
128 if (StandardID == &PostRASchedulerID)
129 return applyDisable(TargetID, DisablePostRA);
131 if (StandardID == &BranchFolderPassID)
132 return applyDisable(TargetID, DisableBranchFold);
134 if (StandardID == &TailDuplicateID)
135 return applyDisable(TargetID, DisableTailDuplicate);
137 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
138 return applyDisable(TargetID, DisableEarlyTailDup);
140 if (StandardID == &MachineBlockPlacementID)
141 return applyDisable(TargetID, DisableCodePlace);
143 if (StandardID == &CodePlacementOptID)
144 return applyDisable(TargetID, DisableCodePlace);
146 if (StandardID == &StackSlotColoringID)
147 return applyDisable(TargetID, DisableSSC);
149 if (StandardID == &DeadMachineInstructionElimID)
150 return applyDisable(TargetID, DisableMachineDCE);
152 if (StandardID == &MachineLICMID)
153 return applyDisable(TargetID, DisableMachineLICM);
155 if (StandardID == &MachineCSEID)
156 return applyDisable(TargetID, DisableMachineCSE);
158 if (StandardID == &MachineSchedulerID)
159 return applyOverride(TargetID, EnableMachineSched, StandardID);
161 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
162 return applyDisable(TargetID, DisablePostRAMachineLICM);
164 if (StandardID == &MachineSinkingID)
165 return applyDisable(TargetID, DisableMachineSink);
167 if (StandardID == &MachineCopyPropagationID)
168 return applyDisable(TargetID, DisableCopyProp);
173 //===---------------------------------------------------------------------===//
175 //===---------------------------------------------------------------------===//
177 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
178 "Target Pass Configuration", false, false)
179 char TargetPassConfig::ID = 0;
181 static char NoPassIDAnchor = 0;
182 char &llvm::NoPassID = NoPassIDAnchor;
185 char TargetPassConfig::EarlyTailDuplicateID = 0;
186 char TargetPassConfig::PostRAMachineLICMID = 0;
189 class PassConfigImpl {
191 // List of passes explicitly substituted by this target. Normally this is
192 // empty, but it is a convenient way to suppress or replace specific passes
193 // that are part of a standard pass pipeline without overridding the entire
194 // pipeline. This mechanism allows target options to inherit a standard pass's
195 // user interface. For example, a target may disable a standard pass by
196 // default by substituting NoPass, and the user may still enable that standard
197 // pass with an explicit command line option.
198 DenseMap<AnalysisID,AnalysisID> TargetPasses;
202 // Out of line virtual method.
203 TargetPassConfig::~TargetPassConfig() {
207 // Out of line constructor provides default values for pass options and
208 // registers all common codegen passes.
209 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
210 : ImmutablePass(ID), TM(tm), PM(&pm), Impl(0), Initialized(false),
211 DisableVerify(false),
212 EnableTailMerge(true) {
214 Impl = new PassConfigImpl();
216 // Register all target independent codegen passes to activate their PassIDs,
217 // including this pass itself.
218 initializeCodeGen(*PassRegistry::getPassRegistry());
220 // Substitute Pseudo Pass IDs for real ones.
221 substitutePass(EarlyTailDuplicateID, TailDuplicateID);
222 substitutePass(PostRAMachineLICMID, MachineLICMID);
224 // Temporarily disable experimental passes.
225 substitutePass(MachineSchedulerID, NoPassID);
228 /// createPassConfig - Create a pass configuration object to be used by
229 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
231 /// Targets may override this to extend TargetPassConfig.
232 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
233 return new TargetPassConfig(this, PM);
236 TargetPassConfig::TargetPassConfig()
237 : ImmutablePass(ID), PM(0) {
238 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
241 // Helper to verify the analysis is really immutable.
242 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
243 assert(!Initialized && "PassConfig is immutable");
247 void TargetPassConfig::substitutePass(char &StandardID, char &TargetID) {
248 Impl->TargetPasses[&StandardID] = &TargetID;
251 AnalysisID TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
252 DenseMap<AnalysisID, AnalysisID>::const_iterator
253 I = Impl->TargetPasses.find(ID);
254 if (I == Impl->TargetPasses.end())
259 /// Add a CodeGen pass at this point in the pipeline after checking for target
260 /// and command line overrides.
261 AnalysisID TargetPassConfig::addPass(char &ID) {
262 assert(!Initialized && "PassConfig is immutable");
264 AnalysisID TargetID = getPassSubstitution(&ID);
265 AnalysisID FinalID = overridePass(&ID, TargetID);
266 if (FinalID == &NoPassID)
269 Pass *P = Pass::createPass(FinalID);
271 llvm_unreachable("Pass ID not registered");
276 void TargetPassConfig::printAndVerify(const char *Banner) const {
277 if (TM->shouldPrintMachineCode())
278 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
280 if (VerifyMachineCode)
281 PM->add(createMachineVerifierPass(Banner));
284 /// Add common target configurable passes that perform LLVM IR to IR transforms
285 /// following machine independent optimization.
286 void TargetPassConfig::addIRPasses() {
287 // Basic AliasAnalysis support.
288 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
289 // BasicAliasAnalysis wins if they disagree. This is intended to help
290 // support "obvious" type-punning idioms.
291 PM->add(createTypeBasedAliasAnalysisPass());
292 PM->add(createBasicAliasAnalysisPass());
294 // Before running any passes, run the verifier to determine if the input
295 // coming from the front-end and/or optimizer is valid.
297 PM->add(createVerifierPass());
299 // Run loop strength reduction before anything else.
300 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
301 PM->add(createLoopStrengthReducePass(getTargetLowering()));
303 PM->add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
306 PM->add(createGCLoweringPass());
308 // Make sure that no unreachable blocks are instruction selected.
309 PM->add(createUnreachableBlockEliminationPass());
312 /// Add common passes that perform LLVM IR to IR transforms in preparation for
313 /// instruction selection.
314 void TargetPassConfig::addISelPrepare() {
315 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
316 PM->add(createCodeGenPreparePass(getTargetLowering()));
318 PM->add(createStackProtectorPass(getTargetLowering()));
323 PM->add(createPrintFunctionPass("\n\n"
324 "*** Final LLVM Code input to ISel ***\n",
327 // All passes which modify the LLVM IR are now complete; run the verifier
328 // to ensure that the IR is valid.
330 PM->add(createVerifierPass());
333 /// Add the complete set of target-independent postISel code generator passes.
335 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
336 /// with nontrivial configuration or multiple passes are broken out below in
337 /// add%Stage routines.
339 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
340 /// addPre/Post methods with empty header implementations allow injecting
341 /// target-specific fixups just before or after major stages. Additionally,
342 /// targets have the flexibility to change pass order within a stage by
343 /// overriding default implementation of add%Stage routines below. Each
344 /// technique has maintainability tradeoffs because alternate pass orders are
345 /// not well supported. addPre/Post works better if the target pass is easily
346 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
347 /// the target should override the stage instead.
349 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
350 /// before/after any target-independent pass. But it's currently overkill.
351 void TargetPassConfig::addMachinePasses() {
352 // Print the instruction selected machine code...
353 printAndVerify("After Instruction Selection");
355 // Expand pseudo-instructions emitted by ISel.
356 addPass(ExpandISelPseudosID);
358 // Add passes that optimize machine instructions in SSA form.
359 if (getOptLevel() != CodeGenOpt::None) {
360 addMachineSSAOptimization();
363 // If the target requests it, assign local variables to stack slots relative
364 // to one another and simplify frame index references where possible.
365 addPass(LocalStackSlotAllocationID);
368 // Run pre-ra passes.
369 if (addPreRegAlloc())
370 printAndVerify("After PreRegAlloc passes");
372 // Run register allocation and passes that are tightly coupled with it,
373 // including phi elimination and scheduling.
374 if (getOptimizeRegAlloc())
375 addOptimizedRegAlloc(createRegAllocPass(true));
377 addFastRegAlloc(createRegAllocPass(false));
379 // Run post-ra passes.
380 if (addPostRegAlloc())
381 printAndVerify("After PostRegAlloc passes");
383 // Insert prolog/epilog code. Eliminate abstract frame index references...
384 addPass(PrologEpilogCodeInserterID);
385 printAndVerify("After PrologEpilogCodeInserter");
387 /// Add passes that optimize machine instructions after register allocation.
388 if (getOptLevel() != CodeGenOpt::None)
389 addMachineLateOptimization();
391 // Expand pseudo instructions before second scheduling pass.
392 addPass(ExpandPostRAPseudosID);
393 printAndVerify("After ExpandPostRAPseudos");
395 // Run pre-sched2 passes.
397 printAndVerify("After PreSched2 passes");
399 // Second pass scheduler.
400 if (getOptLevel() != CodeGenOpt::None) {
401 addPass(PostRASchedulerID);
402 printAndVerify("After PostRAScheduler");
406 addPass(GCMachineCodeAnalysisID);
408 PM->add(createGCInfoPrinter(dbgs()));
410 // Basic block placement.
411 if (getOptLevel() != CodeGenOpt::None)
414 if (addPreEmitPass())
415 printAndVerify("After PreEmit passes");
418 /// Add passes that optimize machine instructions in SSA form.
419 void TargetPassConfig::addMachineSSAOptimization() {
420 // Pre-ra tail duplication.
421 if (addPass(EarlyTailDuplicateID) != &NoPassID)
422 printAndVerify("After Pre-RegAlloc TailDuplicate");
424 // Optimize PHIs before DCE: removing dead PHI cycles may make more
425 // instructions dead.
426 addPass(OptimizePHIsID);
428 // If the target requests it, assign local variables to stack slots relative
429 // to one another and simplify frame index references where possible.
430 addPass(LocalStackSlotAllocationID);
432 // With optimization, dead code should already be eliminated. However
433 // there is one known exception: lowered code for arguments that are only
434 // used by tail calls, where the tail calls reuse the incoming stack
435 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
436 addPass(DeadMachineInstructionElimID);
437 printAndVerify("After codegen DCE pass");
439 addPass(MachineLICMID);
440 addPass(MachineCSEID);
441 addPass(MachineSinkingID);
442 printAndVerify("After Machine LICM, CSE and Sinking passes");
444 addPass(PeepholeOptimizerID);
445 printAndVerify("After codegen peephole optimization pass");
448 //===---------------------------------------------------------------------===//
449 /// Register Allocation Pass Configuration
450 //===---------------------------------------------------------------------===//
452 bool TargetPassConfig::getOptimizeRegAlloc() const {
453 switch (OptimizeRegAlloc) {
454 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
455 case cl::BOU_TRUE: return true;
456 case cl::BOU_FALSE: return false;
458 llvm_unreachable("Invalid optimize-regalloc state");
461 /// RegisterRegAlloc's global Registry tracks allocator registration.
462 MachinePassRegistry RegisterRegAlloc::Registry;
464 /// A dummy default pass factory indicates whether the register allocator is
465 /// overridden on the command line.
466 static FunctionPass *useDefaultRegisterAllocator() { return 0; }
467 static RegisterRegAlloc
468 defaultRegAlloc("default",
469 "pick register allocator based on -O option",
470 useDefaultRegisterAllocator);
472 /// -regalloc=... command line option.
473 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
474 RegisterPassParser<RegisterRegAlloc> >
476 cl::init(&useDefaultRegisterAllocator),
477 cl::desc("Register allocator to use"));
480 /// Instantiate the default register allocator pass for this target for either
481 /// the optimized or unoptimized allocation path. This will be added to the pass
482 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
483 /// in the optimized case.
485 /// A target that uses the standard regalloc pass order for fast or optimized
486 /// allocation may still override this for per-target regalloc
487 /// selection. But -regalloc=... always takes precedence.
488 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
490 return createGreedyRegisterAllocator();
492 return createFastRegisterAllocator();
495 /// Find and instantiate the register allocation pass requested by this target
496 /// at the current optimization level. Different register allocators are
497 /// defined as separate passes because they may require different analysis.
499 /// This helper ensures that the regalloc= option is always available,
500 /// even for targets that override the default allocator.
502 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
503 /// this can be folded into addPass.
504 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
505 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
507 // Initialize the global default.
510 RegisterRegAlloc::setDefault(RegAlloc);
512 if (Ctor != useDefaultRegisterAllocator)
515 // With no -regalloc= override, ask the target for a regalloc pass.
516 return createTargetRegisterAllocator(Optimized);
519 /// Add the minimum set of target-independent passes that are required for
520 /// register allocation. No coalescing or scheduling.
521 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
522 addPass(PHIEliminationID);
523 addPass(TwoAddressInstructionPassID);
525 PM->add(RegAllocPass);
526 printAndVerify("After Register Allocation");
529 /// Add standard target-independent passes that are tightly coupled with
530 /// optimized register allocation, including coalescing, machine instruction
531 /// scheduling, and register allocation itself.
532 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
533 // LiveVariables currently requires pure SSA form.
535 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
536 // LiveVariables can be removed completely, and LiveIntervals can be directly
537 // computed. (We still either need to regenerate kill flags after regalloc, or
538 // preferably fix the scavenger to not depend on them).
539 addPass(LiveVariablesID);
541 // Add passes that move from transformed SSA into conventional SSA. This is a
542 // "copy coalescing" problem.
544 if (!EnableStrongPHIElim) {
545 // Edge splitting is smarter with machine loop info.
546 addPass(MachineLoopInfoID);
547 addPass(PHIEliminationID);
549 addPass(TwoAddressInstructionPassID);
551 // FIXME: Either remove this pass completely, or fix it so that it works on
552 // SSA form. We could modify LiveIntervals to be independent of this pass, But
553 // it would be even better to simply eliminate *all* IMPLICIT_DEFs before
555 addPass(ProcessImplicitDefsID);
557 if (EnableStrongPHIElim)
558 addPass(StrongPHIEliminationID);
560 addPass(RegisterCoalescerID);
562 // PreRA instruction scheduling.
563 if (addPass(MachineSchedulerID) != &NoPassID)
564 printAndVerify("After Machine Scheduling");
566 // Add the selected register allocation pass.
567 PM->add(RegAllocPass);
568 printAndVerify("After Register Allocation");
570 // FinalizeRegAlloc is convenient until MachineInstrBundles is more mature,
571 // but eventually, all users of it should probably be moved to addPostRA and
572 // it can go away. Currently, it's the intended place for targets to run
573 // FinalizeMachineBundles, because passes other than MachineScheduling an
574 // RegAlloc itself may not be aware of bundles.
575 if (addFinalizeRegAlloc())
576 printAndVerify("After RegAlloc finalization");
578 // Perform stack slot coloring and post-ra machine LICM.
580 // FIXME: Re-enable coloring with register when it's capable of adding
582 addPass(StackSlotColoringID);
584 // Run post-ra machine LICM to hoist reloads / remats.
586 // FIXME: can this move into MachineLateOptimization?
587 addPass(PostRAMachineLICMID);
589 printAndVerify("After StackSlotColoring and postra Machine LICM");
592 //===---------------------------------------------------------------------===//
593 /// Post RegAlloc Pass Configuration
594 //===---------------------------------------------------------------------===//
596 /// Add passes that optimize machine instructions after register allocation.
597 void TargetPassConfig::addMachineLateOptimization() {
598 // Branch folding must be run after regalloc and prolog/epilog insertion.
599 if (addPass(BranchFolderPassID) != &NoPassID)
600 printAndVerify("After BranchFolding");
603 if (addPass(TailDuplicateID) != &NoPassID)
604 printAndVerify("After TailDuplicate");
607 if (addPass(MachineCopyPropagationID) != &NoPassID)
608 printAndVerify("After copy propagation pass");
611 /// Add standard basic block placement passes.
612 void TargetPassConfig::addBlockPlacement() {
613 AnalysisID ID = &NoPassID;
614 if (!DisableBlockPlacement) {
615 // MachineBlockPlacement is a new pass which subsumes the functionality of
616 // CodPlacementOpt. The old code placement pass can be restored by
617 // disabling block placement, but eventually it will be removed.
618 ID = addPass(MachineBlockPlacementID);
620 ID = addPass(CodePlacementOptID);
622 if (ID != &NoPassID) {
623 // Run a separate pass to collect block placement statistics.
624 if (EnableBlockPlacementStats)
625 addPass(MachineBlockPlacementStatsID);
627 printAndVerify("After machine block placement.");