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"
34 extern cl::opt<bool> EnablePatchPointLiveness;
37 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
38 cl::desc("Disable Post Regalloc"));
39 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
40 cl::desc("Disable branch folding"));
41 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
42 cl::desc("Disable tail duplication"));
43 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
44 cl::desc("Disable pre-register allocation tail duplication"));
45 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
46 cl::Hidden, cl::desc("Disable probability-driven block placement"));
47 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
48 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
49 static cl::opt<bool> 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",
64 cl::desc("Enable the machine instruction scheduling pass."));
65 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
67 cl::desc("Disable Machine LICM"));
68 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
69 cl::desc("Disable Machine Sinking"));
70 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
71 cl::desc("Disable Loop Strength Reduction Pass"));
72 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
73 cl::Hidden, cl::desc("Disable ConstantHoisting"));
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")!=nullptr));
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 // Temporary option to allow experimenting with MachineScheduler as a post-RA
93 // scheduler. Targets can "properly" enable this with
94 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
95 // wouldn't be part of the standard pass pipeline, and the target would just add
96 // a PostRA scheduling pass wherever it wants.
97 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
98 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
100 // Experimental option to run live interval analysis early.
101 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
102 cl::desc("Run live interval analysis earlier in the pipeline"));
104 /// Allow standard passes to be disabled by command line options. This supports
105 /// simple binary flags that either suppress the pass or do nothing.
106 /// i.e. -disable-mypass=false has no effect.
107 /// These should be converted to boolOrDefault in order to use applyOverride.
108 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
111 return IdentifyingPassPtr();
115 /// Allow Pass selection to be overriden by command line options. This supports
116 /// flags with ternary conditions. TargetID is passed through by default. The
117 /// pass is suppressed when the option is false. When the option is true, the
118 /// StandardID is selected if the target provides no default.
119 static IdentifyingPassPtr applyOverride(IdentifyingPassPtr TargetID,
120 cl::boolOrDefault Override,
121 AnalysisID StandardID) {
126 if (TargetID.isValid())
128 if (StandardID == nullptr)
129 report_fatal_error("Target cannot enable pass");
132 return IdentifyingPassPtr();
134 llvm_unreachable("Invalid command line option state");
137 /// Allow standard passes to be disabled by the command line, regardless of who
138 /// is adding the pass.
140 /// StandardID is the pass identified in the standard pass pipeline and provided
141 /// to addPass(). It may be a target-specific ID in the case that the target
142 /// directly adds its own pass, but in that case we harmlessly fall through.
144 /// TargetID is the pass that the target has configured to override StandardID.
146 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
147 /// pass to run. This allows multiple options to control a single pass depending
148 /// on where in the pipeline that pass is added.
149 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
150 IdentifyingPassPtr TargetID) {
151 if (StandardID == &PostRASchedulerID)
152 return applyDisable(TargetID, DisablePostRA);
154 if (StandardID == &BranchFolderPassID)
155 return applyDisable(TargetID, DisableBranchFold);
157 if (StandardID == &TailDuplicateID)
158 return applyDisable(TargetID, DisableTailDuplicate);
160 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
161 return applyDisable(TargetID, DisableEarlyTailDup);
163 if (StandardID == &MachineBlockPlacementID)
164 return applyDisable(TargetID, DisableBlockPlacement);
166 if (StandardID == &StackSlotColoringID)
167 return applyDisable(TargetID, DisableSSC);
169 if (StandardID == &DeadMachineInstructionElimID)
170 return applyDisable(TargetID, DisableMachineDCE);
172 if (StandardID == &EarlyIfConverterID)
173 return applyDisable(TargetID, DisableEarlyIfConversion);
175 if (StandardID == &MachineLICMID)
176 return applyDisable(TargetID, DisableMachineLICM);
178 if (StandardID == &MachineCSEID)
179 return applyDisable(TargetID, DisableMachineCSE);
181 if (StandardID == &MachineSchedulerID)
182 return applyOverride(TargetID, EnableMachineSched, StandardID);
184 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
185 return applyDisable(TargetID, DisablePostRAMachineLICM);
187 if (StandardID == &MachineSinkingID)
188 return applyDisable(TargetID, DisableMachineSink);
190 if (StandardID == &MachineCopyPropagationID)
191 return applyDisable(TargetID, DisableCopyProp);
196 //===---------------------------------------------------------------------===//
198 //===---------------------------------------------------------------------===//
200 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
201 "Target Pass Configuration", false, false)
202 char TargetPassConfig::ID = 0;
205 char TargetPassConfig::EarlyTailDuplicateID = 0;
206 char TargetPassConfig::PostRAMachineLICMID = 0;
209 class PassConfigImpl {
211 // List of passes explicitly substituted by this target. Normally this is
212 // empty, but it is a convenient way to suppress or replace specific passes
213 // that are part of a standard pass pipeline without overridding the entire
214 // pipeline. This mechanism allows target options to inherit a standard pass's
215 // user interface. For example, a target may disable a standard pass by
216 // default by substituting a pass ID of zero, and the user may still enable
217 // that standard pass with an explicit command line option.
218 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
220 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
221 /// is inserted after each instance of the first one.
222 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
226 // Out of line virtual method.
227 TargetPassConfig::~TargetPassConfig() {
231 // Out of line constructor provides default values for pass options and
232 // registers all common codegen passes.
233 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
234 : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
235 Started(true), Stopped(false), TM(tm), Impl(nullptr), Initialized(false),
236 DisableVerify(false),
237 EnableTailMerge(true) {
239 Impl = new PassConfigImpl();
241 // Register all target independent codegen passes to activate their PassIDs,
242 // including this pass itself.
243 initializeCodeGen(*PassRegistry::getPassRegistry());
245 // Substitute Pseudo Pass IDs for real ones.
246 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
247 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
249 // Temporarily disable experimental passes.
250 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
251 if (!ST.useMachineScheduler())
252 disablePass(&MachineSchedulerID);
255 /// Insert InsertedPassID pass after TargetPassID.
256 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
257 IdentifyingPassPtr InsertedPassID) {
258 assert(((!InsertedPassID.isInstance() &&
259 TargetPassID != InsertedPassID.getID()) ||
260 (InsertedPassID.isInstance() &&
261 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
262 "Insert a pass after itself!");
263 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
264 Impl->InsertedPasses.push_back(P);
267 /// createPassConfig - Create a pass configuration object to be used by
268 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
270 /// Targets may override this to extend TargetPassConfig.
271 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
272 return new TargetPassConfig(this, PM);
275 TargetPassConfig::TargetPassConfig()
276 : ImmutablePass(ID), PM(nullptr) {
277 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
280 // Helper to verify the analysis is really immutable.
281 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
282 assert(!Initialized && "PassConfig is immutable");
286 void TargetPassConfig::substitutePass(AnalysisID StandardID,
287 IdentifyingPassPtr TargetID) {
288 Impl->TargetPasses[StandardID] = TargetID;
291 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
292 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
293 I = Impl->TargetPasses.find(ID);
294 if (I == Impl->TargetPasses.end())
299 /// Add a pass to the PassManager if that pass is supposed to be run. If the
300 /// Started/Stopped flags indicate either that the compilation should start at
301 /// a later pass or that it should stop after an earlier pass, then do not add
302 /// the pass. Finally, compare the current pass against the StartAfter
303 /// and StopAfter options and change the Started/Stopped flags accordingly.
304 void TargetPassConfig::addPass(Pass *P) {
305 assert(!Initialized && "PassConfig is immutable");
307 // Cache the Pass ID here in case the pass manager finds this pass is
308 // redundant with ones already scheduled / available, and deletes it.
309 // Fundamentally, once we add the pass to the manager, we no longer own it
310 // and shouldn't reference it.
311 AnalysisID PassID = P->getPassID();
313 if (Started && !Stopped)
317 if (StopAfter == PassID)
319 if (StartAfter == PassID)
321 if (Stopped && !Started)
322 report_fatal_error("Cannot stop compilation after pass that is not run");
325 /// Add a CodeGen pass at this point in the pipeline after checking for target
326 /// and command line overrides.
328 /// addPass cannot return a pointer to the pass instance because is internal the
329 /// PassManager and the instance we create here may already be freed.
330 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
331 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
332 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
333 if (!FinalPtr.isValid())
337 if (FinalPtr.isInstance())
338 P = FinalPtr.getInstance();
340 P = Pass::createPass(FinalPtr.getID());
342 llvm_unreachable("Pass ID not registered");
344 AnalysisID FinalID = P->getPassID();
345 addPass(P); // Ends the lifetime of P.
347 // Add the passes after the pass P if there is any.
348 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
349 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
351 if ((*I).first == PassID) {
352 assert((*I).second.isValid() && "Illegal Pass ID!");
354 if ((*I).second.isInstance())
355 NP = (*I).second.getInstance();
357 NP = Pass::createPass((*I).second.getID());
358 assert(NP && "Pass ID not registered");
366 void TargetPassConfig::printAndVerify(const char *Banner) {
367 if (TM->shouldPrintMachineCode())
368 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
370 if (VerifyMachineCode)
371 addPass(createMachineVerifierPass(Banner));
374 /// Add common target configurable passes that perform LLVM IR to IR transforms
375 /// following machine independent optimization.
376 void TargetPassConfig::addIRPasses() {
377 // Basic AliasAnalysis support.
378 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
379 // BasicAliasAnalysis wins if they disagree. This is intended to help
380 // support "obvious" type-punning idioms.
381 addPass(createTypeBasedAliasAnalysisPass());
382 addPass(createBasicAliasAnalysisPass());
384 // Before running any passes, run the verifier to determine if the input
385 // coming from the front-end and/or optimizer is valid.
386 if (!DisableVerify) {
387 addPass(createVerifierPass());
388 addPass(createDebugInfoVerifierPass());
391 // Run loop strength reduction before anything else.
392 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
393 addPass(createLoopStrengthReducePass());
395 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
398 addPass(createGCLoweringPass());
400 // Make sure that no unreachable blocks are instruction selected.
401 addPass(createUnreachableBlockEliminationPass());
403 // Prepare expensive constants for SelectionDAG.
404 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
405 addPass(createConstantHoistingPass());
408 /// Turn exception handling constructs into something the code generators can
410 void TargetPassConfig::addPassesToHandleExceptions() {
411 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
412 case ExceptionHandling::SjLj:
413 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
414 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
415 // catch info can get misplaced when a selector ends up more than one block
416 // removed from the parent invoke(s). This could happen when a landing
417 // pad is shared by multiple invokes and is also a target of a normal
418 // edge from elsewhere.
419 addPass(createSjLjEHPreparePass(TM));
421 case ExceptionHandling::DwarfCFI:
422 case ExceptionHandling::ARM:
423 case ExceptionHandling::Win64:
424 addPass(createDwarfEHPass(TM));
426 case ExceptionHandling::None:
427 addPass(createLowerInvokePass());
429 // The lower invoke pass may create unreachable code. Remove it.
430 addPass(createUnreachableBlockEliminationPass());
435 /// Add pass to prepare the LLVM IR for code generation. This should be done
436 /// before exception handling preparation passes.
437 void TargetPassConfig::addCodeGenPrepare() {
438 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
439 addPass(createCodeGenPreparePass(TM));
442 /// Add common passes that perform LLVM IR to IR transforms in preparation for
443 /// instruction selection.
444 void TargetPassConfig::addISelPrepare() {
447 // Need to verify DebugInfo *before* creating the stack protector analysis.
448 // It's a function pass, and verifying between it and its users causes a
451 addPass(createDebugInfoVerifierPass());
453 addPass(createStackProtectorPass(TM));
456 addPass(createPrintFunctionPass(
457 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
459 // All passes which modify the LLVM IR are now complete; run the verifier
460 // to ensure that the IR is valid.
462 addPass(createVerifierPass());
465 /// Add the complete set of target-independent postISel code generator passes.
467 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
468 /// with nontrivial configuration or multiple passes are broken out below in
469 /// add%Stage routines.
471 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
472 /// addPre/Post methods with empty header implementations allow injecting
473 /// target-specific fixups just before or after major stages. Additionally,
474 /// targets have the flexibility to change pass order within a stage by
475 /// overriding default implementation of add%Stage routines below. Each
476 /// technique has maintainability tradeoffs because alternate pass orders are
477 /// not well supported. addPre/Post works better if the target pass is easily
478 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
479 /// the target should override the stage instead.
481 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
482 /// before/after any target-independent pass. But it's currently overkill.
483 void TargetPassConfig::addMachinePasses() {
484 // Insert a machine instr printer pass after the specified pass.
485 // If -print-machineinstrs specified, print machineinstrs after all passes.
486 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
487 TM->Options.PrintMachineCode = true;
488 else if (!StringRef(PrintMachineInstrs.getValue())
489 .equals("option-unspecified")) {
490 const PassRegistry *PR = PassRegistry::getPassRegistry();
491 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
492 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
493 assert (TPI && IPI && "Pass ID not registered!");
494 const char *TID = (const char *)(TPI->getTypeInfo());
495 const char *IID = (const char *)(IPI->getTypeInfo());
496 insertPass(TID, IID);
499 // Print the instruction selected machine code...
500 printAndVerify("After Instruction Selection");
502 // Expand pseudo-instructions emitted by ISel.
503 if (addPass(&ExpandISelPseudosID))
504 printAndVerify("After ExpandISelPseudos");
506 // Add passes that optimize machine instructions in SSA form.
507 if (getOptLevel() != CodeGenOpt::None) {
508 addMachineSSAOptimization();
510 // If the target requests it, assign local variables to stack slots relative
511 // to one another and simplify frame index references where possible.
512 addPass(&LocalStackSlotAllocationID);
515 // Run pre-ra passes.
516 if (addPreRegAlloc())
517 printAndVerify("After PreRegAlloc passes");
519 // Run register allocation and passes that are tightly coupled with it,
520 // including phi elimination and scheduling.
521 if (getOptimizeRegAlloc())
522 addOptimizedRegAlloc(createRegAllocPass(true));
524 addFastRegAlloc(createRegAllocPass(false));
526 // Run post-ra passes.
527 if (addPostRegAlloc())
528 printAndVerify("After PostRegAlloc passes");
530 // Insert prolog/epilog code. Eliminate abstract frame index references...
531 addPass(&PrologEpilogCodeInserterID);
532 printAndVerify("After PrologEpilogCodeInserter");
534 /// Add passes that optimize machine instructions after register allocation.
535 if (getOptLevel() != CodeGenOpt::None)
536 addMachineLateOptimization();
538 // Expand pseudo instructions before second scheduling pass.
539 addPass(&ExpandPostRAPseudosID);
540 printAndVerify("After ExpandPostRAPseudos");
542 // Run pre-sched2 passes.
544 printAndVerify("After PreSched2 passes");
546 // Second pass scheduler.
547 if (getOptLevel() != CodeGenOpt::None) {
549 addPass(&PostMachineSchedulerID);
551 addPass(&PostRASchedulerID);
552 printAndVerify("After PostRAScheduler");
558 addPass(createGCInfoPrinter(dbgs()));
561 // Basic block placement.
562 if (getOptLevel() != CodeGenOpt::None)
565 if (addPreEmitPass())
566 printAndVerify("After PreEmit passes");
568 if (EnablePatchPointLiveness)
569 addPass(&StackMapLivenessID);
572 /// Add passes that optimize machine instructions in SSA form.
573 void TargetPassConfig::addMachineSSAOptimization() {
574 // Pre-ra tail duplication.
575 if (addPass(&EarlyTailDuplicateID))
576 printAndVerify("After Pre-RegAlloc TailDuplicate");
578 // Optimize PHIs before DCE: removing dead PHI cycles may make more
579 // instructions dead.
580 addPass(&OptimizePHIsID);
582 // This pass merges large allocas. StackSlotColoring is a different pass
583 // which merges spill slots.
584 addPass(&StackColoringID);
586 // If the target requests it, assign local variables to stack slots relative
587 // to one another and simplify frame index references where possible.
588 addPass(&LocalStackSlotAllocationID);
590 // With optimization, dead code should already be eliminated. However
591 // there is one known exception: lowered code for arguments that are only
592 // used by tail calls, where the tail calls reuse the incoming stack
593 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
594 addPass(&DeadMachineInstructionElimID);
595 printAndVerify("After codegen DCE pass");
597 // Allow targets to insert passes that improve instruction level parallelism,
598 // like if-conversion. Such passes will typically need dominator trees and
599 // loop info, just like LICM and CSE below.
601 printAndVerify("After ILP optimizations");
603 addPass(&MachineLICMID);
604 addPass(&MachineCSEID);
605 addPass(&MachineSinkingID);
606 printAndVerify("After Machine LICM, CSE and Sinking passes");
608 addPass(&PeepholeOptimizerID);
609 printAndVerify("After codegen peephole optimization pass");
612 //===---------------------------------------------------------------------===//
613 /// Register Allocation Pass Configuration
614 //===---------------------------------------------------------------------===//
616 bool TargetPassConfig::getOptimizeRegAlloc() const {
617 switch (OptimizeRegAlloc) {
618 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
619 case cl::BOU_TRUE: return true;
620 case cl::BOU_FALSE: return false;
622 llvm_unreachable("Invalid optimize-regalloc state");
625 /// RegisterRegAlloc's global Registry tracks allocator registration.
626 MachinePassRegistry RegisterRegAlloc::Registry;
628 /// A dummy default pass factory indicates whether the register allocator is
629 /// overridden on the command line.
630 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
631 static RegisterRegAlloc
632 defaultRegAlloc("default",
633 "pick register allocator based on -O option",
634 useDefaultRegisterAllocator);
636 /// -regalloc=... command line option.
637 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
638 RegisterPassParser<RegisterRegAlloc> >
640 cl::init(&useDefaultRegisterAllocator),
641 cl::desc("Register allocator to use"));
644 /// Instantiate the default register allocator pass for this target for either
645 /// the optimized or unoptimized allocation path. This will be added to the pass
646 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
647 /// in the optimized case.
649 /// A target that uses the standard regalloc pass order for fast or optimized
650 /// allocation may still override this for per-target regalloc
651 /// selection. But -regalloc=... always takes precedence.
652 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
654 return createGreedyRegisterAllocator();
656 return createFastRegisterAllocator();
659 /// Find and instantiate the register allocation pass requested by this target
660 /// at the current optimization level. Different register allocators are
661 /// defined as separate passes because they may require different analysis.
663 /// This helper ensures that the regalloc= option is always available,
664 /// even for targets that override the default allocator.
666 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
667 /// this can be folded into addPass.
668 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
669 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
671 // Initialize the global default.
674 RegisterRegAlloc::setDefault(RegAlloc);
676 if (Ctor != useDefaultRegisterAllocator)
679 // With no -regalloc= override, ask the target for a regalloc pass.
680 return createTargetRegisterAllocator(Optimized);
683 /// Add the minimum set of target-independent passes that are required for
684 /// register allocation. No coalescing or scheduling.
685 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
686 addPass(&PHIEliminationID);
687 addPass(&TwoAddressInstructionPassID);
689 addPass(RegAllocPass);
690 printAndVerify("After Register Allocation");
693 /// Add standard target-independent passes that are tightly coupled with
694 /// optimized register allocation, including coalescing, machine instruction
695 /// scheduling, and register allocation itself.
696 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
697 addPass(&ProcessImplicitDefsID);
699 // LiveVariables currently requires pure SSA form.
701 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
702 // LiveVariables can be removed completely, and LiveIntervals can be directly
703 // computed. (We still either need to regenerate kill flags after regalloc, or
704 // preferably fix the scavenger to not depend on them).
705 addPass(&LiveVariablesID);
707 // Edge splitting is smarter with machine loop info.
708 addPass(&MachineLoopInfoID);
709 addPass(&PHIEliminationID);
711 // Eventually, we want to run LiveIntervals before PHI elimination.
712 if (EarlyLiveIntervals)
713 addPass(&LiveIntervalsID);
715 addPass(&TwoAddressInstructionPassID);
716 addPass(&RegisterCoalescerID);
718 // PreRA instruction scheduling.
719 if (addPass(&MachineSchedulerID))
720 printAndVerify("After Machine Scheduling");
722 // Add the selected register allocation pass.
723 addPass(RegAllocPass);
724 printAndVerify("After Register Allocation, before rewriter");
726 // Allow targets to change the register assignments before rewriting.
728 printAndVerify("After pre-rewrite passes");
730 // Finally rewrite virtual registers.
731 addPass(&VirtRegRewriterID);
732 printAndVerify("After Virtual Register Rewriter");
734 // Perform stack slot coloring and post-ra machine LICM.
736 // FIXME: Re-enable coloring with register when it's capable of adding
738 addPass(&StackSlotColoringID);
740 // Run post-ra machine LICM to hoist reloads / remats.
742 // FIXME: can this move into MachineLateOptimization?
743 addPass(&PostRAMachineLICMID);
745 printAndVerify("After StackSlotColoring and postra Machine LICM");
748 //===---------------------------------------------------------------------===//
749 /// Post RegAlloc Pass Configuration
750 //===---------------------------------------------------------------------===//
752 /// Add passes that optimize machine instructions after register allocation.
753 void TargetPassConfig::addMachineLateOptimization() {
754 // Branch folding must be run after regalloc and prolog/epilog insertion.
755 if (addPass(&BranchFolderPassID))
756 printAndVerify("After BranchFolding");
759 // Note that duplicating tail just increases code size and degrades
760 // performance for targets that require Structured Control Flow.
761 // In addition it can also make CFG irreducible. Thus we disable it.
762 if (!TM->requiresStructuredCFG() && addPass(&TailDuplicateID))
763 printAndVerify("After TailDuplicate");
766 if (addPass(&MachineCopyPropagationID))
767 printAndVerify("After copy propagation pass");
770 /// Add standard GC passes.
771 bool TargetPassConfig::addGCPasses() {
772 addPass(&GCMachineCodeAnalysisID);
776 /// Add standard basic block placement passes.
777 void TargetPassConfig::addBlockPlacement() {
778 if (addPass(&MachineBlockPlacementID)) {
779 // Run a separate pass to collect block placement statistics.
780 if (EnableBlockPlacementStats)
781 addPass(&MachineBlockPlacementStatsID);
783 printAndVerify("After machine block placement.");