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/MachineFunctionPass.h"
18 #include "llvm/CodeGen/RegAllocRegistry.h"
19 #include "llvm/IR/IRPrintingPasses.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Transforms/Utils/SymbolRewriter.h"
32 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
33 cl::desc("Disable Post Regalloc"));
34 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
35 cl::desc("Disable branch folding"));
36 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
37 cl::desc("Disable tail duplication"));
38 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
39 cl::desc("Disable pre-register allocation tail duplication"));
40 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
41 cl::Hidden, cl::desc("Disable probability-driven block placement"));
42 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
43 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
44 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
45 cl::desc("Disable Stack Slot Coloring"));
46 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
47 cl::desc("Disable Machine Dead Code Elimination"));
48 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
49 cl::desc("Disable Early If-conversion"));
50 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
51 cl::desc("Disable Machine LICM"));
52 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
53 cl::desc("Disable Machine Common Subexpression Elimination"));
54 static cl::opt<cl::boolOrDefault>
55 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
56 cl::desc("enable the shrink-wrapping pass"));
57 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
58 "optimize-regalloc", cl::Hidden,
59 cl::desc("Enable optimized register allocation compilation path."));
60 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
62 cl::desc("Disable Machine LICM"));
63 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
64 cl::desc("Disable Machine Sinking"));
65 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
66 cl::desc("Disable Loop Strength Reduction Pass"));
67 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
68 cl::Hidden, cl::desc("Disable ConstantHoisting"));
69 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
70 cl::desc("Disable Codegen Prepare"));
71 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
72 cl::desc("Disable Copy Propagation pass"));
73 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
74 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
75 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
76 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
77 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
78 cl::desc("Print LLVM IR input to isel pass"));
79 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
80 cl::desc("Dump garbage collector data"));
81 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
82 cl::desc("Verify generated machine code"),
86 static cl::opt<std::string>
87 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
88 cl::desc("Print machine instrs"),
89 cl::value_desc("pass-name"), cl::init("option-unspecified"));
91 // Temporary option to allow experimenting with MachineScheduler as a post-RA
92 // scheduler. Targets can "properly" enable this with
93 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
94 // wouldn't be part of the standard pass pipeline, and the target would just add
95 // a PostRA scheduling pass wherever it wants.
96 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
97 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
99 // Experimental option to run live interval analysis early.
100 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
101 cl::desc("Run live interval analysis earlier in the pipeline"));
103 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
104 cl::init(false), cl::Hidden,
105 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
107 /// Allow standard passes to be disabled by command line options. This supports
108 /// simple binary flags that either suppress the pass or do nothing.
109 /// i.e. -disable-mypass=false has no effect.
110 /// These should be converted to boolOrDefault in order to use applyOverride.
111 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
114 return IdentifyingPassPtr();
118 /// Allow standard passes to be disabled by the command line, regardless of who
119 /// is adding the pass.
121 /// StandardID is the pass identified in the standard pass pipeline and provided
122 /// to addPass(). It may be a target-specific ID in the case that the target
123 /// directly adds its own pass, but in that case we harmlessly fall through.
125 /// TargetID is the pass that the target has configured to override StandardID.
127 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
128 /// pass to run. This allows multiple options to control a single pass depending
129 /// on where in the pipeline that pass is added.
130 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
131 IdentifyingPassPtr TargetID) {
132 if (StandardID == &PostRASchedulerID)
133 return applyDisable(TargetID, DisablePostRA);
135 if (StandardID == &BranchFolderPassID)
136 return applyDisable(TargetID, DisableBranchFold);
138 if (StandardID == &TailDuplicateID)
139 return applyDisable(TargetID, DisableTailDuplicate);
141 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
142 return applyDisable(TargetID, DisableEarlyTailDup);
144 if (StandardID == &MachineBlockPlacementID)
145 return applyDisable(TargetID, DisableBlockPlacement);
147 if (StandardID == &StackSlotColoringID)
148 return applyDisable(TargetID, DisableSSC);
150 if (StandardID == &DeadMachineInstructionElimID)
151 return applyDisable(TargetID, DisableMachineDCE);
153 if (StandardID == &EarlyIfConverterID)
154 return applyDisable(TargetID, DisableEarlyIfConversion);
156 if (StandardID == &MachineLICMID)
157 return applyDisable(TargetID, DisableMachineLICM);
159 if (StandardID == &MachineCSEID)
160 return applyDisable(TargetID, DisableMachineCSE);
162 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
163 return applyDisable(TargetID, DisablePostRAMachineLICM);
165 if (StandardID == &MachineSinkingID)
166 return applyDisable(TargetID, DisableMachineSink);
168 if (StandardID == &MachineCopyPropagationID)
169 return applyDisable(TargetID, DisableCopyProp);
174 //===---------------------------------------------------------------------===//
176 //===---------------------------------------------------------------------===//
178 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
179 "Target Pass Configuration", false, false)
180 char TargetPassConfig::ID = 0;
183 char TargetPassConfig::EarlyTailDuplicateID = 0;
184 char TargetPassConfig::PostRAMachineLICMID = 0;
187 class PassConfigImpl {
189 // List of passes explicitly substituted by this target. Normally this is
190 // empty, but it is a convenient way to suppress or replace specific passes
191 // that are part of a standard pass pipeline without overridding the entire
192 // pipeline. This mechanism allows target options to inherit a standard pass's
193 // user interface. For example, a target may disable a standard pass by
194 // default by substituting a pass ID of zero, and the user may still enable
195 // that standard pass with an explicit command line option.
196 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
198 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
199 /// is inserted after each instance of the first one.
200 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
204 // Out of line virtual method.
205 TargetPassConfig::~TargetPassConfig() {
209 // Out of line constructor provides default values for pass options and
210 // registers all common codegen passes.
211 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
212 : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
213 Started(true), Stopped(false), AddingMachinePasses(false), TM(tm),
214 Impl(nullptr), Initialized(false), DisableVerify(false),
215 EnableTailMerge(true), EnableShrinkWrap(false) {
217 Impl = new PassConfigImpl();
219 // Register all target independent codegen passes to activate their PassIDs,
220 // including this pass itself.
221 initializeCodeGen(*PassRegistry::getPassRegistry());
223 // Substitute Pseudo Pass IDs for real ones.
224 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
225 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
228 /// Insert InsertedPassID pass after TargetPassID.
229 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
230 IdentifyingPassPtr InsertedPassID) {
231 assert(((!InsertedPassID.isInstance() &&
232 TargetPassID != InsertedPassID.getID()) ||
233 (InsertedPassID.isInstance() &&
234 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
235 "Insert a pass after itself!");
236 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
237 Impl->InsertedPasses.push_back(P);
240 /// createPassConfig - Create a pass configuration object to be used by
241 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
243 /// Targets may override this to extend TargetPassConfig.
244 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
245 return new TargetPassConfig(this, PM);
248 TargetPassConfig::TargetPassConfig()
249 : ImmutablePass(ID), PM(nullptr) {
250 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
253 // Helper to verify the analysis is really immutable.
254 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
255 assert(!Initialized && "PassConfig is immutable");
259 void TargetPassConfig::substitutePass(AnalysisID StandardID,
260 IdentifyingPassPtr TargetID) {
261 Impl->TargetPasses[StandardID] = TargetID;
264 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
265 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
266 I = Impl->TargetPasses.find(ID);
267 if (I == Impl->TargetPasses.end())
272 /// Add a pass to the PassManager if that pass is supposed to be run. If the
273 /// Started/Stopped flags indicate either that the compilation should start at
274 /// a later pass or that it should stop after an earlier pass, then do not add
275 /// the pass. Finally, compare the current pass against the StartAfter
276 /// and StopAfter options and change the Started/Stopped flags accordingly.
277 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
278 assert(!Initialized && "PassConfig is immutable");
280 // Cache the Pass ID here in case the pass manager finds this pass is
281 // redundant with ones already scheduled / available, and deletes it.
282 // Fundamentally, once we add the pass to the manager, we no longer own it
283 // and shouldn't reference it.
284 AnalysisID PassID = P->getPassID();
286 if (Started && !Stopped) {
288 // Construct banner message before PM->add() as that may delete the pass.
289 if (AddingMachinePasses && (printAfter || verifyAfter))
290 Banner = std::string("After ") + std::string(P->getPassName());
292 if (AddingMachinePasses) {
294 addPrintPass(Banner);
296 addVerifyPass(Banner);
299 // Add the passes after the pass P if there is any.
300 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
301 I = Impl->InsertedPasses.begin(),
302 E = Impl->InsertedPasses.end();
304 if ((*I).first == PassID) {
305 assert((*I).second.isValid() && "Illegal Pass ID!");
307 if ((*I).second.isInstance())
308 NP = (*I).second.getInstance();
310 NP = Pass::createPass((*I).second.getID());
311 assert(NP && "Pass ID not registered");
313 addPass(NP, false, false);
319 if (StopAfter == PassID)
321 if (StartAfter == PassID)
323 if (Stopped && !Started)
324 report_fatal_error("Cannot stop compilation after pass that is not run");
327 /// Add a CodeGen pass at this point in the pipeline after checking for target
328 /// and command line overrides.
330 /// addPass cannot return a pointer to the pass instance because is internal the
331 /// PassManager and the instance we create here may already be freed.
332 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
334 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
335 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
336 if (!FinalPtr.isValid())
340 if (FinalPtr.isInstance())
341 P = FinalPtr.getInstance();
343 P = Pass::createPass(FinalPtr.getID());
345 llvm_unreachable("Pass ID not registered");
347 AnalysisID FinalID = P->getPassID();
348 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
353 void TargetPassConfig::printAndVerify(const std::string &Banner) {
354 addPrintPass(Banner);
355 addVerifyPass(Banner);
358 void TargetPassConfig::addPrintPass(const std::string &Banner) {
359 if (TM->shouldPrintMachineCode())
360 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
363 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
364 if (VerifyMachineCode)
365 PM->add(createMachineVerifierPass(Banner));
368 /// Add common target configurable passes that perform LLVM IR to IR transforms
369 /// following machine independent optimization.
370 void TargetPassConfig::addIRPasses() {
371 // Basic AliasAnalysis support.
372 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
373 // BasicAliasAnalysis wins if they disagree. This is intended to help
374 // support "obvious" type-punning idioms.
376 addPass(createCFLAliasAnalysisPass());
377 addPass(createTypeBasedAliasAnalysisPass());
378 addPass(createScopedNoAliasAAPass());
379 addPass(createBasicAliasAnalysisPass());
381 // Before running any passes, run the verifier to determine if the input
382 // coming from the front-end and/or optimizer is valid.
384 addPass(createVerifierPass());
386 // Run loop strength reduction before anything else.
387 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
388 addPass(createLoopStrengthReducePass());
390 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
393 // Run GC lowering passes for builtin collectors
394 // TODO: add a pass insertion point here
395 addPass(createGCLoweringPass());
396 addPass(createShadowStackGCLoweringPass());
398 // Make sure that no unreachable blocks are instruction selected.
399 addPass(createUnreachableBlockEliminationPass());
401 // Prepare expensive constants for SelectionDAG.
402 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
403 addPass(createConstantHoistingPass());
405 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
406 addPass(createPartiallyInlineLibCallsPass());
409 /// Turn exception handling constructs into something the code generators can
411 void TargetPassConfig::addPassesToHandleExceptions() {
412 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
413 case ExceptionHandling::SjLj:
414 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
415 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
416 // catch info can get misplaced when a selector ends up more than one block
417 // removed from the parent invoke(s). This could happen when a landing
418 // pad is shared by multiple invokes and is also a target of a normal
419 // edge from elsewhere.
420 addPass(createSjLjEHPreparePass(TM));
422 case ExceptionHandling::DwarfCFI:
423 case ExceptionHandling::ARM:
424 addPass(createDwarfEHPass(TM));
426 case ExceptionHandling::WinEH:
427 // We support using both GCC-style and MSVC-style exceptions on Windows, so
428 // add both preparation passes. Each pass will only actually run if it
429 // recognizes the personality function.
430 addPass(createWinEHPass(TM));
431 addPass(createDwarfEHPass(TM));
433 case ExceptionHandling::None:
434 addPass(createLowerInvokePass());
436 // The lower invoke pass may create unreachable code. Remove it.
437 addPass(createUnreachableBlockEliminationPass());
442 /// Add pass to prepare the LLVM IR for code generation. This should be done
443 /// before exception handling preparation passes.
444 void TargetPassConfig::addCodeGenPrepare() {
445 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
446 addPass(createCodeGenPreparePass(TM));
447 addPass(createRewriteSymbolsPass());
450 /// Add common passes that perform LLVM IR to IR transforms in preparation for
451 /// instruction selection.
452 void TargetPassConfig::addISelPrepare() {
455 addPass(createStackProtectorPass(TM));
458 addPass(createPrintFunctionPass(
459 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
461 // All passes which modify the LLVM IR are now complete; run the verifier
462 // to ensure that the IR is valid.
464 addPass(createVerifierPass());
467 /// Add the complete set of target-independent postISel code generator passes.
469 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
470 /// with nontrivial configuration or multiple passes are broken out below in
471 /// add%Stage routines.
473 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
474 /// addPre/Post methods with empty header implementations allow injecting
475 /// target-specific fixups just before or after major stages. Additionally,
476 /// targets have the flexibility to change pass order within a stage by
477 /// overriding default implementation of add%Stage routines below. Each
478 /// technique has maintainability tradeoffs because alternate pass orders are
479 /// not well supported. addPre/Post works better if the target pass is easily
480 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
481 /// the target should override the stage instead.
483 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
484 /// before/after any target-independent pass. But it's currently overkill.
485 void TargetPassConfig::addMachinePasses() {
486 AddingMachinePasses = true;
488 // Insert a machine instr printer pass after the specified pass.
489 // If -print-machineinstrs specified, print machineinstrs after all passes.
490 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
491 TM->Options.PrintMachineCode = true;
492 else if (!StringRef(PrintMachineInstrs.getValue())
493 .equals("option-unspecified")) {
494 const PassRegistry *PR = PassRegistry::getPassRegistry();
495 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
496 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
497 assert (TPI && IPI && "Pass ID not registered!");
498 const char *TID = (const char *)(TPI->getTypeInfo());
499 const char *IID = (const char *)(IPI->getTypeInfo());
500 insertPass(TID, IID);
503 // Print the instruction selected machine code...
504 printAndVerify("After Instruction Selection");
506 // Expand pseudo-instructions emitted by ISel.
507 addPass(&ExpandISelPseudosID);
509 // Add passes that optimize machine instructions in SSA form.
510 if (getOptLevel() != CodeGenOpt::None) {
511 addMachineSSAOptimization();
513 // If the target requests it, assign local variables to stack slots relative
514 // to one another and simplify frame index references where possible.
515 addPass(&LocalStackSlotAllocationID, false);
518 // Run pre-ra passes.
521 // Run register allocation and passes that are tightly coupled with it,
522 // including phi elimination and scheduling.
523 if (getOptimizeRegAlloc())
524 addOptimizedRegAlloc(createRegAllocPass(true));
526 addFastRegAlloc(createRegAllocPass(false));
528 // Run post-ra passes.
531 // Insert prolog/epilog code. Eliminate abstract frame index references...
532 if (getEnableShrinkWrap())
533 addPass(&ShrinkWrapID);
534 addPass(&PrologEpilogCodeInserterID);
536 /// Add passes that optimize machine instructions after register allocation.
537 if (getOptLevel() != CodeGenOpt::None)
538 addMachineLateOptimization();
540 // Expand pseudo instructions before second scheduling pass.
541 addPass(&ExpandPostRAPseudosID);
543 // Run pre-sched2 passes.
546 // Second pass scheduler.
547 if (getOptLevel() != CodeGenOpt::None) {
549 addPass(&PostMachineSchedulerID);
551 addPass(&PostRASchedulerID);
557 addPass(createGCInfoPrinter(dbgs()), false, false);
560 // Basic block placement.
561 if (getOptLevel() != CodeGenOpt::None)
566 addPass(&StackMapLivenessID, false);
568 AddingMachinePasses = false;
571 /// Add passes that optimize machine instructions in SSA form.
572 void TargetPassConfig::addMachineSSAOptimization() {
573 // Pre-ra tail duplication.
574 addPass(&EarlyTailDuplicateID);
576 // Optimize PHIs before DCE: removing dead PHI cycles may make more
577 // instructions dead.
578 addPass(&OptimizePHIsID, false);
580 // This pass merges large allocas. StackSlotColoring is a different pass
581 // which merges spill slots.
582 addPass(&StackColoringID, false);
584 // If the target requests it, assign local variables to stack slots relative
585 // to one another and simplify frame index references where possible.
586 addPass(&LocalStackSlotAllocationID, false);
588 // With optimization, dead code should already be eliminated. However
589 // there is one known exception: lowered code for arguments that are only
590 // used by tail calls, where the tail calls reuse the incoming stack
591 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
592 addPass(&DeadMachineInstructionElimID);
594 // Allow targets to insert passes that improve instruction level parallelism,
595 // like if-conversion. Such passes will typically need dominator trees and
596 // loop info, just like LICM and CSE below.
599 addPass(&MachineLICMID, false);
600 addPass(&MachineCSEID, false);
601 addPass(&MachineSinkingID);
603 addPass(&PeepholeOptimizerID, false);
604 // Clean-up the dead code that may have been generated by peephole
606 addPass(&DeadMachineInstructionElimID);
609 bool TargetPassConfig::getEnableShrinkWrap() const {
610 switch (EnableShrinkWrapOpt) {
612 return EnableShrinkWrap && getOptLevel() != CodeGenOpt::None;
613 // If EnableShrinkWrap is set, it takes precedence on whatever the
614 // target sets. The rational is that we assume we want to test
615 // something related to shrink-wrapping.
621 llvm_unreachable("Invalid shrink-wrapping state");
624 //===---------------------------------------------------------------------===//
625 /// Register Allocation Pass Configuration
626 //===---------------------------------------------------------------------===//
628 bool TargetPassConfig::getOptimizeRegAlloc() const {
629 switch (OptimizeRegAlloc) {
630 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
631 case cl::BOU_TRUE: return true;
632 case cl::BOU_FALSE: return false;
634 llvm_unreachable("Invalid optimize-regalloc state");
637 /// RegisterRegAlloc's global Registry tracks allocator registration.
638 MachinePassRegistry RegisterRegAlloc::Registry;
640 /// A dummy default pass factory indicates whether the register allocator is
641 /// overridden on the command line.
642 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
643 static RegisterRegAlloc
644 defaultRegAlloc("default",
645 "pick register allocator based on -O option",
646 useDefaultRegisterAllocator);
648 /// -regalloc=... command line option.
649 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
650 RegisterPassParser<RegisterRegAlloc> >
652 cl::init(&useDefaultRegisterAllocator),
653 cl::desc("Register allocator to use"));
656 /// Instantiate the default register allocator pass for this target for either
657 /// the optimized or unoptimized allocation path. This will be added to the pass
658 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
659 /// in the optimized case.
661 /// A target that uses the standard regalloc pass order for fast or optimized
662 /// allocation may still override this for per-target regalloc
663 /// selection. But -regalloc=... always takes precedence.
664 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
666 return createGreedyRegisterAllocator();
668 return createFastRegisterAllocator();
671 /// Find and instantiate the register allocation pass requested by this target
672 /// at the current optimization level. Different register allocators are
673 /// defined as separate passes because they may require different analysis.
675 /// This helper ensures that the regalloc= option is always available,
676 /// even for targets that override the default allocator.
678 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
679 /// this can be folded into addPass.
680 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
681 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
683 // Initialize the global default.
686 RegisterRegAlloc::setDefault(RegAlloc);
688 if (Ctor != useDefaultRegisterAllocator)
691 // With no -regalloc= override, ask the target for a regalloc pass.
692 return createTargetRegisterAllocator(Optimized);
695 /// Return true if the default global register allocator is in use and
696 /// has not be overriden on the command line with '-regalloc=...'
697 bool TargetPassConfig::usingDefaultRegAlloc() const {
698 return RegAlloc.getNumOccurrences() == 0;
701 /// Add the minimum set of target-independent passes that are required for
702 /// register allocation. No coalescing or scheduling.
703 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
704 addPass(&PHIEliminationID, false);
705 addPass(&TwoAddressInstructionPassID, false);
707 addPass(RegAllocPass);
710 /// Add standard target-independent passes that are tightly coupled with
711 /// optimized register allocation, including coalescing, machine instruction
712 /// scheduling, and register allocation itself.
713 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
714 addPass(&ProcessImplicitDefsID, false);
716 // LiveVariables currently requires pure SSA form.
718 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
719 // LiveVariables can be removed completely, and LiveIntervals can be directly
720 // computed. (We still either need to regenerate kill flags after regalloc, or
721 // preferably fix the scavenger to not depend on them).
722 addPass(&LiveVariablesID, false);
724 // Edge splitting is smarter with machine loop info.
725 addPass(&MachineLoopInfoID, false);
726 addPass(&PHIEliminationID, false);
728 // Eventually, we want to run LiveIntervals before PHI elimination.
729 if (EarlyLiveIntervals)
730 addPass(&LiveIntervalsID, false);
732 addPass(&TwoAddressInstructionPassID, false);
733 addPass(&RegisterCoalescerID);
735 // PreRA instruction scheduling.
736 addPass(&MachineSchedulerID);
738 // Add the selected register allocation pass.
739 addPass(RegAllocPass);
741 // Allow targets to change the register assignments before rewriting.
744 // Finally rewrite virtual registers.
745 addPass(&VirtRegRewriterID);
747 // Perform stack slot coloring and post-ra machine LICM.
749 // FIXME: Re-enable coloring with register when it's capable of adding
751 addPass(&StackSlotColoringID);
753 // Run post-ra machine LICM to hoist reloads / remats.
755 // FIXME: can this move into MachineLateOptimization?
756 addPass(&PostRAMachineLICMID);
759 //===---------------------------------------------------------------------===//
760 /// Post RegAlloc Pass Configuration
761 //===---------------------------------------------------------------------===//
763 /// Add passes that optimize machine instructions after register allocation.
764 void TargetPassConfig::addMachineLateOptimization() {
765 // Branch folding must be run after regalloc and prolog/epilog insertion.
766 addPass(&BranchFolderPassID);
769 // Note that duplicating tail just increases code size and degrades
770 // performance for targets that require Structured Control Flow.
771 // In addition it can also make CFG irreducible. Thus we disable it.
772 if (!TM->requiresStructuredCFG())
773 addPass(&TailDuplicateID);
776 addPass(&MachineCopyPropagationID);
779 /// Add standard GC passes.
780 bool TargetPassConfig::addGCPasses() {
781 addPass(&GCMachineCodeAnalysisID, false);
785 /// Add standard basic block placement passes.
786 void TargetPassConfig::addBlockPlacement() {
787 if (addPass(&MachineBlockPlacementID, false)) {
788 // Run a separate pass to collect block placement statistics.
789 if (EnableBlockPlacementStats)
790 addPass(&MachineBlockPlacementStatsID);