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/CodeGen/GCStrategy.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/IR/IRPrintingPasses.h"
21 #include "llvm/IR/Verifier.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/TargetSubtargetInfo.h"
29 #include "llvm/Transforms/Scalar.h"
33 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
34 cl::desc("Disable Post Regalloc"));
35 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
36 cl::desc("Disable branch folding"));
37 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
38 cl::desc("Disable tail duplication"));
39 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
40 cl::desc("Disable pre-register allocation tail duplication"));
41 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
42 cl::Hidden, cl::desc("Disable probability-driven block placement"));
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> DisableSSC("disable-ssc", cl::Hidden,
46 cl::desc("Disable Stack Slot Coloring"));
47 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
48 cl::desc("Disable Machine Dead Code Elimination"));
49 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
50 cl::desc("Disable Early If-conversion"));
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",
60 cl::desc("Enable the machine instruction scheduling pass."));
61 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
63 cl::desc("Disable Machine LICM"));
64 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
65 cl::desc("Disable Machine Sinking"));
66 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
67 cl::desc("Disable Loop Strength Reduction Pass"));
68 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
69 cl::Hidden, cl::desc("Disable ConstantHoisting"));
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")!=nullptr));
83 static cl::opt<std::string>
84 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
85 cl::desc("Print machine instrs"),
86 cl::value_desc("pass-name"), cl::init("option-unspecified"));
88 // Temporary option to allow experimenting with MachineScheduler as a post-RA
89 // scheduler. Targets can "properly" enable this with
90 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
91 // wouldn't be part of the standard pass pipeline, and the target would just add
92 // a PostRA scheduling pass wherever it wants.
93 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
94 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
96 // Experimental option to run live interval analysis early.
97 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
98 cl::desc("Run live interval analysis earlier in the pipeline"));
100 /// Allow standard passes to be disabled by command line options. This supports
101 /// simple binary flags that either suppress the pass or do nothing.
102 /// i.e. -disable-mypass=false has no effect.
103 /// These should be converted to boolOrDefault in order to use applyOverride.
104 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
107 return IdentifyingPassPtr();
111 /// Allow Pass selection to be overriden by command line options. This supports
112 /// flags with ternary conditions. TargetID is passed through by default. The
113 /// pass is suppressed when the option is false. When the option is true, the
114 /// StandardID is selected if the target provides no default.
115 static IdentifyingPassPtr applyOverride(IdentifyingPassPtr TargetID,
116 cl::boolOrDefault Override,
117 AnalysisID StandardID) {
122 if (TargetID.isValid())
124 if (StandardID == nullptr)
125 report_fatal_error("Target cannot enable pass");
128 return IdentifyingPassPtr();
130 llvm_unreachable("Invalid command line option state");
133 /// Allow standard passes to be disabled by the command line, regardless of who
134 /// is adding the pass.
136 /// StandardID is the pass identified in the standard pass pipeline and provided
137 /// to addPass(). It may be a target-specific ID in the case that the target
138 /// directly adds its own pass, but in that case we harmlessly fall through.
140 /// TargetID is the pass that the target has configured to override StandardID.
142 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
143 /// pass to run. This allows multiple options to control a single pass depending
144 /// on where in the pipeline that pass is added.
145 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
146 IdentifyingPassPtr TargetID) {
147 if (StandardID == &PostRASchedulerID)
148 return applyDisable(TargetID, DisablePostRA);
150 if (StandardID == &BranchFolderPassID)
151 return applyDisable(TargetID, DisableBranchFold);
153 if (StandardID == &TailDuplicateID)
154 return applyDisable(TargetID, DisableTailDuplicate);
156 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
157 return applyDisable(TargetID, DisableEarlyTailDup);
159 if (StandardID == &MachineBlockPlacementID)
160 return applyDisable(TargetID, DisableBlockPlacement);
162 if (StandardID == &StackSlotColoringID)
163 return applyDisable(TargetID, DisableSSC);
165 if (StandardID == &DeadMachineInstructionElimID)
166 return applyDisable(TargetID, DisableMachineDCE);
168 if (StandardID == &EarlyIfConverterID)
169 return applyDisable(TargetID, DisableEarlyIfConversion);
171 if (StandardID == &MachineLICMID)
172 return applyDisable(TargetID, DisableMachineLICM);
174 if (StandardID == &MachineCSEID)
175 return applyDisable(TargetID, DisableMachineCSE);
177 if (StandardID == &MachineSchedulerID)
178 return applyOverride(TargetID, EnableMachineSched, StandardID);
180 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
181 return applyDisable(TargetID, DisablePostRAMachineLICM);
183 if (StandardID == &MachineSinkingID)
184 return applyDisable(TargetID, DisableMachineSink);
186 if (StandardID == &MachineCopyPropagationID)
187 return applyDisable(TargetID, DisableCopyProp);
192 //===---------------------------------------------------------------------===//
194 //===---------------------------------------------------------------------===//
196 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
197 "Target Pass Configuration", false, false)
198 char TargetPassConfig::ID = 0;
201 char TargetPassConfig::EarlyTailDuplicateID = 0;
202 char TargetPassConfig::PostRAMachineLICMID = 0;
205 class PassConfigImpl {
207 // List of passes explicitly substituted by this target. Normally this is
208 // empty, but it is a convenient way to suppress or replace specific passes
209 // that are part of a standard pass pipeline without overridding the entire
210 // pipeline. This mechanism allows target options to inherit a standard pass's
211 // user interface. For example, a target may disable a standard pass by
212 // default by substituting a pass ID of zero, and the user may still enable
213 // that standard pass with an explicit command line option.
214 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
216 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
217 /// is inserted after each instance of the first one.
218 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
222 // Out of line virtual method.
223 TargetPassConfig::~TargetPassConfig() {
227 // Out of line constructor provides default values for pass options and
228 // registers all common codegen passes.
229 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
230 : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
231 Started(true), Stopped(false), TM(tm), Impl(nullptr), Initialized(false),
232 DisableVerify(false),
233 EnableTailMerge(true) {
235 Impl = new PassConfigImpl();
237 // Register all target independent codegen passes to activate their PassIDs,
238 // including this pass itself.
239 initializeCodeGen(*PassRegistry::getPassRegistry());
241 // Substitute Pseudo Pass IDs for real ones.
242 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
243 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
245 // Temporarily disable experimental passes.
246 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
247 if (!ST.useMachineScheduler())
248 disablePass(&MachineSchedulerID);
251 /// Insert InsertedPassID pass after TargetPassID.
252 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
253 IdentifyingPassPtr InsertedPassID) {
254 assert(((!InsertedPassID.isInstance() &&
255 TargetPassID != InsertedPassID.getID()) ||
256 (InsertedPassID.isInstance() &&
257 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
258 "Insert a pass after itself!");
259 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
260 Impl->InsertedPasses.push_back(P);
263 /// createPassConfig - Create a pass configuration object to be used by
264 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
266 /// Targets may override this to extend TargetPassConfig.
267 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
268 return new TargetPassConfig(this, PM);
271 TargetPassConfig::TargetPassConfig()
272 : ImmutablePass(ID), PM(nullptr) {
273 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
276 // Helper to verify the analysis is really immutable.
277 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
278 assert(!Initialized && "PassConfig is immutable");
282 void TargetPassConfig::substitutePass(AnalysisID StandardID,
283 IdentifyingPassPtr TargetID) {
284 Impl->TargetPasses[StandardID] = TargetID;
287 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
288 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
289 I = Impl->TargetPasses.find(ID);
290 if (I == Impl->TargetPasses.end())
295 /// Add a pass to the PassManager if that pass is supposed to be run. If the
296 /// Started/Stopped flags indicate either that the compilation should start at
297 /// a later pass or that it should stop after an earlier pass, then do not add
298 /// the pass. Finally, compare the current pass against the StartAfter
299 /// and StopAfter options and change the Started/Stopped flags accordingly.
300 void TargetPassConfig::addPass(Pass *P) {
301 assert(!Initialized && "PassConfig is immutable");
303 // Cache the Pass ID here in case the pass manager finds this pass is
304 // redundant with ones already scheduled / available, and deletes it.
305 // Fundamentally, once we add the pass to the manager, we no longer own it
306 // and shouldn't reference it.
307 AnalysisID PassID = P->getPassID();
309 if (Started && !Stopped)
313 if (StopAfter == PassID)
315 if (StartAfter == PassID)
317 if (Stopped && !Started)
318 report_fatal_error("Cannot stop compilation after pass that is not run");
321 /// Add a CodeGen pass at this point in the pipeline after checking for target
322 /// and command line overrides.
324 /// addPass cannot return a pointer to the pass instance because is internal the
325 /// PassManager and the instance we create here may already be freed.
326 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
327 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
328 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
329 if (!FinalPtr.isValid())
333 if (FinalPtr.isInstance())
334 P = FinalPtr.getInstance();
336 P = Pass::createPass(FinalPtr.getID());
338 llvm_unreachable("Pass ID not registered");
340 AnalysisID FinalID = P->getPassID();
341 addPass(P); // Ends the lifetime of P.
343 // Add the passes after the pass P if there is any.
344 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
345 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
347 if ((*I).first == PassID) {
348 assert((*I).second.isValid() && "Illegal Pass ID!");
350 if ((*I).second.isInstance())
351 NP = (*I).second.getInstance();
353 NP = Pass::createPass((*I).second.getID());
354 assert(NP && "Pass ID not registered");
362 void TargetPassConfig::printAndVerify(const char *Banner) {
363 if (TM->shouldPrintMachineCode())
364 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
366 if (VerifyMachineCode)
367 addPass(createMachineVerifierPass(Banner));
370 /// Add common target configurable passes that perform LLVM IR to IR transforms
371 /// following machine independent optimization.
372 void TargetPassConfig::addIRPasses() {
373 // Basic AliasAnalysis support.
374 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
375 // BasicAliasAnalysis wins if they disagree. This is intended to help
376 // support "obvious" type-punning idioms.
377 addPass(createTypeBasedAliasAnalysisPass());
378 addPass(createBasicAliasAnalysisPass());
380 // Before running any passes, run the verifier to determine if the input
381 // coming from the front-end and/or optimizer is valid.
382 if (!DisableVerify) {
383 addPass(createVerifierPass());
384 addPass(createDebugInfoVerifierPass());
387 // Run loop strength reduction before anything else.
388 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
389 addPass(createLoopStrengthReducePass());
391 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
394 addPass(createGCLoweringPass());
396 // Make sure that no unreachable blocks are instruction selected.
397 addPass(createUnreachableBlockEliminationPass());
399 // Prepare expensive constants for SelectionDAG.
400 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
401 addPass(createConstantHoistingPass());
404 /// Turn exception handling constructs into something the code generators can
406 void TargetPassConfig::addPassesToHandleExceptions() {
407 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
408 case ExceptionHandling::SjLj:
409 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
410 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
411 // catch info can get misplaced when a selector ends up more than one block
412 // removed from the parent invoke(s). This could happen when a landing
413 // pad is shared by multiple invokes and is also a target of a normal
414 // edge from elsewhere.
415 addPass(createSjLjEHPreparePass(TM));
417 case ExceptionHandling::DwarfCFI:
418 case ExceptionHandling::ARM:
419 case ExceptionHandling::WinEH:
420 addPass(createDwarfEHPass(TM));
422 case ExceptionHandling::None:
423 addPass(createLowerInvokePass());
425 // The lower invoke pass may create unreachable code. Remove it.
426 addPass(createUnreachableBlockEliminationPass());
431 /// Add pass to prepare the LLVM IR for code generation. This should be done
432 /// before exception handling preparation passes.
433 void TargetPassConfig::addCodeGenPrepare() {
434 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
435 addPass(createCodeGenPreparePass(TM));
438 /// Add common passes that perform LLVM IR to IR transforms in preparation for
439 /// instruction selection.
440 void TargetPassConfig::addISelPrepare() {
443 // Need to verify DebugInfo *before* creating the stack protector analysis.
444 // It's a function pass, and verifying between it and its users causes a
447 addPass(createDebugInfoVerifierPass());
449 addPass(createStackProtectorPass(TM));
452 addPass(createPrintFunctionPass(
453 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
455 // All passes which modify the LLVM IR are now complete; run the verifier
456 // to ensure that the IR is valid.
458 addPass(createVerifierPass());
461 /// Add the complete set of target-independent postISel code generator passes.
463 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
464 /// with nontrivial configuration or multiple passes are broken out below in
465 /// add%Stage routines.
467 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
468 /// addPre/Post methods with empty header implementations allow injecting
469 /// target-specific fixups just before or after major stages. Additionally,
470 /// targets have the flexibility to change pass order within a stage by
471 /// overriding default implementation of add%Stage routines below. Each
472 /// technique has maintainability tradeoffs because alternate pass orders are
473 /// not well supported. addPre/Post works better if the target pass is easily
474 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
475 /// the target should override the stage instead.
477 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
478 /// before/after any target-independent pass. But it's currently overkill.
479 void TargetPassConfig::addMachinePasses() {
480 // Insert a machine instr printer pass after the specified pass.
481 // If -print-machineinstrs specified, print machineinstrs after all passes.
482 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
483 TM->Options.PrintMachineCode = true;
484 else if (!StringRef(PrintMachineInstrs.getValue())
485 .equals("option-unspecified")) {
486 const PassRegistry *PR = PassRegistry::getPassRegistry();
487 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
488 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
489 assert (TPI && IPI && "Pass ID not registered!");
490 const char *TID = (const char *)(TPI->getTypeInfo());
491 const char *IID = (const char *)(IPI->getTypeInfo());
492 insertPass(TID, IID);
495 // Print the instruction selected machine code...
496 printAndVerify("After Instruction Selection");
498 // Expand pseudo-instructions emitted by ISel.
499 if (addPass(&ExpandISelPseudosID))
500 printAndVerify("After ExpandISelPseudos");
502 // Add passes that optimize machine instructions in SSA form.
503 if (getOptLevel() != CodeGenOpt::None) {
504 addMachineSSAOptimization();
506 // If the target requests it, assign local variables to stack slots relative
507 // to one another and simplify frame index references where possible.
508 addPass(&LocalStackSlotAllocationID);
511 // Run pre-ra passes.
512 if (addPreRegAlloc())
513 printAndVerify("After PreRegAlloc passes");
515 // Run register allocation and passes that are tightly coupled with it,
516 // including phi elimination and scheduling.
517 if (getOptimizeRegAlloc())
518 addOptimizedRegAlloc(createRegAllocPass(true));
520 addFastRegAlloc(createRegAllocPass(false));
522 // Run post-ra passes.
523 if (addPostRegAlloc())
524 printAndVerify("After PostRegAlloc passes");
526 // Insert prolog/epilog code. Eliminate abstract frame index references...
527 addPass(&PrologEpilogCodeInserterID);
528 printAndVerify("After PrologEpilogCodeInserter");
530 /// Add passes that optimize machine instructions after register allocation.
531 if (getOptLevel() != CodeGenOpt::None)
532 addMachineLateOptimization();
534 // Expand pseudo instructions before second scheduling pass.
535 addPass(&ExpandPostRAPseudosID);
536 printAndVerify("After ExpandPostRAPseudos");
538 // Run pre-sched2 passes.
540 printAndVerify("After PreSched2 passes");
542 // Second pass scheduler.
543 if (getOptLevel() != CodeGenOpt::None) {
545 addPass(&PostMachineSchedulerID);
547 addPass(&PostRASchedulerID);
548 printAndVerify("After PostRAScheduler");
554 addPass(createGCInfoPrinter(dbgs()));
557 // Basic block placement.
558 if (getOptLevel() != CodeGenOpt::None)
561 if (addPreEmitPass())
562 printAndVerify("After PreEmit passes");
564 addPass(&StackMapLivenessID);
567 /// Add passes that optimize machine instructions in SSA form.
568 void TargetPassConfig::addMachineSSAOptimization() {
569 // Pre-ra tail duplication.
570 if (addPass(&EarlyTailDuplicateID))
571 printAndVerify("After Pre-RegAlloc TailDuplicate");
573 // Optimize PHIs before DCE: removing dead PHI cycles may make more
574 // instructions dead.
575 addPass(&OptimizePHIsID);
577 // This pass merges large allocas. StackSlotColoring is a different pass
578 // which merges spill slots.
579 addPass(&StackColoringID);
581 // If the target requests it, assign local variables to stack slots relative
582 // to one another and simplify frame index references where possible.
583 addPass(&LocalStackSlotAllocationID);
585 // With optimization, dead code should already be eliminated. However
586 // there is one known exception: lowered code for arguments that are only
587 // used by tail calls, where the tail calls reuse the incoming stack
588 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
589 addPass(&DeadMachineInstructionElimID);
590 printAndVerify("After codegen DCE pass");
592 // Allow targets to insert passes that improve instruction level parallelism,
593 // like if-conversion. Such passes will typically need dominator trees and
594 // loop info, just like LICM and CSE below.
596 printAndVerify("After ILP optimizations");
598 addPass(&MachineLICMID);
599 addPass(&MachineCSEID);
600 addPass(&MachineSinkingID);
601 printAndVerify("After Machine LICM, CSE and Sinking passes");
603 addPass(&PeepholeOptimizerID);
604 printAndVerify("After codegen peephole optimization pass");
607 //===---------------------------------------------------------------------===//
608 /// Register Allocation Pass Configuration
609 //===---------------------------------------------------------------------===//
611 bool TargetPassConfig::getOptimizeRegAlloc() const {
612 switch (OptimizeRegAlloc) {
613 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
614 case cl::BOU_TRUE: return true;
615 case cl::BOU_FALSE: return false;
617 llvm_unreachable("Invalid optimize-regalloc state");
620 /// RegisterRegAlloc's global Registry tracks allocator registration.
621 MachinePassRegistry RegisterRegAlloc::Registry;
623 /// A dummy default pass factory indicates whether the register allocator is
624 /// overridden on the command line.
625 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
626 static RegisterRegAlloc
627 defaultRegAlloc("default",
628 "pick register allocator based on -O option",
629 useDefaultRegisterAllocator);
631 /// -regalloc=... command line option.
632 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
633 RegisterPassParser<RegisterRegAlloc> >
635 cl::init(&useDefaultRegisterAllocator),
636 cl::desc("Register allocator to use"));
639 /// Instantiate the default register allocator pass for this target for either
640 /// the optimized or unoptimized allocation path. This will be added to the pass
641 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
642 /// in the optimized case.
644 /// A target that uses the standard regalloc pass order for fast or optimized
645 /// allocation may still override this for per-target regalloc
646 /// selection. But -regalloc=... always takes precedence.
647 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
649 return createGreedyRegisterAllocator();
651 return createFastRegisterAllocator();
654 /// Find and instantiate the register allocation pass requested by this target
655 /// at the current optimization level. Different register allocators are
656 /// defined as separate passes because they may require different analysis.
658 /// This helper ensures that the regalloc= option is always available,
659 /// even for targets that override the default allocator.
661 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
662 /// this can be folded into addPass.
663 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
664 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
666 // Initialize the global default.
669 RegisterRegAlloc::setDefault(RegAlloc);
671 if (Ctor != useDefaultRegisterAllocator)
674 // With no -regalloc= override, ask the target for a regalloc pass.
675 return createTargetRegisterAllocator(Optimized);
678 /// Add the minimum set of target-independent passes that are required for
679 /// register allocation. No coalescing or scheduling.
680 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
681 addPass(&PHIEliminationID);
682 addPass(&TwoAddressInstructionPassID);
684 addPass(RegAllocPass);
685 printAndVerify("After Register Allocation");
688 /// Add standard target-independent passes that are tightly coupled with
689 /// optimized register allocation, including coalescing, machine instruction
690 /// scheduling, and register allocation itself.
691 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
692 addPass(&ProcessImplicitDefsID);
694 // LiveVariables currently requires pure SSA form.
696 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
697 // LiveVariables can be removed completely, and LiveIntervals can be directly
698 // computed. (We still either need to regenerate kill flags after regalloc, or
699 // preferably fix the scavenger to not depend on them).
700 addPass(&LiveVariablesID);
702 // Edge splitting is smarter with machine loop info.
703 addPass(&MachineLoopInfoID);
704 addPass(&PHIEliminationID);
706 // Eventually, we want to run LiveIntervals before PHI elimination.
707 if (EarlyLiveIntervals)
708 addPass(&LiveIntervalsID);
710 addPass(&TwoAddressInstructionPassID);
711 addPass(&RegisterCoalescerID);
713 // PreRA instruction scheduling.
714 if (addPass(&MachineSchedulerID))
715 printAndVerify("After Machine Scheduling");
717 // Add the selected register allocation pass.
718 addPass(RegAllocPass);
719 printAndVerify("After Register Allocation, before rewriter");
721 // Allow targets to change the register assignments before rewriting.
723 printAndVerify("After pre-rewrite passes");
725 // Finally rewrite virtual registers.
726 addPass(&VirtRegRewriterID);
727 printAndVerify("After Virtual Register Rewriter");
729 // Perform stack slot coloring and post-ra machine LICM.
731 // FIXME: Re-enable coloring with register when it's capable of adding
733 addPass(&StackSlotColoringID);
735 // Run post-ra machine LICM to hoist reloads / remats.
737 // FIXME: can this move into MachineLateOptimization?
738 addPass(&PostRAMachineLICMID);
740 printAndVerify("After StackSlotColoring and postra Machine LICM");
743 //===---------------------------------------------------------------------===//
744 /// Post RegAlloc Pass Configuration
745 //===---------------------------------------------------------------------===//
747 /// Add passes that optimize machine instructions after register allocation.
748 void TargetPassConfig::addMachineLateOptimization() {
749 // Branch folding must be run after regalloc and prolog/epilog insertion.
750 if (addPass(&BranchFolderPassID))
751 printAndVerify("After BranchFolding");
754 // Note that duplicating tail just increases code size and degrades
755 // performance for targets that require Structured Control Flow.
756 // In addition it can also make CFG irreducible. Thus we disable it.
757 if (!TM->requiresStructuredCFG() && addPass(&TailDuplicateID))
758 printAndVerify("After TailDuplicate");
761 if (addPass(&MachineCopyPropagationID))
762 printAndVerify("After copy propagation pass");
765 /// Add standard GC passes.
766 bool TargetPassConfig::addGCPasses() {
767 addPass(&GCMachineCodeAnalysisID);
771 /// Add standard basic block placement passes.
772 void TargetPassConfig::addBlockPlacement() {
773 if (addPass(&MachineBlockPlacementID)) {
774 // Run a separate pass to collect block placement statistics.
775 if (EnableBlockPlacementStats)
776 addPass(&MachineBlockPlacementStatsID);
778 printAndVerify("After machine block placement.");