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> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
75 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
76 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
77 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
78 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
79 cl::desc("Print LLVM IR input to isel pass"));
80 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
81 cl::desc("Dump garbage collector data"));
82 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
83 cl::desc("Verify generated machine code"),
84 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=nullptr));
85 static cl::opt<std::string>
86 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
87 cl::desc("Print machine instrs"),
88 cl::value_desc("pass-name"), cl::init("option-unspecified"));
90 // Temporary option to allow experimenting with MachineScheduler as a post-RA
91 // scheduler. Targets can "properly" enable this with
92 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
93 // wouldn't be part of the standard pass pipeline, and the target would just add
94 // a PostRA scheduling pass wherever it wants.
95 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
96 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
98 // Experimental option to run live interval analysis early.
99 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
100 cl::desc("Run live interval analysis earlier in the pipeline"));
102 /// Allow standard passes to be disabled by command line options. This supports
103 /// simple binary flags that either suppress the pass or do nothing.
104 /// i.e. -disable-mypass=false has no effect.
105 /// These should be converted to boolOrDefault in order to use applyOverride.
106 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
109 return IdentifyingPassPtr();
113 /// Allow Pass selection to be overriden by command line options. This supports
114 /// flags with ternary conditions. TargetID is passed through by default. The
115 /// pass is suppressed when the option is false. When the option is true, the
116 /// StandardID is selected if the target provides no default.
117 static IdentifyingPassPtr applyOverride(IdentifyingPassPtr TargetID,
118 cl::boolOrDefault Override,
119 AnalysisID StandardID) {
124 if (TargetID.isValid())
126 if (StandardID == nullptr)
127 report_fatal_error("Target cannot enable pass");
130 return IdentifyingPassPtr();
132 llvm_unreachable("Invalid command line option state");
135 /// Allow standard passes to be disabled by the command line, regardless of who
136 /// is adding the pass.
138 /// StandardID is the pass identified in the standard pass pipeline and provided
139 /// to addPass(). It may be a target-specific ID in the case that the target
140 /// directly adds its own pass, but in that case we harmlessly fall through.
142 /// TargetID is the pass that the target has configured to override StandardID.
144 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
145 /// pass to run. This allows multiple options to control a single pass depending
146 /// on where in the pipeline that pass is added.
147 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
148 IdentifyingPassPtr TargetID) {
149 if (StandardID == &PostRASchedulerID)
150 return applyDisable(TargetID, DisablePostRA);
152 if (StandardID == &BranchFolderPassID)
153 return applyDisable(TargetID, DisableBranchFold);
155 if (StandardID == &TailDuplicateID)
156 return applyDisable(TargetID, DisableTailDuplicate);
158 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
159 return applyDisable(TargetID, DisableEarlyTailDup);
161 if (StandardID == &MachineBlockPlacementID)
162 return applyDisable(TargetID, DisableBlockPlacement);
164 if (StandardID == &StackSlotColoringID)
165 return applyDisable(TargetID, DisableSSC);
167 if (StandardID == &DeadMachineInstructionElimID)
168 return applyDisable(TargetID, DisableMachineDCE);
170 if (StandardID == &EarlyIfConverterID)
171 return applyDisable(TargetID, DisableEarlyIfConversion);
173 if (StandardID == &MachineLICMID)
174 return applyDisable(TargetID, DisableMachineLICM);
176 if (StandardID == &MachineCSEID)
177 return applyDisable(TargetID, DisableMachineCSE);
179 if (StandardID == &MachineSchedulerID)
180 return applyOverride(TargetID, EnableMachineSched, StandardID);
182 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
183 return applyDisable(TargetID, DisablePostRAMachineLICM);
185 if (StandardID == &MachineSinkingID)
186 return applyDisable(TargetID, DisableMachineSink);
188 if (StandardID == &MachineCopyPropagationID)
189 return applyDisable(TargetID, DisableCopyProp);
194 //===---------------------------------------------------------------------===//
196 //===---------------------------------------------------------------------===//
198 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
199 "Target Pass Configuration", false, false)
200 char TargetPassConfig::ID = 0;
203 char TargetPassConfig::EarlyTailDuplicateID = 0;
204 char TargetPassConfig::PostRAMachineLICMID = 0;
207 class PassConfigImpl {
209 // List of passes explicitly substituted by this target. Normally this is
210 // empty, but it is a convenient way to suppress or replace specific passes
211 // that are part of a standard pass pipeline without overridding the entire
212 // pipeline. This mechanism allows target options to inherit a standard pass's
213 // user interface. For example, a target may disable a standard pass by
214 // default by substituting a pass ID of zero, and the user may still enable
215 // that standard pass with an explicit command line option.
216 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
218 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
219 /// is inserted after each instance of the first one.
220 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
224 // Out of line virtual method.
225 TargetPassConfig::~TargetPassConfig() {
229 // Out of line constructor provides default values for pass options and
230 // registers all common codegen passes.
231 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
232 : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
233 Started(true), Stopped(false), TM(tm), Impl(nullptr), Initialized(false),
234 DisableVerify(false),
235 EnableTailMerge(true) {
237 Impl = new PassConfigImpl();
239 // Register all target independent codegen passes to activate their PassIDs,
240 // including this pass itself.
241 initializeCodeGen(*PassRegistry::getPassRegistry());
243 // Substitute Pseudo Pass IDs for real ones.
244 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
245 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
247 // Temporarily disable experimental passes.
248 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
249 if (!ST.useMachineScheduler())
250 disablePass(&MachineSchedulerID);
253 /// Insert InsertedPassID pass after TargetPassID.
254 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
255 IdentifyingPassPtr InsertedPassID) {
256 assert(((!InsertedPassID.isInstance() &&
257 TargetPassID != InsertedPassID.getID()) ||
258 (InsertedPassID.isInstance() &&
259 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
260 "Insert a pass after itself!");
261 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
262 Impl->InsertedPasses.push_back(P);
265 /// createPassConfig - Create a pass configuration object to be used by
266 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
268 /// Targets may override this to extend TargetPassConfig.
269 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
270 return new TargetPassConfig(this, PM);
273 TargetPassConfig::TargetPassConfig()
274 : ImmutablePass(ID), PM(nullptr) {
275 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
278 // Helper to verify the analysis is really immutable.
279 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
280 assert(!Initialized && "PassConfig is immutable");
284 void TargetPassConfig::substitutePass(AnalysisID StandardID,
285 IdentifyingPassPtr TargetID) {
286 Impl->TargetPasses[StandardID] = TargetID;
289 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
290 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
291 I = Impl->TargetPasses.find(ID);
292 if (I == Impl->TargetPasses.end())
297 /// Add a pass to the PassManager if that pass is supposed to be run. If the
298 /// Started/Stopped flags indicate either that the compilation should start at
299 /// a later pass or that it should stop after an earlier pass, then do not add
300 /// the pass. Finally, compare the current pass against the StartAfter
301 /// and StopAfter options and change the Started/Stopped flags accordingly.
302 void TargetPassConfig::addPass(Pass *P) {
303 assert(!Initialized && "PassConfig is immutable");
305 // Cache the Pass ID here in case the pass manager finds this pass is
306 // redundant with ones already scheduled / available, and deletes it.
307 // Fundamentally, once we add the pass to the manager, we no longer own it
308 // and shouldn't reference it.
309 AnalysisID PassID = P->getPassID();
311 if (Started && !Stopped)
315 if (StopAfter == PassID)
317 if (StartAfter == PassID)
319 if (Stopped && !Started)
320 report_fatal_error("Cannot stop compilation after pass that is not run");
323 /// Add a CodeGen pass at this point in the pipeline after checking for target
324 /// and command line overrides.
326 /// addPass cannot return a pointer to the pass instance because is internal the
327 /// PassManager and the instance we create here may already be freed.
328 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
329 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
330 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
331 if (!FinalPtr.isValid())
335 if (FinalPtr.isInstance())
336 P = FinalPtr.getInstance();
338 P = Pass::createPass(FinalPtr.getID());
340 llvm_unreachable("Pass ID not registered");
342 AnalysisID FinalID = P->getPassID();
343 addPass(P); // Ends the lifetime of P.
345 // Add the passes after the pass P if there is any.
346 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
347 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
349 if ((*I).first == PassID) {
350 assert((*I).second.isValid() && "Illegal Pass ID!");
352 if ((*I).second.isInstance())
353 NP = (*I).second.getInstance();
355 NP = Pass::createPass((*I).second.getID());
356 assert(NP && "Pass ID not registered");
364 void TargetPassConfig::printAndVerify(const char *Banner) {
365 if (TM->shouldPrintMachineCode())
366 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
368 if (VerifyMachineCode)
369 addPass(createMachineVerifierPass(Banner));
372 /// Add common target configurable passes that perform LLVM IR to IR transforms
373 /// following machine independent optimization.
374 void TargetPassConfig::addIRPasses() {
375 // Basic AliasAnalysis support.
376 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
377 // BasicAliasAnalysis wins if they disagree. This is intended to help
378 // support "obvious" type-punning idioms.
379 addPass(createTypeBasedAliasAnalysisPass());
380 addPass(createScopedNoAliasAAPass());
381 addPass(createBasicAliasAnalysisPass());
383 // Before running any passes, run the verifier to determine if the input
384 // coming from the front-end and/or optimizer is valid.
385 if (!DisableVerify) {
386 addPass(createVerifierPass());
387 addPass(createDebugInfoVerifierPass());
390 // Run loop strength reduction before anything else.
391 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
392 addPass(createLoopStrengthReducePass());
394 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
397 addPass(createGCLoweringPass());
399 // Make sure that no unreachable blocks are instruction selected.
400 addPass(createUnreachableBlockEliminationPass());
402 // Prepare expensive constants for SelectionDAG.
403 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
404 addPass(createConstantHoistingPass());
406 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
407 addPass(createPartiallyInlineLibCallsPass());
410 /// Turn exception handling constructs into something the code generators can
412 void TargetPassConfig::addPassesToHandleExceptions() {
413 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
414 case ExceptionHandling::SjLj:
415 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
416 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
417 // catch info can get misplaced when a selector ends up more than one block
418 // removed from the parent invoke(s). This could happen when a landing
419 // pad is shared by multiple invokes and is also a target of a normal
420 // edge from elsewhere.
421 addPass(createSjLjEHPreparePass(TM));
423 case ExceptionHandling::DwarfCFI:
424 case ExceptionHandling::ARM:
425 case ExceptionHandling::WinEH:
426 addPass(createDwarfEHPass(TM));
428 case ExceptionHandling::None:
429 addPass(createLowerInvokePass());
431 // The lower invoke pass may create unreachable code. Remove it.
432 addPass(createUnreachableBlockEliminationPass());
437 /// Add pass to prepare the LLVM IR for code generation. This should be done
438 /// before exception handling preparation passes.
439 void TargetPassConfig::addCodeGenPrepare() {
440 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
441 addPass(createCodeGenPreparePass(TM));
444 /// Add common passes that perform LLVM IR to IR transforms in preparation for
445 /// instruction selection.
446 void TargetPassConfig::addISelPrepare() {
449 // Need to verify DebugInfo *before* creating the stack protector analysis.
450 // It's a function pass, and verifying between it and its users causes a
453 addPass(createDebugInfoVerifierPass());
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 // Insert a machine instr printer pass after the specified pass.
487 // If -print-machineinstrs specified, print machineinstrs after all passes.
488 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
489 TM->Options.PrintMachineCode = true;
490 else if (!StringRef(PrintMachineInstrs.getValue())
491 .equals("option-unspecified")) {
492 const PassRegistry *PR = PassRegistry::getPassRegistry();
493 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
494 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
495 assert (TPI && IPI && "Pass ID not registered!");
496 const char *TID = (const char *)(TPI->getTypeInfo());
497 const char *IID = (const char *)(IPI->getTypeInfo());
498 insertPass(TID, IID);
501 // Print the instruction selected machine code...
502 printAndVerify("After Instruction Selection");
504 // Expand pseudo-instructions emitted by ISel.
505 if (addPass(&ExpandISelPseudosID))
506 printAndVerify("After ExpandISelPseudos");
508 // Add passes that optimize machine instructions in SSA form.
509 if (getOptLevel() != CodeGenOpt::None) {
510 addMachineSSAOptimization();
512 // If the target requests it, assign local variables to stack slots relative
513 // to one another and simplify frame index references where possible.
514 addPass(&LocalStackSlotAllocationID);
517 // Run pre-ra passes.
518 if (addPreRegAlloc())
519 printAndVerify("After PreRegAlloc 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.
529 if (addPostRegAlloc())
530 printAndVerify("After PostRegAlloc passes");
532 // Insert prolog/epilog code. Eliminate abstract frame index references...
533 addPass(&PrologEpilogCodeInserterID);
534 printAndVerify("After PrologEpilogCodeInserter");
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);
542 printAndVerify("After ExpandPostRAPseudos");
544 // Run pre-sched2 passes.
546 printAndVerify("After PreSched2 passes");
548 // Second pass scheduler.
549 if (getOptLevel() != CodeGenOpt::None) {
551 addPass(&PostMachineSchedulerID);
553 addPass(&PostRASchedulerID);
554 printAndVerify("After PostRAScheduler");
560 addPass(createGCInfoPrinter(dbgs()));
563 // Basic block placement.
564 if (getOptLevel() != CodeGenOpt::None)
567 if (addPreEmitPass())
568 printAndVerify("After PreEmit passes");
570 addPass(&StackMapLivenessID);
573 /// Add passes that optimize machine instructions in SSA form.
574 void TargetPassConfig::addMachineSSAOptimization() {
575 // Pre-ra tail duplication.
576 if (addPass(&EarlyTailDuplicateID))
577 printAndVerify("After Pre-RegAlloc TailDuplicate");
579 // Optimize PHIs before DCE: removing dead PHI cycles may make more
580 // instructions dead.
581 addPass(&OptimizePHIsID);
583 // This pass merges large allocas. StackSlotColoring is a different pass
584 // which merges spill slots.
585 addPass(&StackColoringID);
587 // If the target requests it, assign local variables to stack slots relative
588 // to one another and simplify frame index references where possible.
589 addPass(&LocalStackSlotAllocationID);
591 // With optimization, dead code should already be eliminated. However
592 // there is one known exception: lowered code for arguments that are only
593 // used by tail calls, where the tail calls reuse the incoming stack
594 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
595 addPass(&DeadMachineInstructionElimID);
596 printAndVerify("After codegen DCE pass");
598 // Allow targets to insert passes that improve instruction level parallelism,
599 // like if-conversion. Such passes will typically need dominator trees and
600 // loop info, just like LICM and CSE below.
602 printAndVerify("After ILP optimizations");
604 addPass(&MachineLICMID);
605 addPass(&MachineCSEID);
606 addPass(&MachineSinkingID);
607 printAndVerify("After Machine LICM, CSE and Sinking passes");
609 addPass(&PeepholeOptimizerID);
610 printAndVerify("After codegen peephole optimization pass");
613 //===---------------------------------------------------------------------===//
614 /// Register Allocation Pass Configuration
615 //===---------------------------------------------------------------------===//
617 bool TargetPassConfig::getOptimizeRegAlloc() const {
618 switch (OptimizeRegAlloc) {
619 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
620 case cl::BOU_TRUE: return true;
621 case cl::BOU_FALSE: return false;
623 llvm_unreachable("Invalid optimize-regalloc state");
626 /// RegisterRegAlloc's global Registry tracks allocator registration.
627 MachinePassRegistry RegisterRegAlloc::Registry;
629 /// A dummy default pass factory indicates whether the register allocator is
630 /// overridden on the command line.
631 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
632 static RegisterRegAlloc
633 defaultRegAlloc("default",
634 "pick register allocator based on -O option",
635 useDefaultRegisterAllocator);
637 /// -regalloc=... command line option.
638 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
639 RegisterPassParser<RegisterRegAlloc> >
641 cl::init(&useDefaultRegisterAllocator),
642 cl::desc("Register allocator to use"));
645 /// Instantiate the default register allocator pass for this target for either
646 /// the optimized or unoptimized allocation path. This will be added to the pass
647 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
648 /// in the optimized case.
650 /// A target that uses the standard regalloc pass order for fast or optimized
651 /// allocation may still override this for per-target regalloc
652 /// selection. But -regalloc=... always takes precedence.
653 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
655 return createGreedyRegisterAllocator();
657 return createFastRegisterAllocator();
660 /// Find and instantiate the register allocation pass requested by this target
661 /// at the current optimization level. Different register allocators are
662 /// defined as separate passes because they may require different analysis.
664 /// This helper ensures that the regalloc= option is always available,
665 /// even for targets that override the default allocator.
667 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
668 /// this can be folded into addPass.
669 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
670 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
672 // Initialize the global default.
675 RegisterRegAlloc::setDefault(RegAlloc);
677 if (Ctor != useDefaultRegisterAllocator)
680 // With no -regalloc= override, ask the target for a regalloc pass.
681 return createTargetRegisterAllocator(Optimized);
684 /// Add the minimum set of target-independent passes that are required for
685 /// register allocation. No coalescing or scheduling.
686 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
687 addPass(&PHIEliminationID);
688 addPass(&TwoAddressInstructionPassID);
690 addPass(RegAllocPass);
691 printAndVerify("After Register Allocation");
694 /// Add standard target-independent passes that are tightly coupled with
695 /// optimized register allocation, including coalescing, machine instruction
696 /// scheduling, and register allocation itself.
697 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
698 addPass(&ProcessImplicitDefsID);
700 // LiveVariables currently requires pure SSA form.
702 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
703 // LiveVariables can be removed completely, and LiveIntervals can be directly
704 // computed. (We still either need to regenerate kill flags after regalloc, or
705 // preferably fix the scavenger to not depend on them).
706 addPass(&LiveVariablesID);
708 // Edge splitting is smarter with machine loop info.
709 addPass(&MachineLoopInfoID);
710 addPass(&PHIEliminationID);
712 // Eventually, we want to run LiveIntervals before PHI elimination.
713 if (EarlyLiveIntervals)
714 addPass(&LiveIntervalsID);
716 addPass(&TwoAddressInstructionPassID);
717 addPass(&RegisterCoalescerID);
719 // PreRA instruction scheduling.
720 if (addPass(&MachineSchedulerID))
721 printAndVerify("After Machine Scheduling");
723 // Add the selected register allocation pass.
724 addPass(RegAllocPass);
725 printAndVerify("After Register Allocation, before rewriter");
727 // Allow targets to change the register assignments before rewriting.
729 printAndVerify("After pre-rewrite passes");
731 // Finally rewrite virtual registers.
732 addPass(&VirtRegRewriterID);
733 printAndVerify("After Virtual Register Rewriter");
735 // Perform stack slot coloring and post-ra machine LICM.
737 // FIXME: Re-enable coloring with register when it's capable of adding
739 addPass(&StackSlotColoringID);
741 // Run post-ra machine LICM to hoist reloads / remats.
743 // FIXME: can this move into MachineLateOptimization?
744 addPass(&PostRAMachineLICMID);
746 printAndVerify("After StackSlotColoring and postra Machine LICM");
749 //===---------------------------------------------------------------------===//
750 /// Post RegAlloc Pass Configuration
751 //===---------------------------------------------------------------------===//
753 /// Add passes that optimize machine instructions after register allocation.
754 void TargetPassConfig::addMachineLateOptimization() {
755 // Branch folding must be run after regalloc and prolog/epilog insertion.
756 if (addPass(&BranchFolderPassID))
757 printAndVerify("After BranchFolding");
760 // Note that duplicating tail just increases code size and degrades
761 // performance for targets that require Structured Control Flow.
762 // In addition it can also make CFG irreducible. Thus we disable it.
763 if (!TM->requiresStructuredCFG() && addPass(&TailDuplicateID))
764 printAndVerify("After TailDuplicate");
767 if (addPass(&MachineCopyPropagationID))
768 printAndVerify("After copy propagation pass");
771 /// Add standard GC passes.
772 bool TargetPassConfig::addGCPasses() {
773 addPass(&GCMachineCodeAnalysisID);
777 /// Add standard basic block placement passes.
778 void TargetPassConfig::addBlockPlacement() {
779 if (addPass(&MachineBlockPlacementID)) {
780 // Run a separate pass to collect block placement statistics.
781 if (EnableBlockPlacementStats)
782 addPass(&MachineBlockPlacementStatsID);
784 printAndVerify("After machine block placement.");