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/BasicAliasAnalysis.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/IR/IRPrintingPasses.h"
21 #include "llvm/IR/LegacyPassManager.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Instrumentation.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/SymbolRewriter.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 probability-driven block placement"));
44 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
45 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
46 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
47 cl::desc("Disable Stack Slot Coloring"));
48 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
49 cl::desc("Disable Machine Dead Code Elimination"));
50 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
51 cl::desc("Disable Early If-conversion"));
52 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
53 cl::desc("Disable Machine LICM"));
54 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
55 cl::desc("Disable Machine Common Subexpression Elimination"));
56 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
57 "optimize-regalloc", cl::Hidden,
58 cl::desc("Enable optimized register allocation compilation path."));
59 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
61 cl::desc("Disable Machine LICM"));
62 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
63 cl::desc("Disable Machine Sinking"));
64 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
65 cl::desc("Disable Loop Strength Reduction Pass"));
66 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
67 cl::Hidden, cl::desc("Disable ConstantHoisting"));
68 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
69 cl::desc("Disable Codegen Prepare"));
70 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
71 cl::desc("Disable Copy Propagation pass"));
72 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
73 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
74 static cl::opt<bool> EnableImplicitNullChecks(
75 "enable-implicit-null-checks",
76 cl::desc("Fold null checks into faulting memory operations"),
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"),
89 static cl::opt<std::string>
90 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
91 cl::desc("Print machine instrs"),
92 cl::value_desc("pass-name"), cl::init("option-unspecified"));
94 // Temporary option to allow experimenting with MachineScheduler as a post-RA
95 // scheduler. Targets can "properly" enable this with
96 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
97 // wouldn't be part of the standard pass pipeline, and the target would just add
98 // a PostRA scheduling pass wherever it wants.
99 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
100 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
102 // Experimental option to run live interval analysis early.
103 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
104 cl::desc("Run live interval analysis earlier in the pipeline"));
106 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
107 cl::init(false), cl::Hidden,
108 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
110 /// Allow standard passes to be disabled by command line options. This supports
111 /// simple binary flags that either suppress the pass or do nothing.
112 /// i.e. -disable-mypass=false has no effect.
113 /// These should be converted to boolOrDefault in order to use applyOverride.
114 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
117 return IdentifyingPassPtr();
121 /// Allow standard passes to be disabled by the command line, regardless of who
122 /// is adding the pass.
124 /// StandardID is the pass identified in the standard pass pipeline and provided
125 /// to addPass(). It may be a target-specific ID in the case that the target
126 /// directly adds its own pass, but in that case we harmlessly fall through.
128 /// TargetID is the pass that the target has configured to override StandardID.
130 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
131 /// pass to run. This allows multiple options to control a single pass depending
132 /// on where in the pipeline that pass is added.
133 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
134 IdentifyingPassPtr TargetID) {
135 if (StandardID == &PostRASchedulerID)
136 return applyDisable(TargetID, DisablePostRA);
138 if (StandardID == &BranchFolderPassID)
139 return applyDisable(TargetID, DisableBranchFold);
141 if (StandardID == &TailDuplicateID)
142 return applyDisable(TargetID, DisableTailDuplicate);
144 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
145 return applyDisable(TargetID, DisableEarlyTailDup);
147 if (StandardID == &MachineBlockPlacementID)
148 return applyDisable(TargetID, DisableBlockPlacement);
150 if (StandardID == &StackSlotColoringID)
151 return applyDisable(TargetID, DisableSSC);
153 if (StandardID == &DeadMachineInstructionElimID)
154 return applyDisable(TargetID, DisableMachineDCE);
156 if (StandardID == &EarlyIfConverterID)
157 return applyDisable(TargetID, DisableEarlyIfConversion);
159 if (StandardID == &MachineLICMID)
160 return applyDisable(TargetID, DisableMachineLICM);
162 if (StandardID == &MachineCSEID)
163 return applyDisable(TargetID, DisableMachineCSE);
165 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
166 return applyDisable(TargetID, DisablePostRAMachineLICM);
168 if (StandardID == &MachineSinkingID)
169 return applyDisable(TargetID, DisableMachineSink);
171 if (StandardID == &MachineCopyPropagationID)
172 return applyDisable(TargetID, DisableCopyProp);
177 //===---------------------------------------------------------------------===//
179 //===---------------------------------------------------------------------===//
181 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
182 "Target Pass Configuration", false, false)
183 char TargetPassConfig::ID = 0;
186 char TargetPassConfig::EarlyTailDuplicateID = 0;
187 char TargetPassConfig::PostRAMachineLICMID = 0;
190 class PassConfigImpl {
192 // List of passes explicitly substituted by this target. Normally this is
193 // empty, but it is a convenient way to suppress or replace specific passes
194 // that are part of a standard pass pipeline without overridding the entire
195 // pipeline. This mechanism allows target options to inherit a standard pass's
196 // user interface. For example, a target may disable a standard pass by
197 // default by substituting a pass ID of zero, and the user may still enable
198 // that standard pass with an explicit command line option.
199 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
201 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
202 /// is inserted after each instance of the first one.
203 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
207 // Out of line virtual method.
208 TargetPassConfig::~TargetPassConfig() {
212 // Out of line constructor provides default values for pass options and
213 // registers all common codegen passes.
214 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
215 : ImmutablePass(ID), PM(&pm), StartBefore(nullptr), StartAfter(nullptr),
216 StopAfter(nullptr), Started(true), Stopped(false),
217 AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
218 DisableVerify(false), EnableTailMerge(true) {
220 Impl = new PassConfigImpl();
222 // Register all target independent codegen passes to activate their PassIDs,
223 // including this pass itself.
224 initializeCodeGen(*PassRegistry::getPassRegistry());
226 // Substitute Pseudo Pass IDs for real ones.
227 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
228 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
231 /// Insert InsertedPassID pass after TargetPassID.
232 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
233 IdentifyingPassPtr InsertedPassID) {
234 assert(((!InsertedPassID.isInstance() &&
235 TargetPassID != InsertedPassID.getID()) ||
236 (InsertedPassID.isInstance() &&
237 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
238 "Insert a pass after itself!");
239 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
240 Impl->InsertedPasses.push_back(P);
243 /// createPassConfig - Create a pass configuration object to be used by
244 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
246 /// Targets may override this to extend TargetPassConfig.
247 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
248 return new TargetPassConfig(this, PM);
251 TargetPassConfig::TargetPassConfig()
252 : ImmutablePass(ID), PM(nullptr) {
253 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
256 // Helper to verify the analysis is really immutable.
257 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
258 assert(!Initialized && "PassConfig is immutable");
262 void TargetPassConfig::substitutePass(AnalysisID StandardID,
263 IdentifyingPassPtr TargetID) {
264 Impl->TargetPasses[StandardID] = TargetID;
267 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
268 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
269 I = Impl->TargetPasses.find(ID);
270 if (I == Impl->TargetPasses.end())
275 /// Add a pass to the PassManager if that pass is supposed to be run. If the
276 /// Started/Stopped flags indicate either that the compilation should start at
277 /// a later pass or that it should stop after an earlier pass, then do not add
278 /// the pass. Finally, compare the current pass against the StartAfter
279 /// and StopAfter options and change the Started/Stopped flags accordingly.
280 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
281 assert(!Initialized && "PassConfig is immutable");
283 // Cache the Pass ID here in case the pass manager finds this pass is
284 // redundant with ones already scheduled / available, and deletes it.
285 // Fundamentally, once we add the pass to the manager, we no longer own it
286 // and shouldn't reference it.
287 AnalysisID PassID = P->getPassID();
289 if (StartBefore == PassID)
291 if (Started && !Stopped) {
293 // Construct banner message before PM->add() as that may delete the pass.
294 if (AddingMachinePasses && (printAfter || verifyAfter))
295 Banner = std::string("After ") + std::string(P->getPassName());
297 if (AddingMachinePasses) {
299 addPrintPass(Banner);
301 addVerifyPass(Banner);
304 // Add the passes after the pass P if there is any.
305 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
306 I = Impl->InsertedPasses.begin(),
307 E = Impl->InsertedPasses.end();
309 if ((*I).first == PassID) {
310 assert((*I).second.isValid() && "Illegal Pass ID!");
312 if ((*I).second.isInstance())
313 NP = (*I).second.getInstance();
315 NP = Pass::createPass((*I).second.getID());
316 assert(NP && "Pass ID not registered");
318 addPass(NP, false, false);
324 if (StopAfter == PassID)
326 if (StartAfter == PassID)
328 if (Stopped && !Started)
329 report_fatal_error("Cannot stop compilation after pass that is not run");
332 /// Add a CodeGen pass at this point in the pipeline after checking for target
333 /// and command line overrides.
335 /// addPass cannot return a pointer to the pass instance because is internal the
336 /// PassManager and the instance we create here may already be freed.
337 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
339 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
340 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
341 if (!FinalPtr.isValid())
345 if (FinalPtr.isInstance())
346 P = FinalPtr.getInstance();
348 P = Pass::createPass(FinalPtr.getID());
350 llvm_unreachable("Pass ID not registered");
352 AnalysisID FinalID = P->getPassID();
353 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
358 void TargetPassConfig::printAndVerify(const std::string &Banner) {
359 addPrintPass(Banner);
360 addVerifyPass(Banner);
363 void TargetPassConfig::addPrintPass(const std::string &Banner) {
364 if (TM->shouldPrintMachineCode())
365 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
368 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
369 if (VerifyMachineCode)
370 PM->add(createMachineVerifierPass(Banner));
373 /// Add common target configurable passes that perform LLVM IR to IR transforms
374 /// following machine independent optimization.
375 void TargetPassConfig::addIRPasses() {
376 // Basic AliasAnalysis support.
377 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
378 // BasicAliasAnalysis wins if they disagree. This is intended to help
379 // support "obvious" type-punning idioms.
381 addPass(createCFLAliasAnalysisPass());
382 addPass(createTypeBasedAliasAnalysisPass());
383 addPass(createScopedNoAliasAAPass());
384 addPass(createBasicAliasAnalysisPass());
386 // Before running any passes, run the verifier to determine if the input
387 // coming from the front-end and/or optimizer is valid.
389 addPass(createVerifierPass());
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 // Run GC lowering passes for builtin collectors
399 // TODO: add a pass insertion point here
400 addPass(createGCLoweringPass());
401 addPass(createShadowStackGCLoweringPass());
403 // Make sure that no unreachable blocks are instruction selected.
404 addPass(createUnreachableBlockEliminationPass());
406 // Prepare expensive constants for SelectionDAG.
407 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
408 addPass(createConstantHoistingPass());
410 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
411 addPass(createPartiallyInlineLibCallsPass());
414 /// Turn exception handling constructs into something the code generators can
416 void TargetPassConfig::addPassesToHandleExceptions() {
417 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
418 case ExceptionHandling::SjLj:
419 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
420 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
421 // catch info can get misplaced when a selector ends up more than one block
422 // removed from the parent invoke(s). This could happen when a landing
423 // pad is shared by multiple invokes and is also a target of a normal
424 // edge from elsewhere.
425 addPass(createSjLjEHPreparePass());
427 case ExceptionHandling::DwarfCFI:
428 case ExceptionHandling::ARM:
429 addPass(createDwarfEHPass(TM));
431 case ExceptionHandling::WinEH:
432 // We support using both GCC-style and MSVC-style exceptions on Windows, so
433 // add both preparation passes. Each pass will only actually run if it
434 // recognizes the personality function.
435 addPass(createWinEHPass(TM));
436 addPass(createDwarfEHPass(TM));
438 case ExceptionHandling::None:
439 addPass(createLowerInvokePass());
441 // The lower invoke pass may create unreachable code. Remove it.
442 addPass(createUnreachableBlockEliminationPass());
447 /// Add pass to prepare the LLVM IR for code generation. This should be done
448 /// before exception handling preparation passes.
449 void TargetPassConfig::addCodeGenPrepare() {
450 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
451 addPass(createCodeGenPreparePass(TM));
452 addPass(createRewriteSymbolsPass());
455 /// Add common passes that perform LLVM IR to IR transforms in preparation for
456 /// instruction selection.
457 void TargetPassConfig::addISelPrepare() {
460 // Add both the safe stack and the stack protection passes: each of them will
461 // only protect functions that have corresponding attributes.
462 addPass(createSafeStackPass());
463 addPass(createStackProtectorPass(TM));
466 addPass(createPrintFunctionPass(
467 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
469 // All passes which modify the LLVM IR are now complete; run the verifier
470 // to ensure that the IR is valid.
472 addPass(createVerifierPass());
475 /// Add the complete set of target-independent postISel code generator passes.
477 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
478 /// with nontrivial configuration or multiple passes are broken out below in
479 /// add%Stage routines.
481 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
482 /// addPre/Post methods with empty header implementations allow injecting
483 /// target-specific fixups just before or after major stages. Additionally,
484 /// targets have the flexibility to change pass order within a stage by
485 /// overriding default implementation of add%Stage routines below. Each
486 /// technique has maintainability tradeoffs because alternate pass orders are
487 /// not well supported. addPre/Post works better if the target pass is easily
488 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
489 /// the target should override the stage instead.
491 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
492 /// before/after any target-independent pass. But it's currently overkill.
493 void TargetPassConfig::addMachinePasses() {
494 AddingMachinePasses = true;
496 // Insert a machine instr printer pass after the specified pass.
497 // If -print-machineinstrs specified, print machineinstrs after all passes.
498 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
499 TM->Options.PrintMachineCode = true;
500 else if (!StringRef(PrintMachineInstrs.getValue())
501 .equals("option-unspecified")) {
502 const PassRegistry *PR = PassRegistry::getPassRegistry();
503 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
504 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
505 assert (TPI && IPI && "Pass ID not registered!");
506 const char *TID = (const char *)(TPI->getTypeInfo());
507 const char *IID = (const char *)(IPI->getTypeInfo());
508 insertPass(TID, IID);
511 // Print the instruction selected machine code...
512 printAndVerify("After Instruction Selection");
514 // Expand pseudo-instructions emitted by ISel.
515 addPass(&ExpandISelPseudosID);
517 // Add passes that optimize machine instructions in SSA form.
518 if (getOptLevel() != CodeGenOpt::None) {
519 addMachineSSAOptimization();
521 // If the target requests it, assign local variables to stack slots relative
522 // to one another and simplify frame index references where possible.
523 addPass(&LocalStackSlotAllocationID, false);
526 // Run pre-ra passes.
529 // Run register allocation and passes that are tightly coupled with it,
530 // including phi elimination and scheduling.
531 if (getOptimizeRegAlloc())
532 addOptimizedRegAlloc(createRegAllocPass(true));
534 addFastRegAlloc(createRegAllocPass(false));
536 // Run post-ra passes.
539 // Insert prolog/epilog code. Eliminate abstract frame index references...
540 if (getOptLevel() != CodeGenOpt::None)
541 addPass(createShrinkWrapPass());
542 addPass(&PrologEpilogCodeInserterID);
544 /// Add passes that optimize machine instructions after register allocation.
545 if (getOptLevel() != CodeGenOpt::None)
546 addMachineLateOptimization();
548 // Expand pseudo instructions before second scheduling pass.
549 addPass(&ExpandPostRAPseudosID);
551 // Run pre-sched2 passes.
554 if (EnableImplicitNullChecks)
555 addPass(&ImplicitNullChecksID);
557 // Second pass scheduler.
558 if (getOptLevel() != CodeGenOpt::None) {
560 addPass(&PostMachineSchedulerID);
562 addPass(&PostRASchedulerID);
568 addPass(createGCInfoPrinter(dbgs()), false, false);
571 // Basic block placement.
572 if (getOptLevel() != CodeGenOpt::None)
577 addPass(&StackMapLivenessID, false);
579 AddingMachinePasses = false;
582 /// Add passes that optimize machine instructions in SSA form.
583 void TargetPassConfig::addMachineSSAOptimization() {
584 // Pre-ra tail duplication.
585 addPass(&EarlyTailDuplicateID);
587 // Optimize PHIs before DCE: removing dead PHI cycles may make more
588 // instructions dead.
589 addPass(&OptimizePHIsID, false);
591 // This pass merges large allocas. StackSlotColoring is a different pass
592 // which merges spill slots.
593 addPass(&StackColoringID, false);
595 // If the target requests it, assign local variables to stack slots relative
596 // to one another and simplify frame index references where possible.
597 addPass(&LocalStackSlotAllocationID, false);
599 // With optimization, dead code should already be eliminated. However
600 // there is one known exception: lowered code for arguments that are only
601 // used by tail calls, where the tail calls reuse the incoming stack
602 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
603 addPass(&DeadMachineInstructionElimID);
605 // Allow targets to insert passes that improve instruction level parallelism,
606 // like if-conversion. Such passes will typically need dominator trees and
607 // loop info, just like LICM and CSE below.
610 addPass(&MachineLICMID, false);
611 addPass(&MachineCSEID, false);
612 addPass(&MachineSinkingID);
614 addPass(&PeepholeOptimizerID, false);
615 // Clean-up the dead code that may have been generated by peephole
617 addPass(&DeadMachineInstructionElimID);
620 //===---------------------------------------------------------------------===//
621 /// Register Allocation Pass Configuration
622 //===---------------------------------------------------------------------===//
624 bool TargetPassConfig::getOptimizeRegAlloc() const {
625 switch (OptimizeRegAlloc) {
626 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
627 case cl::BOU_TRUE: return true;
628 case cl::BOU_FALSE: return false;
630 llvm_unreachable("Invalid optimize-regalloc state");
633 /// RegisterRegAlloc's global Registry tracks allocator registration.
634 MachinePassRegistry RegisterRegAlloc::Registry;
636 /// A dummy default pass factory indicates whether the register allocator is
637 /// overridden on the command line.
638 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
639 static RegisterRegAlloc
640 defaultRegAlloc("default",
641 "pick register allocator based on -O option",
642 useDefaultRegisterAllocator);
644 /// -regalloc=... command line option.
645 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
646 RegisterPassParser<RegisterRegAlloc> >
648 cl::init(&useDefaultRegisterAllocator),
649 cl::desc("Register allocator to use"));
652 /// Instantiate the default register allocator pass for this target for either
653 /// the optimized or unoptimized allocation path. This will be added to the pass
654 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
655 /// in the optimized case.
657 /// A target that uses the standard regalloc pass order for fast or optimized
658 /// allocation may still override this for per-target regalloc
659 /// selection. But -regalloc=... always takes precedence.
660 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
662 return createGreedyRegisterAllocator();
664 return createFastRegisterAllocator();
667 /// Find and instantiate the register allocation pass requested by this target
668 /// at the current optimization level. Different register allocators are
669 /// defined as separate passes because they may require different analysis.
671 /// This helper ensures that the regalloc= option is always available,
672 /// even for targets that override the default allocator.
674 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
675 /// this can be folded into addPass.
676 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
677 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
679 // Initialize the global default.
682 RegisterRegAlloc::setDefault(RegAlloc);
684 if (Ctor != useDefaultRegisterAllocator)
687 // With no -regalloc= override, ask the target for a regalloc pass.
688 return createTargetRegisterAllocator(Optimized);
691 /// Return true if the default global register allocator is in use and
692 /// has not be overriden on the command line with '-regalloc=...'
693 bool TargetPassConfig::usingDefaultRegAlloc() const {
694 return RegAlloc.getNumOccurrences() == 0;
697 /// Add the minimum set of target-independent passes that are required for
698 /// register allocation. No coalescing or scheduling.
699 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
700 addPass(&PHIEliminationID, false);
701 addPass(&TwoAddressInstructionPassID, false);
703 addPass(RegAllocPass);
706 /// Add standard target-independent passes that are tightly coupled with
707 /// optimized register allocation, including coalescing, machine instruction
708 /// scheduling, and register allocation itself.
709 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
710 addPass(&ProcessImplicitDefsID, false);
712 // LiveVariables currently requires pure SSA form.
714 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
715 // LiveVariables can be removed completely, and LiveIntervals can be directly
716 // computed. (We still either need to regenerate kill flags after regalloc, or
717 // preferably fix the scavenger to not depend on them).
718 addPass(&LiveVariablesID, false);
720 // Edge splitting is smarter with machine loop info.
721 addPass(&MachineLoopInfoID, false);
722 addPass(&PHIEliminationID, false);
724 // Eventually, we want to run LiveIntervals before PHI elimination.
725 if (EarlyLiveIntervals)
726 addPass(&LiveIntervalsID, false);
728 addPass(&TwoAddressInstructionPassID, false);
729 addPass(&RegisterCoalescerID);
731 // PreRA instruction scheduling.
732 addPass(&MachineSchedulerID);
734 // Add the selected register allocation pass.
735 addPass(RegAllocPass);
737 // Allow targets to change the register assignments before rewriting.
740 // Finally rewrite virtual registers.
741 addPass(&VirtRegRewriterID);
743 // Perform stack slot coloring and post-ra machine LICM.
745 // FIXME: Re-enable coloring with register when it's capable of adding
747 addPass(&StackSlotColoringID);
749 // Run post-ra machine LICM to hoist reloads / remats.
751 // FIXME: can this move into MachineLateOptimization?
752 addPass(&PostRAMachineLICMID);
755 //===---------------------------------------------------------------------===//
756 /// Post RegAlloc Pass Configuration
757 //===---------------------------------------------------------------------===//
759 /// Add passes that optimize machine instructions after register allocation.
760 void TargetPassConfig::addMachineLateOptimization() {
761 // Branch folding must be run after regalloc and prolog/epilog insertion.
762 addPass(&BranchFolderPassID);
765 // Note that duplicating tail just increases code size and degrades
766 // performance for targets that require Structured Control Flow.
767 // In addition it can also make CFG irreducible. Thus we disable it.
768 if (!TM->requiresStructuredCFG())
769 addPass(&TailDuplicateID);
772 addPass(&MachineCopyPropagationID);
775 /// Add standard GC passes.
776 bool TargetPassConfig::addGCPasses() {
777 addPass(&GCMachineCodeAnalysisID, false);
781 /// Add standard basic block placement passes.
782 void TargetPassConfig::addBlockPlacement() {
783 if (addPass(&MachineBlockPlacementID, false)) {
784 // Run a separate pass to collect block placement statistics.
785 if (EnableBlockPlacementStats)
786 addPass(&MachineBlockPlacementStatsID);