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/CFLAliasAnalysis.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/ScopedNoAliasAA.h"
20 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/IR/IRPrintingPasses.h"
24 #include "llvm/IR/LegacyPassManager.h"
25 #include "llvm/IR/Verifier.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Instrumentation.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Transforms/Utils/SymbolRewriter.h"
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 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
61 cl::desc("enable the shrink-wrapping pass"));
62 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
63 "optimize-regalloc", cl::Hidden,
64 cl::desc("Enable optimized register allocation compilation path."));
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> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
79 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
80 static cl::opt<bool> EnableImplicitNullChecks(
81 "enable-implicit-null-checks",
82 cl::desc("Fold null checks into faulting memory operations"),
84 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
85 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
86 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
87 cl::desc("Print LLVM IR input to isel pass"));
88 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
89 cl::desc("Dump garbage collector data"));
90 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
91 cl::desc("Verify generated machine code"),
95 static cl::opt<std::string>
96 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
97 cl::desc("Print machine instrs"),
98 cl::value_desc("pass-name"), cl::init("option-unspecified"));
100 // Temporary option to allow experimenting with MachineScheduler as a post-RA
101 // scheduler. Targets can "properly" enable this with
102 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
103 // wouldn't be part of the standard pass pipeline, and the target would just add
104 // a PostRA scheduling pass wherever it wants.
105 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
106 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
108 // Experimental option to run live interval analysis early.
109 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
110 cl::desc("Run live interval analysis earlier in the pipeline"));
112 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
113 cl::init(false), cl::Hidden,
114 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
116 /// Allow standard passes to be disabled by command line options. This supports
117 /// simple binary flags that either suppress the pass or do nothing.
118 /// i.e. -disable-mypass=false has no effect.
119 /// These should be converted to boolOrDefault in order to use applyOverride.
120 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
123 return IdentifyingPassPtr();
127 /// Allow standard passes to be disabled by the command line, regardless of who
128 /// is adding the pass.
130 /// StandardID is the pass identified in the standard pass pipeline and provided
131 /// to addPass(). It may be a target-specific ID in the case that the target
132 /// directly adds its own pass, but in that case we harmlessly fall through.
134 /// TargetID is the pass that the target has configured to override StandardID.
136 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
137 /// pass to run. This allows multiple options to control a single pass depending
138 /// on where in the pipeline that pass is added.
139 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
140 IdentifyingPassPtr TargetID) {
141 if (StandardID == &PostRASchedulerID)
142 return applyDisable(TargetID, DisablePostRA);
144 if (StandardID == &BranchFolderPassID)
145 return applyDisable(TargetID, DisableBranchFold);
147 if (StandardID == &TailDuplicateID)
148 return applyDisable(TargetID, DisableTailDuplicate);
150 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
151 return applyDisable(TargetID, DisableEarlyTailDup);
153 if (StandardID == &MachineBlockPlacementID)
154 return applyDisable(TargetID, DisableBlockPlacement);
156 if (StandardID == &StackSlotColoringID)
157 return applyDisable(TargetID, DisableSSC);
159 if (StandardID == &DeadMachineInstructionElimID)
160 return applyDisable(TargetID, DisableMachineDCE);
162 if (StandardID == &EarlyIfConverterID)
163 return applyDisable(TargetID, DisableEarlyIfConversion);
165 if (StandardID == &MachineLICMID)
166 return applyDisable(TargetID, DisableMachineLICM);
168 if (StandardID == &MachineCSEID)
169 return applyDisable(TargetID, DisableMachineCSE);
171 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
172 return applyDisable(TargetID, DisablePostRAMachineLICM);
174 if (StandardID == &MachineSinkingID)
175 return applyDisable(TargetID, DisableMachineSink);
177 if (StandardID == &MachineCopyPropagationID)
178 return applyDisable(TargetID, DisableCopyProp);
183 //===---------------------------------------------------------------------===//
185 //===---------------------------------------------------------------------===//
187 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
188 "Target Pass Configuration", false, false)
189 char TargetPassConfig::ID = 0;
192 char TargetPassConfig::EarlyTailDuplicateID = 0;
193 char TargetPassConfig::PostRAMachineLICMID = 0;
196 class PassConfigImpl {
198 // List of passes explicitly substituted by this target. Normally this is
199 // empty, but it is a convenient way to suppress or replace specific passes
200 // that are part of a standard pass pipeline without overridding the entire
201 // pipeline. This mechanism allows target options to inherit a standard pass's
202 // user interface. For example, a target may disable a standard pass by
203 // default by substituting a pass ID of zero, and the user may still enable
204 // that standard pass with an explicit command line option.
205 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
207 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
208 /// is inserted after each instance of the first one.
209 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
213 // Out of line virtual method.
214 TargetPassConfig::~TargetPassConfig() {
218 // Out of line constructor provides default values for pass options and
219 // registers all common codegen passes.
220 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
221 : ImmutablePass(ID), PM(&pm), StartBefore(nullptr), StartAfter(nullptr),
222 StopAfter(nullptr), Started(true), Stopped(false),
223 AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
224 DisableVerify(false), EnableTailMerge(true), EnableShrinkWrap(false) {
226 Impl = new PassConfigImpl();
228 // Register all target independent codegen passes to activate their PassIDs,
229 // including this pass itself.
230 initializeCodeGen(*PassRegistry::getPassRegistry());
232 // Substitute Pseudo Pass IDs for real ones.
233 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
234 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
237 /// Insert InsertedPassID pass after TargetPassID.
238 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
239 IdentifyingPassPtr InsertedPassID) {
240 assert(((!InsertedPassID.isInstance() &&
241 TargetPassID != InsertedPassID.getID()) ||
242 (InsertedPassID.isInstance() &&
243 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
244 "Insert a pass after itself!");
245 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
246 Impl->InsertedPasses.push_back(P);
249 /// createPassConfig - Create a pass configuration object to be used by
250 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
252 /// Targets may override this to extend TargetPassConfig.
253 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
254 return new TargetPassConfig(this, PM);
257 TargetPassConfig::TargetPassConfig()
258 : ImmutablePass(ID), PM(nullptr) {
259 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
262 // Helper to verify the analysis is really immutable.
263 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
264 assert(!Initialized && "PassConfig is immutable");
268 void TargetPassConfig::substitutePass(AnalysisID StandardID,
269 IdentifyingPassPtr TargetID) {
270 Impl->TargetPasses[StandardID] = TargetID;
273 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
274 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
275 I = Impl->TargetPasses.find(ID);
276 if (I == Impl->TargetPasses.end())
281 /// Add a pass to the PassManager if that pass is supposed to be run. If the
282 /// Started/Stopped flags indicate either that the compilation should start at
283 /// a later pass or that it should stop after an earlier pass, then do not add
284 /// the pass. Finally, compare the current pass against the StartAfter
285 /// and StopAfter options and change the Started/Stopped flags accordingly.
286 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
287 assert(!Initialized && "PassConfig is immutable");
289 // Cache the Pass ID here in case the pass manager finds this pass is
290 // redundant with ones already scheduled / available, and deletes it.
291 // Fundamentally, once we add the pass to the manager, we no longer own it
292 // and shouldn't reference it.
293 AnalysisID PassID = P->getPassID();
295 if (StartBefore == PassID)
297 if (Started && !Stopped) {
299 // Construct banner message before PM->add() as that may delete the pass.
300 if (AddingMachinePasses && (printAfter || verifyAfter))
301 Banner = std::string("After ") + std::string(P->getPassName());
303 if (AddingMachinePasses) {
305 addPrintPass(Banner);
307 addVerifyPass(Banner);
310 // Add the passes after the pass P if there is any.
311 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
312 I = Impl->InsertedPasses.begin(),
313 E = Impl->InsertedPasses.end();
315 if ((*I).first == PassID) {
316 assert((*I).second.isValid() && "Illegal Pass ID!");
318 if ((*I).second.isInstance())
319 NP = (*I).second.getInstance();
321 NP = Pass::createPass((*I).second.getID());
322 assert(NP && "Pass ID not registered");
324 addPass(NP, false, false);
330 if (StopAfter == PassID)
332 if (StartAfter == PassID)
334 if (Stopped && !Started)
335 report_fatal_error("Cannot stop compilation after pass that is not run");
338 /// Add a CodeGen pass at this point in the pipeline after checking for target
339 /// and command line overrides.
341 /// addPass cannot return a pointer to the pass instance because is internal the
342 /// PassManager and the instance we create here may already be freed.
343 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
345 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
346 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
347 if (!FinalPtr.isValid())
351 if (FinalPtr.isInstance())
352 P = FinalPtr.getInstance();
354 P = Pass::createPass(FinalPtr.getID());
356 llvm_unreachable("Pass ID not registered");
358 AnalysisID FinalID = P->getPassID();
359 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
364 void TargetPassConfig::printAndVerify(const std::string &Banner) {
365 addPrintPass(Banner);
366 addVerifyPass(Banner);
369 void TargetPassConfig::addPrintPass(const std::string &Banner) {
370 if (TM->shouldPrintMachineCode())
371 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
374 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
375 if (VerifyMachineCode)
376 PM->add(createMachineVerifierPass(Banner));
379 /// Add common target configurable passes that perform LLVM IR to IR transforms
380 /// following machine independent optimization.
381 void TargetPassConfig::addIRPasses() {
382 // Basic AliasAnalysis support.
383 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
384 // BasicAliasAnalysis wins if they disagree. This is intended to help
385 // support "obvious" type-punning idioms.
387 addPass(createCFLAliasAnalysisPass());
388 addPass(createTypeBasedAliasAnalysisPass());
389 addPass(createScopedNoAliasAAPass());
390 addPass(createBasicAliasAnalysisPass());
392 // Before running any passes, run the verifier to determine if the input
393 // coming from the front-end and/or optimizer is valid.
395 addPass(createVerifierPass());
397 // Run loop strength reduction before anything else.
398 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
399 addPass(createLoopStrengthReducePass());
401 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
404 // Run GC lowering passes for builtin collectors
405 // TODO: add a pass insertion point here
406 addPass(createGCLoweringPass());
407 addPass(createShadowStackGCLoweringPass());
409 // Make sure that no unreachable blocks are instruction selected.
410 addPass(createUnreachableBlockEliminationPass());
412 // Prepare expensive constants for SelectionDAG.
413 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
414 addPass(createConstantHoistingPass());
416 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
417 addPass(createPartiallyInlineLibCallsPass());
420 /// Turn exception handling constructs into something the code generators can
422 void TargetPassConfig::addPassesToHandleExceptions() {
423 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
424 case ExceptionHandling::SjLj:
425 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
426 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
427 // catch info can get misplaced when a selector ends up more than one block
428 // removed from the parent invoke(s). This could happen when a landing
429 // pad is shared by multiple invokes and is also a target of a normal
430 // edge from elsewhere.
431 addPass(createSjLjEHPreparePass());
433 case ExceptionHandling::DwarfCFI:
434 case ExceptionHandling::ARM:
435 addPass(createDwarfEHPass(TM));
437 case ExceptionHandling::WinEH:
438 // We support using both GCC-style and MSVC-style exceptions on Windows, so
439 // add both preparation passes. Each pass will only actually run if it
440 // recognizes the personality function.
441 addPass(createWinEHPass(TM));
442 addPass(createDwarfEHPass(TM));
444 case ExceptionHandling::None:
445 addPass(createLowerInvokePass());
447 // The lower invoke pass may create unreachable code. Remove it.
448 addPass(createUnreachableBlockEliminationPass());
453 /// Add pass to prepare the LLVM IR for code generation. This should be done
454 /// before exception handling preparation passes.
455 void TargetPassConfig::addCodeGenPrepare() {
456 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
457 addPass(createCodeGenPreparePass(TM));
458 addPass(createRewriteSymbolsPass());
461 /// Add common passes that perform LLVM IR to IR transforms in preparation for
462 /// instruction selection.
463 void TargetPassConfig::addISelPrepare() {
466 // Add both the safe stack and the stack protection passes: each of them will
467 // only protect functions that have corresponding attributes.
468 addPass(createSafeStackPass());
469 addPass(createStackProtectorPass(TM));
472 addPass(createPrintFunctionPass(
473 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
475 // All passes which modify the LLVM IR are now complete; run the verifier
476 // to ensure that the IR is valid.
478 addPass(createVerifierPass());
481 /// Add the complete set of target-independent postISel code generator passes.
483 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
484 /// with nontrivial configuration or multiple passes are broken out below in
485 /// add%Stage routines.
487 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
488 /// addPre/Post methods with empty header implementations allow injecting
489 /// target-specific fixups just before or after major stages. Additionally,
490 /// targets have the flexibility to change pass order within a stage by
491 /// overriding default implementation of add%Stage routines below. Each
492 /// technique has maintainability tradeoffs because alternate pass orders are
493 /// not well supported. addPre/Post works better if the target pass is easily
494 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
495 /// the target should override the stage instead.
497 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
498 /// before/after any target-independent pass. But it's currently overkill.
499 void TargetPassConfig::addMachinePasses() {
500 AddingMachinePasses = true;
502 // Insert a machine instr printer pass after the specified pass.
503 // If -print-machineinstrs specified, print machineinstrs after all passes.
504 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
505 TM->Options.PrintMachineCode = true;
506 else if (!StringRef(PrintMachineInstrs.getValue())
507 .equals("option-unspecified")) {
508 const PassRegistry *PR = PassRegistry::getPassRegistry();
509 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
510 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
511 assert (TPI && IPI && "Pass ID not registered!");
512 const char *TID = (const char *)(TPI->getTypeInfo());
513 const char *IID = (const char *)(IPI->getTypeInfo());
514 insertPass(TID, IID);
517 // Print the instruction selected machine code...
518 printAndVerify("After Instruction Selection");
520 // Expand pseudo-instructions emitted by ISel.
521 addPass(&ExpandISelPseudosID);
523 // Add passes that optimize machine instructions in SSA form.
524 if (getOptLevel() != CodeGenOpt::None) {
525 addMachineSSAOptimization();
527 // If the target requests it, assign local variables to stack slots relative
528 // to one another and simplify frame index references where possible.
529 addPass(&LocalStackSlotAllocationID, false);
532 // Run pre-ra passes.
535 // Run register allocation and passes that are tightly coupled with it,
536 // including phi elimination and scheduling.
537 if (getOptimizeRegAlloc())
538 addOptimizedRegAlloc(createRegAllocPass(true));
540 addFastRegAlloc(createRegAllocPass(false));
542 // Run post-ra passes.
545 // Insert prolog/epilog code. Eliminate abstract frame index references...
546 if (getEnableShrinkWrap())
547 addPass(&ShrinkWrapID);
548 addPass(&PrologEpilogCodeInserterID);
550 /// Add passes that optimize machine instructions after register allocation.
551 if (getOptLevel() != CodeGenOpt::None)
552 addMachineLateOptimization();
554 // Expand pseudo instructions before second scheduling pass.
555 addPass(&ExpandPostRAPseudosID);
557 // Run pre-sched2 passes.
560 if (EnableImplicitNullChecks)
561 addPass(&ImplicitNullChecksID);
563 // Second pass scheduler.
564 if (getOptLevel() != CodeGenOpt::None) {
566 addPass(&PostMachineSchedulerID);
568 addPass(&PostRASchedulerID);
574 addPass(createGCInfoPrinter(dbgs()), false, false);
577 // Basic block placement.
578 if (getOptLevel() != CodeGenOpt::None)
583 addPass(&StackMapLivenessID, false);
585 AddingMachinePasses = false;
588 /// Add passes that optimize machine instructions in SSA form.
589 void TargetPassConfig::addMachineSSAOptimization() {
590 // Pre-ra tail duplication.
591 addPass(&EarlyTailDuplicateID);
593 // Optimize PHIs before DCE: removing dead PHI cycles may make more
594 // instructions dead.
595 addPass(&OptimizePHIsID, false);
597 // This pass merges large allocas. StackSlotColoring is a different pass
598 // which merges spill slots.
599 addPass(&StackColoringID, false);
601 // If the target requests it, assign local variables to stack slots relative
602 // to one another and simplify frame index references where possible.
603 addPass(&LocalStackSlotAllocationID, false);
605 // With optimization, dead code should already be eliminated. However
606 // there is one known exception: lowered code for arguments that are only
607 // used by tail calls, where the tail calls reuse the incoming stack
608 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
609 addPass(&DeadMachineInstructionElimID);
611 // Allow targets to insert passes that improve instruction level parallelism,
612 // like if-conversion. Such passes will typically need dominator trees and
613 // loop info, just like LICM and CSE below.
616 addPass(&MachineLICMID, false);
617 addPass(&MachineCSEID, false);
618 addPass(&MachineSinkingID);
620 addPass(&PeepholeOptimizerID, false);
621 // Clean-up the dead code that may have been generated by peephole
623 addPass(&DeadMachineInstructionElimID);
626 bool TargetPassConfig::getEnableShrinkWrap() const {
627 switch (EnableShrinkWrapOpt) {
629 return EnableShrinkWrap && getOptLevel() != CodeGenOpt::None;
630 // If EnableShrinkWrap is set, it takes precedence on whatever the
631 // target sets. The rational is that we assume we want to test
632 // something related to shrink-wrapping.
638 llvm_unreachable("Invalid shrink-wrapping state");
641 //===---------------------------------------------------------------------===//
642 /// Register Allocation Pass Configuration
643 //===---------------------------------------------------------------------===//
645 bool TargetPassConfig::getOptimizeRegAlloc() const {
646 switch (OptimizeRegAlloc) {
647 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
648 case cl::BOU_TRUE: return true;
649 case cl::BOU_FALSE: return false;
651 llvm_unreachable("Invalid optimize-regalloc state");
654 /// RegisterRegAlloc's global Registry tracks allocator registration.
655 MachinePassRegistry RegisterRegAlloc::Registry;
657 /// A dummy default pass factory indicates whether the register allocator is
658 /// overridden on the command line.
659 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
660 static RegisterRegAlloc
661 defaultRegAlloc("default",
662 "pick register allocator based on -O option",
663 useDefaultRegisterAllocator);
665 /// -regalloc=... command line option.
666 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
667 RegisterPassParser<RegisterRegAlloc> >
669 cl::init(&useDefaultRegisterAllocator),
670 cl::desc("Register allocator to use"));
673 /// Instantiate the default register allocator pass for this target for either
674 /// the optimized or unoptimized allocation path. This will be added to the pass
675 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
676 /// in the optimized case.
678 /// A target that uses the standard regalloc pass order for fast or optimized
679 /// allocation may still override this for per-target regalloc
680 /// selection. But -regalloc=... always takes precedence.
681 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
683 return createGreedyRegisterAllocator();
685 return createFastRegisterAllocator();
688 /// Find and instantiate the register allocation pass requested by this target
689 /// at the current optimization level. Different register allocators are
690 /// defined as separate passes because they may require different analysis.
692 /// This helper ensures that the regalloc= option is always available,
693 /// even for targets that override the default allocator.
695 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
696 /// this can be folded into addPass.
697 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
698 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
700 // Initialize the global default.
703 RegisterRegAlloc::setDefault(RegAlloc);
705 if (Ctor != useDefaultRegisterAllocator)
708 // With no -regalloc= override, ask the target for a regalloc pass.
709 return createTargetRegisterAllocator(Optimized);
712 /// Return true if the default global register allocator is in use and
713 /// has not be overriden on the command line with '-regalloc=...'
714 bool TargetPassConfig::usingDefaultRegAlloc() const {
715 return RegAlloc.getNumOccurrences() == 0;
718 /// Add the minimum set of target-independent passes that are required for
719 /// register allocation. No coalescing or scheduling.
720 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
721 addPass(&PHIEliminationID, false);
722 addPass(&TwoAddressInstructionPassID, false);
724 addPass(RegAllocPass);
727 /// Add standard target-independent passes that are tightly coupled with
728 /// optimized register allocation, including coalescing, machine instruction
729 /// scheduling, and register allocation itself.
730 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
731 addPass(&ProcessImplicitDefsID, false);
733 // LiveVariables currently requires pure SSA form.
735 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
736 // LiveVariables can be removed completely, and LiveIntervals can be directly
737 // computed. (We still either need to regenerate kill flags after regalloc, or
738 // preferably fix the scavenger to not depend on them).
739 addPass(&LiveVariablesID, false);
741 // Edge splitting is smarter with machine loop info.
742 addPass(&MachineLoopInfoID, false);
743 addPass(&PHIEliminationID, false);
745 // Eventually, we want to run LiveIntervals before PHI elimination.
746 if (EarlyLiveIntervals)
747 addPass(&LiveIntervalsID, false);
749 addPass(&TwoAddressInstructionPassID, false);
750 addPass(&RegisterCoalescerID);
752 // PreRA instruction scheduling.
753 addPass(&MachineSchedulerID);
755 // Add the selected register allocation pass.
756 addPass(RegAllocPass);
758 // Allow targets to change the register assignments before rewriting.
761 // Finally rewrite virtual registers.
762 addPass(&VirtRegRewriterID);
764 // Perform stack slot coloring and post-ra machine LICM.
766 // FIXME: Re-enable coloring with register when it's capable of adding
768 addPass(&StackSlotColoringID);
770 // Run post-ra machine LICM to hoist reloads / remats.
772 // FIXME: can this move into MachineLateOptimization?
773 addPass(&PostRAMachineLICMID);
776 //===---------------------------------------------------------------------===//
777 /// Post RegAlloc Pass Configuration
778 //===---------------------------------------------------------------------===//
780 /// Add passes that optimize machine instructions after register allocation.
781 void TargetPassConfig::addMachineLateOptimization() {
782 // Branch folding must be run after regalloc and prolog/epilog insertion.
783 addPass(&BranchFolderPassID);
786 // Note that duplicating tail just increases code size and degrades
787 // performance for targets that require Structured Control Flow.
788 // In addition it can also make CFG irreducible. Thus we disable it.
789 if (!TM->requiresStructuredCFG())
790 addPass(&TailDuplicateID);
793 addPass(&MachineCopyPropagationID);
796 /// Add standard GC passes.
797 bool TargetPassConfig::addGCPasses() {
798 addPass(&GCMachineCodeAnalysisID, false);
802 /// Add standard basic block placement passes.
803 void TargetPassConfig::addBlockPlacement() {
804 if (addPass(&MachineBlockPlacementID, false)) {
805 // Run a separate pass to collect block placement statistics.
806 if (EnableBlockPlacementStats)
807 addPass(&MachineBlockPlacementStatsID);