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> OptimizeRegAlloc(
60 "optimize-regalloc", cl::Hidden,
61 cl::desc("Enable optimized register allocation compilation path."));
62 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
64 cl::desc("Disable Machine LICM"));
65 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
66 cl::desc("Disable Machine Sinking"));
67 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
68 cl::desc("Disable Loop Strength Reduction Pass"));
69 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
70 cl::Hidden, cl::desc("Disable ConstantHoisting"));
71 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
72 cl::desc("Disable Codegen Prepare"));
73 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
74 cl::desc("Disable Copy Propagation pass"));
75 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
76 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
77 static cl::opt<bool> EnableImplicitNullChecks(
78 "enable-implicit-null-checks",
79 cl::desc("Fold null checks into faulting memory operations"),
81 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
82 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
83 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
84 cl::desc("Print LLVM IR input to isel pass"));
85 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
86 cl::desc("Dump garbage collector data"));
87 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
88 cl::desc("Verify generated machine code"),
92 static cl::opt<std::string>
93 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
94 cl::desc("Print machine instrs"),
95 cl::value_desc("pass-name"), cl::init("option-unspecified"));
97 // Temporary option to allow experimenting with MachineScheduler as a post-RA
98 // scheduler. Targets can "properly" enable this with
99 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
100 // wouldn't be part of the standard pass pipeline, and the target would just add
101 // a PostRA scheduling pass wherever it wants.
102 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
103 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
105 // Experimental option to run live interval analysis early.
106 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
107 cl::desc("Run live interval analysis earlier in the pipeline"));
109 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
110 cl::init(false), cl::Hidden,
111 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
113 /// Allow standard passes to be disabled by command line options. This supports
114 /// simple binary flags that either suppress the pass or do nothing.
115 /// i.e. -disable-mypass=false has no effect.
116 /// These should be converted to boolOrDefault in order to use applyOverride.
117 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
120 return IdentifyingPassPtr();
124 /// Allow standard passes to be disabled by the command line, regardless of who
125 /// is adding the pass.
127 /// StandardID is the pass identified in the standard pass pipeline and provided
128 /// to addPass(). It may be a target-specific ID in the case that the target
129 /// directly adds its own pass, but in that case we harmlessly fall through.
131 /// TargetID is the pass that the target has configured to override StandardID.
133 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
134 /// pass to run. This allows multiple options to control a single pass depending
135 /// on where in the pipeline that pass is added.
136 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
137 IdentifyingPassPtr TargetID) {
138 if (StandardID == &PostRASchedulerID)
139 return applyDisable(TargetID, DisablePostRA);
141 if (StandardID == &BranchFolderPassID)
142 return applyDisable(TargetID, DisableBranchFold);
144 if (StandardID == &TailDuplicateID)
145 return applyDisable(TargetID, DisableTailDuplicate);
147 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
148 return applyDisable(TargetID, DisableEarlyTailDup);
150 if (StandardID == &MachineBlockPlacementID)
151 return applyDisable(TargetID, DisableBlockPlacement);
153 if (StandardID == &StackSlotColoringID)
154 return applyDisable(TargetID, DisableSSC);
156 if (StandardID == &DeadMachineInstructionElimID)
157 return applyDisable(TargetID, DisableMachineDCE);
159 if (StandardID == &EarlyIfConverterID)
160 return applyDisable(TargetID, DisableEarlyIfConversion);
162 if (StandardID == &MachineLICMID)
163 return applyDisable(TargetID, DisableMachineLICM);
165 if (StandardID == &MachineCSEID)
166 return applyDisable(TargetID, DisableMachineCSE);
168 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
169 return applyDisable(TargetID, DisablePostRAMachineLICM);
171 if (StandardID == &MachineSinkingID)
172 return applyDisable(TargetID, DisableMachineSink);
174 if (StandardID == &MachineCopyPropagationID)
175 return applyDisable(TargetID, DisableCopyProp);
180 //===---------------------------------------------------------------------===//
182 //===---------------------------------------------------------------------===//
184 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
185 "Target Pass Configuration", false, false)
186 char TargetPassConfig::ID = 0;
189 char TargetPassConfig::EarlyTailDuplicateID = 0;
190 char TargetPassConfig::PostRAMachineLICMID = 0;
193 class PassConfigImpl {
195 // List of passes explicitly substituted by this target. Normally this is
196 // empty, but it is a convenient way to suppress or replace specific passes
197 // that are part of a standard pass pipeline without overridding the entire
198 // pipeline. This mechanism allows target options to inherit a standard pass's
199 // user interface. For example, a target may disable a standard pass by
200 // default by substituting a pass ID of zero, and the user may still enable
201 // that standard pass with an explicit command line option.
202 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
204 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
205 /// is inserted after each instance of the first one.
206 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
210 // Out of line virtual method.
211 TargetPassConfig::~TargetPassConfig() {
215 // Out of line constructor provides default values for pass options and
216 // registers all common codegen passes.
217 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
218 : ImmutablePass(ID), PM(&pm), StartBefore(nullptr), StartAfter(nullptr),
219 StopAfter(nullptr), Started(true), Stopped(false),
220 AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
221 DisableVerify(false), EnableTailMerge(true) {
223 Impl = new PassConfigImpl();
225 // Register all target independent codegen passes to activate their PassIDs,
226 // including this pass itself.
227 initializeCodeGen(*PassRegistry::getPassRegistry());
229 // Also register alias analysis passes required by codegen passes.
230 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
231 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
233 // Substitute Pseudo Pass IDs for real ones.
234 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
235 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
238 /// Insert InsertedPassID pass after TargetPassID.
239 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
240 IdentifyingPassPtr InsertedPassID) {
241 assert(((!InsertedPassID.isInstance() &&
242 TargetPassID != InsertedPassID.getID()) ||
243 (InsertedPassID.isInstance() &&
244 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
245 "Insert a pass after itself!");
246 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
247 Impl->InsertedPasses.push_back(P);
250 /// createPassConfig - Create a pass configuration object to be used by
251 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
253 /// Targets may override this to extend TargetPassConfig.
254 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
255 return new TargetPassConfig(this, PM);
258 TargetPassConfig::TargetPassConfig()
259 : ImmutablePass(ID), PM(nullptr) {
260 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
263 // Helper to verify the analysis is really immutable.
264 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
265 assert(!Initialized && "PassConfig is immutable");
269 void TargetPassConfig::substitutePass(AnalysisID StandardID,
270 IdentifyingPassPtr TargetID) {
271 Impl->TargetPasses[StandardID] = TargetID;
274 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
275 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
276 I = Impl->TargetPasses.find(ID);
277 if (I == Impl->TargetPasses.end())
282 /// Add a pass to the PassManager if that pass is supposed to be run. If the
283 /// Started/Stopped flags indicate either that the compilation should start at
284 /// a later pass or that it should stop after an earlier pass, then do not add
285 /// the pass. Finally, compare the current pass against the StartAfter
286 /// and StopAfter options and change the Started/Stopped flags accordingly.
287 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
288 assert(!Initialized && "PassConfig is immutable");
290 // Cache the Pass ID here in case the pass manager finds this pass is
291 // redundant with ones already scheduled / available, and deletes it.
292 // Fundamentally, once we add the pass to the manager, we no longer own it
293 // and shouldn't reference it.
294 AnalysisID PassID = P->getPassID();
296 if (StartBefore == PassID)
298 if (Started && !Stopped) {
300 // Construct banner message before PM->add() as that may delete the pass.
301 if (AddingMachinePasses && (printAfter || verifyAfter))
302 Banner = std::string("After ") + std::string(P->getPassName());
304 if (AddingMachinePasses) {
306 addPrintPass(Banner);
308 addVerifyPass(Banner);
311 // Add the passes after the pass P if there is any.
312 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
313 I = Impl->InsertedPasses.begin(),
314 E = Impl->InsertedPasses.end();
316 if ((*I).first == PassID) {
317 assert((*I).second.isValid() && "Illegal Pass ID!");
319 if ((*I).second.isInstance())
320 NP = (*I).second.getInstance();
322 NP = Pass::createPass((*I).second.getID());
323 assert(NP && "Pass ID not registered");
325 addPass(NP, false, false);
331 if (StopAfter == PassID)
333 if (StartAfter == PassID)
335 if (Stopped && !Started)
336 report_fatal_error("Cannot stop compilation after pass that is not run");
339 /// Add a CodeGen pass at this point in the pipeline after checking for target
340 /// and command line overrides.
342 /// addPass cannot return a pointer to the pass instance because is internal the
343 /// PassManager and the instance we create here may already be freed.
344 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
346 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
347 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
348 if (!FinalPtr.isValid())
352 if (FinalPtr.isInstance())
353 P = FinalPtr.getInstance();
355 P = Pass::createPass(FinalPtr.getID());
357 llvm_unreachable("Pass ID not registered");
359 AnalysisID FinalID = P->getPassID();
360 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
365 void TargetPassConfig::printAndVerify(const std::string &Banner) {
366 addPrintPass(Banner);
367 addVerifyPass(Banner);
370 void TargetPassConfig::addPrintPass(const std::string &Banner) {
371 if (TM->shouldPrintMachineCode())
372 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
375 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
376 if (VerifyMachineCode)
377 PM->add(createMachineVerifierPass(Banner));
380 /// Add common target configurable passes that perform LLVM IR to IR transforms
381 /// following machine independent optimization.
382 void TargetPassConfig::addIRPasses() {
383 // Basic AliasAnalysis support.
384 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
385 // BasicAliasAnalysis wins if they disagree. This is intended to help
386 // support "obvious" type-punning idioms.
388 addPass(createCFLAAWrapperPass());
389 addPass(createTypeBasedAAWrapperPass());
390 addPass(createScopedNoAliasAAWrapperPass());
391 addPass(createBasicAAWrapperPass());
393 // Before running any passes, run the verifier to determine if the input
394 // coming from the front-end and/or optimizer is valid.
396 addPass(createVerifierPass());
398 // Run loop strength reduction before anything else.
399 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
400 addPass(createLoopStrengthReducePass());
402 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
405 // Run GC lowering passes for builtin collectors
406 // TODO: add a pass insertion point here
407 addPass(createGCLoweringPass());
408 addPass(createShadowStackGCLoweringPass());
410 // Make sure that no unreachable blocks are instruction selected.
411 addPass(createUnreachableBlockEliminationPass());
413 // Prepare expensive constants for SelectionDAG.
414 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
415 addPass(createConstantHoistingPass());
417 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
418 addPass(createPartiallyInlineLibCallsPass());
421 /// Turn exception handling constructs into something the code generators can
423 void TargetPassConfig::addPassesToHandleExceptions() {
424 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
425 case ExceptionHandling::SjLj:
426 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
427 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
428 // catch info can get misplaced when a selector ends up more than one block
429 // removed from the parent invoke(s). This could happen when a landing
430 // pad is shared by multiple invokes and is also a target of a normal
431 // edge from elsewhere.
432 addPass(createSjLjEHPreparePass());
434 case ExceptionHandling::DwarfCFI:
435 case ExceptionHandling::ARM:
436 addPass(createDwarfEHPass(TM));
438 case ExceptionHandling::WinEH:
439 // We support using both GCC-style and MSVC-style exceptions on Windows, so
440 // add both preparation passes. Each pass will only actually run if it
441 // recognizes the personality function.
442 addPass(createWinEHPass(TM));
443 addPass(createDwarfEHPass(TM));
445 case ExceptionHandling::None:
446 addPass(createLowerInvokePass());
448 // The lower invoke pass may create unreachable code. Remove it.
449 addPass(createUnreachableBlockEliminationPass());
454 /// Add pass to prepare the LLVM IR for code generation. This should be done
455 /// before exception handling preparation passes.
456 void TargetPassConfig::addCodeGenPrepare() {
457 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
458 addPass(createCodeGenPreparePass(TM));
459 addPass(createRewriteSymbolsPass());
462 /// Add common passes that perform LLVM IR to IR transforms in preparation for
463 /// instruction selection.
464 void TargetPassConfig::addISelPrepare() {
467 // Add both the safe stack and the stack protection passes: each of them will
468 // only protect functions that have corresponding attributes.
469 addPass(createSafeStackPass());
470 addPass(createStackProtectorPass(TM));
473 addPass(createPrintFunctionPass(
474 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
476 // All passes which modify the LLVM IR are now complete; run the verifier
477 // to ensure that the IR is valid.
479 addPass(createVerifierPass());
482 /// Add the complete set of target-independent postISel code generator passes.
484 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
485 /// with nontrivial configuration or multiple passes are broken out below in
486 /// add%Stage routines.
488 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
489 /// addPre/Post methods with empty header implementations allow injecting
490 /// target-specific fixups just before or after major stages. Additionally,
491 /// targets have the flexibility to change pass order within a stage by
492 /// overriding default implementation of add%Stage routines below. Each
493 /// technique has maintainability tradeoffs because alternate pass orders are
494 /// not well supported. addPre/Post works better if the target pass is easily
495 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
496 /// the target should override the stage instead.
498 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
499 /// before/after any target-independent pass. But it's currently overkill.
500 void TargetPassConfig::addMachinePasses() {
501 AddingMachinePasses = true;
503 // Insert a machine instr printer pass after the specified pass.
504 // If -print-machineinstrs specified, print machineinstrs after all passes.
505 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
506 TM->Options.PrintMachineCode = true;
507 else if (!StringRef(PrintMachineInstrs.getValue())
508 .equals("option-unspecified")) {
509 const PassRegistry *PR = PassRegistry::getPassRegistry();
510 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
511 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
512 assert (TPI && IPI && "Pass ID not registered!");
513 const char *TID = (const char *)(TPI->getTypeInfo());
514 const char *IID = (const char *)(IPI->getTypeInfo());
515 insertPass(TID, IID);
518 // Print the instruction selected machine code...
519 printAndVerify("After Instruction Selection");
521 // Expand pseudo-instructions emitted by ISel.
522 addPass(&ExpandISelPseudosID);
524 // Add passes that optimize machine instructions in SSA form.
525 if (getOptLevel() != CodeGenOpt::None) {
526 addMachineSSAOptimization();
528 // If the target requests it, assign local variables to stack slots relative
529 // to one another and simplify frame index references where possible.
530 addPass(&LocalStackSlotAllocationID, false);
533 // Run pre-ra passes.
536 // Run register allocation and passes that are tightly coupled with it,
537 // including phi elimination and scheduling.
538 if (getOptimizeRegAlloc())
539 addOptimizedRegAlloc(createRegAllocPass(true));
541 addFastRegAlloc(createRegAllocPass(false));
543 // Run post-ra passes.
546 // Insert prolog/epilog code. Eliminate abstract frame index references...
547 if (getOptLevel() != CodeGenOpt::None)
548 addPass(&ShrinkWrapID);
550 addPass(&PrologEpilogCodeInserterID);
552 /// Add passes that optimize machine instructions after register allocation.
553 if (getOptLevel() != CodeGenOpt::None)
554 addMachineLateOptimization();
556 // Expand pseudo instructions before second scheduling pass.
557 addPass(&ExpandPostRAPseudosID);
559 // Run pre-sched2 passes.
562 if (EnableImplicitNullChecks)
563 addPass(&ImplicitNullChecksID);
565 // Second pass scheduler.
566 if (getOptLevel() != CodeGenOpt::None) {
568 addPass(&PostMachineSchedulerID);
570 addPass(&PostRASchedulerID);
576 addPass(createGCInfoPrinter(dbgs()), false, false);
579 // Basic block placement.
580 if (getOptLevel() != CodeGenOpt::None)
585 addPass(&StackMapLivenessID, false);
587 AddingMachinePasses = false;
590 /// Add passes that optimize machine instructions in SSA form.
591 void TargetPassConfig::addMachineSSAOptimization() {
592 // Pre-ra tail duplication.
593 addPass(&EarlyTailDuplicateID);
595 // Optimize PHIs before DCE: removing dead PHI cycles may make more
596 // instructions dead.
597 addPass(&OptimizePHIsID, false);
599 // This pass merges large allocas. StackSlotColoring is a different pass
600 // which merges spill slots.
601 addPass(&StackColoringID, false);
603 // If the target requests it, assign local variables to stack slots relative
604 // to one another and simplify frame index references where possible.
605 addPass(&LocalStackSlotAllocationID, false);
607 // With optimization, dead code should already be eliminated. However
608 // there is one known exception: lowered code for arguments that are only
609 // used by tail calls, where the tail calls reuse the incoming stack
610 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
611 addPass(&DeadMachineInstructionElimID);
613 // Allow targets to insert passes that improve instruction level parallelism,
614 // like if-conversion. Such passes will typically need dominator trees and
615 // loop info, just like LICM and CSE below.
618 addPass(&MachineLICMID, false);
619 addPass(&MachineCSEID, false);
620 addPass(&MachineSinkingID);
622 addPass(&PeepholeOptimizerID, false);
623 // Clean-up the dead code that may have been generated by peephole
625 addPass(&DeadMachineInstructionElimID);
628 //===---------------------------------------------------------------------===//
629 /// Register Allocation Pass Configuration
630 //===---------------------------------------------------------------------===//
632 bool TargetPassConfig::getOptimizeRegAlloc() const {
633 switch (OptimizeRegAlloc) {
634 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
635 case cl::BOU_TRUE: return true;
636 case cl::BOU_FALSE: return false;
638 llvm_unreachable("Invalid optimize-regalloc state");
641 /// RegisterRegAlloc's global Registry tracks allocator registration.
642 MachinePassRegistry RegisterRegAlloc::Registry;
644 /// A dummy default pass factory indicates whether the register allocator is
645 /// overridden on the command line.
646 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
647 static RegisterRegAlloc
648 defaultRegAlloc("default",
649 "pick register allocator based on -O option",
650 useDefaultRegisterAllocator);
652 /// -regalloc=... command line option.
653 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
654 RegisterPassParser<RegisterRegAlloc> >
656 cl::init(&useDefaultRegisterAllocator),
657 cl::desc("Register allocator to use"));
660 /// Instantiate the default register allocator pass for this target for either
661 /// the optimized or unoptimized allocation path. This will be added to the pass
662 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
663 /// in the optimized case.
665 /// A target that uses the standard regalloc pass order for fast or optimized
666 /// allocation may still override this for per-target regalloc
667 /// selection. But -regalloc=... always takes precedence.
668 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
670 return createGreedyRegisterAllocator();
672 return createFastRegisterAllocator();
675 /// Find and instantiate the register allocation pass requested by this target
676 /// at the current optimization level. Different register allocators are
677 /// defined as separate passes because they may require different analysis.
679 /// This helper ensures that the regalloc= option is always available,
680 /// even for targets that override the default allocator.
682 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
683 /// this can be folded into addPass.
684 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
685 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
687 // Initialize the global default.
690 RegisterRegAlloc::setDefault(RegAlloc);
692 if (Ctor != useDefaultRegisterAllocator)
695 // With no -regalloc= override, ask the target for a regalloc pass.
696 return createTargetRegisterAllocator(Optimized);
699 /// Return true if the default global register allocator is in use and
700 /// has not be overriden on the command line with '-regalloc=...'
701 bool TargetPassConfig::usingDefaultRegAlloc() const {
702 return RegAlloc.getNumOccurrences() == 0;
705 /// Add the minimum set of target-independent passes that are required for
706 /// register allocation. No coalescing or scheduling.
707 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
708 addPass(&PHIEliminationID, false);
709 addPass(&TwoAddressInstructionPassID, false);
712 addPass(RegAllocPass);
715 /// Add standard target-independent passes that are tightly coupled with
716 /// optimized register allocation, including coalescing, machine instruction
717 /// scheduling, and register allocation itself.
718 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
719 addPass(&ProcessImplicitDefsID, false);
721 // LiveVariables currently requires pure SSA form.
723 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
724 // LiveVariables can be removed completely, and LiveIntervals can be directly
725 // computed. (We still either need to regenerate kill flags after regalloc, or
726 // preferably fix the scavenger to not depend on them).
727 addPass(&LiveVariablesID, false);
729 // Edge splitting is smarter with machine loop info.
730 addPass(&MachineLoopInfoID, false);
731 addPass(&PHIEliminationID, false);
733 // Eventually, we want to run LiveIntervals before PHI elimination.
734 if (EarlyLiveIntervals)
735 addPass(&LiveIntervalsID, false);
737 addPass(&TwoAddressInstructionPassID, false);
738 addPass(&RegisterCoalescerID);
740 // PreRA instruction scheduling.
741 addPass(&MachineSchedulerID);
744 // Add the selected register allocation pass.
745 addPass(RegAllocPass);
747 // Allow targets to change the register assignments before rewriting.
750 // Finally rewrite virtual registers.
751 addPass(&VirtRegRewriterID);
753 // Perform stack slot coloring and post-ra machine LICM.
755 // FIXME: Re-enable coloring with register when it's capable of adding
757 addPass(&StackSlotColoringID);
759 // Run post-ra machine LICM to hoist reloads / remats.
761 // FIXME: can this move into MachineLateOptimization?
762 addPass(&PostRAMachineLICMID);
766 //===---------------------------------------------------------------------===//
767 /// Post RegAlloc Pass Configuration
768 //===---------------------------------------------------------------------===//
770 /// Add passes that optimize machine instructions after register allocation.
771 void TargetPassConfig::addMachineLateOptimization() {
772 // Branch folding must be run after regalloc and prolog/epilog insertion.
773 addPass(&BranchFolderPassID);
776 // Note that duplicating tail just increases code size and degrades
777 // performance for targets that require Structured Control Flow.
778 // In addition it can also make CFG irreducible. Thus we disable it.
779 if (!TM->requiresStructuredCFG())
780 addPass(&TailDuplicateID);
783 addPass(&MachineCopyPropagationID);
786 /// Add standard GC passes.
787 bool TargetPassConfig::addGCPasses() {
788 addPass(&GCMachineCodeAnalysisID, false);
792 /// Add standard basic block placement passes.
793 void TargetPassConfig::addBlockPlacement() {
794 if (addPass(&MachineBlockPlacementID, false)) {
795 // Run a separate pass to collect block placement statistics.
796 if (EnableBlockPlacementStats)
797 addPass(&MachineBlockPlacementStatsID);