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/CodeGen/Passes.h"
16 #include "llvm/Analysis/Passes.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/GCStrategy.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/RegAllocRegistry.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
30 #include "llvm/Transforms/Scalar.h"
34 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
35 cl::desc("Disable Post Regalloc"));
36 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
37 cl::desc("Disable branch folding"));
38 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
39 cl::desc("Disable tail duplication"));
40 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
41 cl::desc("Disable pre-register allocation tail duplication"));
42 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
43 cl::Hidden, cl::desc("Disable the probability-driven block placement, and "
44 "re-enable the old code placement pass"));
45 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
46 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
47 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
48 cl::desc("Disable code placement"));
49 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
50 cl::desc("Disable Stack Slot Coloring"));
51 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
52 cl::desc("Disable Machine Dead Code Elimination"));
53 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
54 cl::desc("Disable Early If-conversion"));
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<cl::boolOrDefault>
60 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
61 cl::desc("Enable optimized register allocation compilation path."));
62 static cl::opt<cl::boolOrDefault>
63 EnableMachineSched("enable-misched", cl::Hidden,
64 cl::desc("Enable the machine instruction scheduling pass."));
65 static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
66 cl::desc("Use strong PHI elimination."));
67 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
69 cl::desc("Disable Machine LICM"));
70 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
71 cl::desc("Disable Machine Sinking"));
72 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
73 cl::desc("Disable Loop Strength Reduction Pass"));
74 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
75 cl::desc("Disable Codegen Prepare"));
76 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
77 cl::desc("Disable Copy Propagation pass"));
78 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
79 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
80 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
81 cl::desc("Print LLVM IR input to isel pass"));
82 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
83 cl::desc("Dump garbage collector data"));
84 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
85 cl::desc("Verify generated machine code"),
86 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
87 static cl::opt<std::string>
88 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
89 cl::desc("Print machine instrs"),
90 cl::value_desc("pass-name"), cl::init("option-unspecified"));
92 // Experimental option to run live interval analysis early.
93 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
94 cl::desc("Run live interval analysis earlier in the pipeline"));
96 /// Allow standard passes to be disabled by command line options. This supports
97 /// simple binary flags that either suppress the pass or do nothing.
98 /// i.e. -disable-mypass=false has no effect.
99 /// These should be converted to boolOrDefault in order to use applyOverride.
100 static AnalysisID applyDisable(AnalysisID PassID, bool Override) {
106 /// Allow Pass selection to be overriden by command line options. This supports
107 /// flags with ternary conditions. TargetID is passed through by default. The
108 /// pass is suppressed when the option is false. When the option is true, the
109 /// StandardID is selected if the target provides no default.
110 static AnalysisID applyOverride(AnalysisID TargetID, cl::boolOrDefault Override,
111 AnalysisID StandardID) {
119 report_fatal_error("Target cannot enable pass");
124 llvm_unreachable("Invalid command line option state");
127 /// Allow standard passes to be disabled by the command line, regardless of who
128 /// is adding the pass.
130 /// StandardID is the pass identified in the standard pass pipeline and provided
131 /// to addPass(). It may be a target-specific ID in the case that the target
132 /// directly adds its own pass, but in that case we harmlessly fall through.
134 /// TargetID is the pass that the target has configured to override StandardID.
136 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
137 /// pass to run. This allows multiple options to control a single pass depending
138 /// on where in the pipeline that pass is added.
139 static AnalysisID overridePass(AnalysisID StandardID, AnalysisID TargetID) {
140 if (StandardID == &PostRASchedulerID)
141 return applyDisable(TargetID, DisablePostRA);
143 if (StandardID == &BranchFolderPassID)
144 return applyDisable(TargetID, DisableBranchFold);
146 if (StandardID == &TailDuplicateID)
147 return applyDisable(TargetID, DisableTailDuplicate);
149 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
150 return applyDisable(TargetID, DisableEarlyTailDup);
152 if (StandardID == &MachineBlockPlacementID)
153 return applyDisable(TargetID, DisableCodePlace);
155 if (StandardID == &CodePlacementOptID)
156 return applyDisable(TargetID, DisableCodePlace);
158 if (StandardID == &StackSlotColoringID)
159 return applyDisable(TargetID, DisableSSC);
161 if (StandardID == &DeadMachineInstructionElimID)
162 return applyDisable(TargetID, DisableMachineDCE);
164 if (StandardID == &EarlyIfConverterID)
165 return applyDisable(TargetID, DisableEarlyIfConversion);
167 if (StandardID == &MachineLICMID)
168 return applyDisable(TargetID, DisableMachineLICM);
170 if (StandardID == &MachineCSEID)
171 return applyDisable(TargetID, DisableMachineCSE);
173 if (StandardID == &MachineSchedulerID)
174 return applyOverride(TargetID, EnableMachineSched, StandardID);
176 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
177 return applyDisable(TargetID, DisablePostRAMachineLICM);
179 if (StandardID == &MachineSinkingID)
180 return applyDisable(TargetID, DisableMachineSink);
182 if (StandardID == &MachineCopyPropagationID)
183 return applyDisable(TargetID, DisableCopyProp);
188 //===---------------------------------------------------------------------===//
190 //===---------------------------------------------------------------------===//
192 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
193 "Target Pass Configuration", false, false)
194 char TargetPassConfig::ID = 0;
197 char TargetPassConfig::EarlyTailDuplicateID = 0;
198 char TargetPassConfig::PostRAMachineLICMID = 0;
201 class PassConfigImpl {
203 // List of passes explicitly substituted by this target. Normally this is
204 // empty, but it is a convenient way to suppress or replace specific passes
205 // that are part of a standard pass pipeline without overridding the entire
206 // pipeline. This mechanism allows target options to inherit a standard pass's
207 // user interface. For example, a target may disable a standard pass by
208 // default by substituting a pass ID of zero, and the user may still enable
209 // that standard pass with an explicit command line option.
210 DenseMap<AnalysisID,AnalysisID> TargetPasses;
212 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
213 /// is inserted after each instance of the first one.
214 SmallVector<std::pair<AnalysisID, AnalysisID>, 4> InsertedPasses;
218 // Out of line virtual method.
219 TargetPassConfig::~TargetPassConfig() {
223 // Out of line constructor provides default values for pass options and
224 // registers all common codegen passes.
225 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
226 : ImmutablePass(ID), PM(&pm), StartAfter(0), StopAfter(0),
227 Started(true), Stopped(false), TM(tm), Impl(0), Initialized(false),
228 DisableVerify(false),
229 EnableTailMerge(true) {
231 Impl = new PassConfigImpl();
233 // Register all target independent codegen passes to activate their PassIDs,
234 // including this pass itself.
235 initializeCodeGen(*PassRegistry::getPassRegistry());
237 // Substitute Pseudo Pass IDs for real ones.
238 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
239 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
241 // Temporarily disable experimental passes.
242 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
243 if (!ST.enableMachineScheduler())
244 disablePass(&MachineSchedulerID);
247 /// Insert InsertedPassID pass after TargetPassID.
248 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
249 AnalysisID InsertedPassID) {
250 assert(TargetPassID != InsertedPassID && "Insert a pass after itself!");
251 std::pair<AnalysisID, AnalysisID> P(TargetPassID, InsertedPassID);
252 Impl->InsertedPasses.push_back(P);
255 /// createPassConfig - Create a pass configuration object to be used by
256 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
258 /// Targets may override this to extend TargetPassConfig.
259 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
260 return new TargetPassConfig(this, PM);
263 TargetPassConfig::TargetPassConfig()
264 : ImmutablePass(ID), PM(0) {
265 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
268 // Helper to verify the analysis is really immutable.
269 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
270 assert(!Initialized && "PassConfig is immutable");
274 void TargetPassConfig::substitutePass(AnalysisID StandardID,
275 AnalysisID TargetID) {
276 Impl->TargetPasses[StandardID] = TargetID;
279 AnalysisID TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
280 DenseMap<AnalysisID, AnalysisID>::const_iterator
281 I = Impl->TargetPasses.find(ID);
282 if (I == Impl->TargetPasses.end())
287 /// Add a pass to the PassManager if that pass is supposed to be run. If the
288 /// Started/Stopped flags indicate either that the compilation should start at
289 /// a later pass or that it should stop after an earlier pass, then do not add
290 /// the pass. Finally, compare the current pass against the StartAfter
291 /// and StopAfter options and change the Started/Stopped flags accordingly.
292 void TargetPassConfig::addPass(Pass *P) {
293 assert(!Initialized && "PassConfig is immutable");
295 // Cache the Pass ID here in case the pass manager finds this pass is
296 // redundant with ones already scheduled / available, and deletes it.
297 // Fundamentally, once we add the pass to the manager, we no longer own it
298 // and shouldn't reference it.
299 AnalysisID PassID = P->getPassID();
301 if (Started && !Stopped)
303 if (StopAfter == PassID)
305 if (StartAfter == PassID)
307 if (Stopped && !Started)
308 report_fatal_error("Cannot stop compilation after pass that is not run");
311 /// Add a CodeGen pass at this point in the pipeline after checking for target
312 /// and command line overrides.
313 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
314 AnalysisID TargetID = getPassSubstitution(PassID);
315 AnalysisID FinalID = overridePass(PassID, TargetID);
319 Pass *P = Pass::createPass(FinalID);
321 llvm_unreachable("Pass ID not registered");
323 // Add the passes after the pass P if there is any.
324 for (SmallVector<std::pair<AnalysisID, AnalysisID>, 4>::iterator
325 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
327 if ((*I).first == PassID) {
328 assert((*I).second && "Illegal Pass ID!");
329 Pass *NP = Pass::createPass((*I).second);
330 assert(NP && "Pass ID not registered");
337 void TargetPassConfig::printAndVerify(const char *Banner) {
338 if (TM->shouldPrintMachineCode())
339 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
341 if (VerifyMachineCode)
342 addPass(createMachineVerifierPass(Banner));
345 /// Add common target configurable passes that perform LLVM IR to IR transforms
346 /// following machine independent optimization.
347 void TargetPassConfig::addIRPasses() {
348 // Basic AliasAnalysis support.
349 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
350 // BasicAliasAnalysis wins if they disagree. This is intended to help
351 // support "obvious" type-punning idioms.
352 addPass(createTypeBasedAliasAnalysisPass());
353 addPass(createBasicAliasAnalysisPass());
355 // Before running any passes, run the verifier to determine if the input
356 // coming from the front-end and/or optimizer is valid.
358 addPass(createVerifierPass());
360 // Run loop strength reduction before anything else.
361 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
362 addPass(createLoopStrengthReducePass());
364 addPass(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
367 addPass(createGCLoweringPass());
369 // Make sure that no unreachable blocks are instruction selected.
370 addPass(createUnreachableBlockEliminationPass());
373 /// Turn exception handling constructs into something the code generators can
375 void TargetPassConfig::addPassesToHandleExceptions() {
376 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
377 case ExceptionHandling::SjLj:
378 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
379 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
380 // catch info can get misplaced when a selector ends up more than one block
381 // removed from the parent invoke(s). This could happen when a landing
382 // pad is shared by multiple invokes and is also a target of a normal
383 // edge from elsewhere.
384 addPass(createSjLjEHPreparePass(TM->getTargetLowering()));
386 case ExceptionHandling::DwarfCFI:
387 case ExceptionHandling::ARM:
388 case ExceptionHandling::Win64:
389 addPass(createDwarfEHPass(TM));
391 case ExceptionHandling::None:
392 addPass(createLowerInvokePass(TM->getTargetLowering()));
394 // The lower invoke pass may create unreachable code. Remove it.
395 addPass(createUnreachableBlockEliminationPass());
400 /// Add pass to prepare the LLVM IR for code generation. This should be done
401 /// before exception handling preparation passes.
402 void TargetPassConfig::addCodeGenPrepare() {
403 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
404 addPass(createCodeGenPreparePass(getTargetLowering()));
407 /// Add common passes that perform LLVM IR to IR transforms in preparation for
408 /// instruction selection.
409 void TargetPassConfig::addISelPrepare() {
410 addPass(createStackProtectorPass(getTargetLowering()));
415 addPass(createPrintFunctionPass("\n\n"
416 "*** Final LLVM Code input to ISel ***\n",
419 // All passes which modify the LLVM IR are now complete; run the verifier
420 // to ensure that the IR is valid.
422 addPass(createVerifierPass());
425 /// Add the complete set of target-independent postISel code generator passes.
427 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
428 /// with nontrivial configuration or multiple passes are broken out below in
429 /// add%Stage routines.
431 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
432 /// addPre/Post methods with empty header implementations allow injecting
433 /// target-specific fixups just before or after major stages. Additionally,
434 /// targets have the flexibility to change pass order within a stage by
435 /// overriding default implementation of add%Stage routines below. Each
436 /// technique has maintainability tradeoffs because alternate pass orders are
437 /// not well supported. addPre/Post works better if the target pass is easily
438 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
439 /// the target should override the stage instead.
441 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
442 /// before/after any target-independent pass. But it's currently overkill.
443 void TargetPassConfig::addMachinePasses() {
444 // Insert a machine instr printer pass after the specified pass.
445 // If -print-machineinstrs specified, print machineinstrs after all passes.
446 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
447 TM->Options.PrintMachineCode = true;
448 else if (!StringRef(PrintMachineInstrs.getValue())
449 .equals("option-unspecified")) {
450 const PassRegistry *PR = PassRegistry::getPassRegistry();
451 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
452 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
453 assert (TPI && IPI && "Pass ID not registered!");
454 const char *TID = (const char *)(TPI->getTypeInfo());
455 const char *IID = (const char *)(IPI->getTypeInfo());
456 insertPass(TID, IID);
459 // Print the instruction selected machine code...
460 printAndVerify("After Instruction Selection");
462 // Expand pseudo-instructions emitted by ISel.
463 if (addPass(&ExpandISelPseudosID))
464 printAndVerify("After ExpandISelPseudos");
466 // Add passes that optimize machine instructions in SSA form.
467 if (getOptLevel() != CodeGenOpt::None) {
468 addMachineSSAOptimization();
470 // If the target requests it, assign local variables to stack slots relative
471 // to one another and simplify frame index references where possible.
472 addPass(&LocalStackSlotAllocationID);
475 // Run pre-ra passes.
476 if (addPreRegAlloc())
477 printAndVerify("After PreRegAlloc passes");
479 // Run register allocation and passes that are tightly coupled with it,
480 // including phi elimination and scheduling.
481 if (getOptimizeRegAlloc())
482 addOptimizedRegAlloc(createRegAllocPass(true));
484 addFastRegAlloc(createRegAllocPass(false));
486 // Run post-ra passes.
487 if (addPostRegAlloc())
488 printAndVerify("After PostRegAlloc passes");
490 // Insert prolog/epilog code. Eliminate abstract frame index references...
491 addPass(&PrologEpilogCodeInserterID);
492 printAndVerify("After PrologEpilogCodeInserter");
494 /// Add passes that optimize machine instructions after register allocation.
495 if (getOptLevel() != CodeGenOpt::None)
496 addMachineLateOptimization();
498 // Expand pseudo instructions before second scheduling pass.
499 addPass(&ExpandPostRAPseudosID);
500 printAndVerify("After ExpandPostRAPseudos");
502 // Run pre-sched2 passes.
504 printAndVerify("After PreSched2 passes");
506 // Second pass scheduler.
507 if (getOptLevel() != CodeGenOpt::None) {
508 addPass(&PostRASchedulerID);
509 printAndVerify("After PostRAScheduler");
515 addPass(createGCInfoPrinter(dbgs()));
518 // Basic block placement.
519 if (getOptLevel() != CodeGenOpt::None)
522 if (addPreEmitPass())
523 printAndVerify("After PreEmit passes");
526 /// Add passes that optimize machine instructions in SSA form.
527 void TargetPassConfig::addMachineSSAOptimization() {
528 // Pre-ra tail duplication.
529 if (addPass(&EarlyTailDuplicateID))
530 printAndVerify("After Pre-RegAlloc TailDuplicate");
532 // Optimize PHIs before DCE: removing dead PHI cycles may make more
533 // instructions dead.
534 addPass(&OptimizePHIsID);
536 // This pass merges large allocas. StackSlotColoring is a different pass
537 // which merges spill slots.
538 addPass(&StackColoringID);
540 // If the target requests it, assign local variables to stack slots relative
541 // to one another and simplify frame index references where possible.
542 addPass(&LocalStackSlotAllocationID);
544 // With optimization, dead code should already be eliminated. However
545 // there is one known exception: lowered code for arguments that are only
546 // used by tail calls, where the tail calls reuse the incoming stack
547 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
548 addPass(&DeadMachineInstructionElimID);
549 printAndVerify("After codegen DCE pass");
551 // Allow targets to insert passes that improve instruction level parallelism,
552 // like if-conversion. Such passes will typically need dominator trees and
553 // loop info, just like LICM and CSE below.
555 printAndVerify("After ILP optimizations");
557 addPass(&MachineLICMID);
558 addPass(&MachineCSEID);
559 addPass(&MachineSinkingID);
560 printAndVerify("After Machine LICM, CSE and Sinking passes");
562 addPass(&PeepholeOptimizerID);
563 printAndVerify("After codegen peephole optimization pass");
566 //===---------------------------------------------------------------------===//
567 /// Register Allocation Pass Configuration
568 //===---------------------------------------------------------------------===//
570 bool TargetPassConfig::getOptimizeRegAlloc() const {
571 switch (OptimizeRegAlloc) {
572 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
573 case cl::BOU_TRUE: return true;
574 case cl::BOU_FALSE: return false;
576 llvm_unreachable("Invalid optimize-regalloc state");
579 /// RegisterRegAlloc's global Registry tracks allocator registration.
580 MachinePassRegistry RegisterRegAlloc::Registry;
582 /// A dummy default pass factory indicates whether the register allocator is
583 /// overridden on the command line.
584 static FunctionPass *useDefaultRegisterAllocator() { return 0; }
585 static RegisterRegAlloc
586 defaultRegAlloc("default",
587 "pick register allocator based on -O option",
588 useDefaultRegisterAllocator);
590 /// -regalloc=... command line option.
591 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
592 RegisterPassParser<RegisterRegAlloc> >
594 cl::init(&useDefaultRegisterAllocator),
595 cl::desc("Register allocator to use"));
598 /// Instantiate the default register allocator pass for this target for either
599 /// the optimized or unoptimized allocation path. This will be added to the pass
600 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
601 /// in the optimized case.
603 /// A target that uses the standard regalloc pass order for fast or optimized
604 /// allocation may still override this for per-target regalloc
605 /// selection. But -regalloc=... always takes precedence.
606 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
608 return createGreedyRegisterAllocator();
610 return createFastRegisterAllocator();
613 /// Find and instantiate the register allocation pass requested by this target
614 /// at the current optimization level. Different register allocators are
615 /// defined as separate passes because they may require different analysis.
617 /// This helper ensures that the regalloc= option is always available,
618 /// even for targets that override the default allocator.
620 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
621 /// this can be folded into addPass.
622 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
623 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
625 // Initialize the global default.
628 RegisterRegAlloc::setDefault(RegAlloc);
630 if (Ctor != useDefaultRegisterAllocator)
633 // With no -regalloc= override, ask the target for a regalloc pass.
634 return createTargetRegisterAllocator(Optimized);
637 /// Add the minimum set of target-independent passes that are required for
638 /// register allocation. No coalescing or scheduling.
639 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
640 addPass(&PHIEliminationID);
641 addPass(&TwoAddressInstructionPassID);
643 addPass(RegAllocPass);
644 printAndVerify("After Register Allocation");
647 /// Add standard target-independent passes that are tightly coupled with
648 /// optimized register allocation, including coalescing, machine instruction
649 /// scheduling, and register allocation itself.
650 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
651 addPass(&ProcessImplicitDefsID);
653 // LiveVariables currently requires pure SSA form.
655 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
656 // LiveVariables can be removed completely, and LiveIntervals can be directly
657 // computed. (We still either need to regenerate kill flags after regalloc, or
658 // preferably fix the scavenger to not depend on them).
659 addPass(&LiveVariablesID);
661 // Add passes that move from transformed SSA into conventional SSA. This is a
662 // "copy coalescing" problem.
664 if (!EnableStrongPHIElim) {
665 // Edge splitting is smarter with machine loop info.
666 addPass(&MachineLoopInfoID);
667 addPass(&PHIEliminationID);
670 // Eventually, we want to run LiveIntervals before PHI elimination.
671 if (EarlyLiveIntervals)
672 addPass(&LiveIntervalsID);
674 addPass(&TwoAddressInstructionPassID);
676 if (EnableStrongPHIElim)
677 addPass(&StrongPHIEliminationID);
679 addPass(&RegisterCoalescerID);
681 // PreRA instruction scheduling.
682 if (addPass(&MachineSchedulerID))
683 printAndVerify("After Machine Scheduling");
685 // Add the selected register allocation pass.
686 addPass(RegAllocPass);
687 printAndVerify("After Register Allocation, before rewriter");
689 // Allow targets to change the register assignments before rewriting.
691 printAndVerify("After pre-rewrite passes");
693 // Finally rewrite virtual registers.
694 addPass(&VirtRegRewriterID);
695 printAndVerify("After Virtual Register Rewriter");
697 // FinalizeRegAlloc is convenient until MachineInstrBundles is more mature,
698 // but eventually, all users of it should probably be moved to addPostRA and
699 // it can go away. Currently, it's the intended place for targets to run
700 // FinalizeMachineBundles, because passes other than MachineScheduling an
701 // RegAlloc itself may not be aware of bundles.
702 if (addFinalizeRegAlloc())
703 printAndVerify("After RegAlloc finalization");
705 // Perform stack slot coloring and post-ra machine LICM.
707 // FIXME: Re-enable coloring with register when it's capable of adding
709 addPass(&StackSlotColoringID);
711 // Run post-ra machine LICM to hoist reloads / remats.
713 // FIXME: can this move into MachineLateOptimization?
714 addPass(&PostRAMachineLICMID);
716 printAndVerify("After StackSlotColoring and postra Machine LICM");
719 //===---------------------------------------------------------------------===//
720 /// Post RegAlloc Pass Configuration
721 //===---------------------------------------------------------------------===//
723 /// Add passes that optimize machine instructions after register allocation.
724 void TargetPassConfig::addMachineLateOptimization() {
725 // Branch folding must be run after regalloc and prolog/epilog insertion.
726 if (addPass(&BranchFolderPassID))
727 printAndVerify("After BranchFolding");
730 if (addPass(&TailDuplicateID))
731 printAndVerify("After TailDuplicate");
734 if (addPass(&MachineCopyPropagationID))
735 printAndVerify("After copy propagation pass");
738 /// Add standard GC passes.
739 bool TargetPassConfig::addGCPasses() {
740 addPass(&GCMachineCodeAnalysisID);
744 /// Add standard basic block placement passes.
745 void TargetPassConfig::addBlockPlacement() {
746 AnalysisID PassID = 0;
747 if (!DisableBlockPlacement) {
748 // MachineBlockPlacement is a new pass which subsumes the functionality of
749 // CodPlacementOpt. The old code placement pass can be restored by
750 // disabling block placement, but eventually it will be removed.
751 PassID = addPass(&MachineBlockPlacementID);
753 PassID = addPass(&CodePlacementOptID);
756 // Run a separate pass to collect block placement statistics.
757 if (EnableBlockPlacementStats)
758 addPass(&MachineBlockPlacementStatsID);
760 printAndVerify("After machine block placement.");