Stop calling DwarfEHPrepare from WinEHPrepare
[oota-llvm.git] / lib / CodeGen / Passes.cpp
1 //===-- Passes.cpp - Target independent code generation passes ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
12 //
13 //===---------------------------------------------------------------------===//
14
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/Target/TargetLowering.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Transforms/Utils/SymbolRewriter.h"
30
31 using namespace llvm;
32
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<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
59     cl::Hidden,
60     cl::desc("Disable Machine LICM"));
61 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
62     cl::desc("Disable Machine Sinking"));
63 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
64     cl::desc("Disable Loop Strength Reduction Pass"));
65 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
66     cl::Hidden, cl::desc("Disable ConstantHoisting"));
67 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
68     cl::desc("Disable Codegen Prepare"));
69 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
70     cl::desc("Disable Copy Propagation pass"));
71 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
72     cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
73 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
74     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
75 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
76     cl::desc("Print LLVM IR input to isel pass"));
77 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
78     cl::desc("Dump garbage collector data"));
79 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
80     cl::desc("Verify generated machine code"),
81     cl::init(false),
82     cl::ZeroOrMore);
83
84 static cl::opt<std::string>
85 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
86                    cl::desc("Print machine instrs"),
87                    cl::value_desc("pass-name"), cl::init("option-unspecified"));
88
89 // Temporary option to allow experimenting with MachineScheduler as a post-RA
90 // scheduler. Targets can "properly" enable this with
91 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
92 // wouldn't be part of the standard pass pipeline, and the target would just add
93 // a PostRA scheduling pass wherever it wants.
94 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
95   cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
96
97 // Experimental option to run live interval analysis early.
98 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
99     cl::desc("Run live interval analysis earlier in the pipeline"));
100
101 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
102   cl::init(false), cl::Hidden,
103   cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
104
105 /// Allow standard passes to be disabled by command line options. This supports
106 /// simple binary flags that either suppress the pass or do nothing.
107 /// i.e. -disable-mypass=false has no effect.
108 /// These should be converted to boolOrDefault in order to use applyOverride.
109 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
110                                        bool Override) {
111   if (Override)
112     return IdentifyingPassPtr();
113   return PassID;
114 }
115
116 /// Allow standard passes to be disabled by the command line, regardless of who
117 /// is adding the pass.
118 ///
119 /// StandardID is the pass identified in the standard pass pipeline and provided
120 /// to addPass(). It may be a target-specific ID in the case that the target
121 /// directly adds its own pass, but in that case we harmlessly fall through.
122 ///
123 /// TargetID is the pass that the target has configured to override StandardID.
124 ///
125 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
126 /// pass to run. This allows multiple options to control a single pass depending
127 /// on where in the pipeline that pass is added.
128 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
129                                        IdentifyingPassPtr TargetID) {
130   if (StandardID == &PostRASchedulerID)
131     return applyDisable(TargetID, DisablePostRA);
132
133   if (StandardID == &BranchFolderPassID)
134     return applyDisable(TargetID, DisableBranchFold);
135
136   if (StandardID == &TailDuplicateID)
137     return applyDisable(TargetID, DisableTailDuplicate);
138
139   if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
140     return applyDisable(TargetID, DisableEarlyTailDup);
141
142   if (StandardID == &MachineBlockPlacementID)
143     return applyDisable(TargetID, DisableBlockPlacement);
144
145   if (StandardID == &StackSlotColoringID)
146     return applyDisable(TargetID, DisableSSC);
147
148   if (StandardID == &DeadMachineInstructionElimID)
149     return applyDisable(TargetID, DisableMachineDCE);
150
151   if (StandardID == &EarlyIfConverterID)
152     return applyDisable(TargetID, DisableEarlyIfConversion);
153
154   if (StandardID == &MachineLICMID)
155     return applyDisable(TargetID, DisableMachineLICM);
156
157   if (StandardID == &MachineCSEID)
158     return applyDisable(TargetID, DisableMachineCSE);
159
160   if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
161     return applyDisable(TargetID, DisablePostRAMachineLICM);
162
163   if (StandardID == &MachineSinkingID)
164     return applyDisable(TargetID, DisableMachineSink);
165
166   if (StandardID == &MachineCopyPropagationID)
167     return applyDisable(TargetID, DisableCopyProp);
168
169   return TargetID;
170 }
171
172 //===---------------------------------------------------------------------===//
173 /// TargetPassConfig
174 //===---------------------------------------------------------------------===//
175
176 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
177                 "Target Pass Configuration", false, false)
178 char TargetPassConfig::ID = 0;
179
180 // Pseudo Pass IDs.
181 char TargetPassConfig::EarlyTailDuplicateID = 0;
182 char TargetPassConfig::PostRAMachineLICMID = 0;
183
184 namespace llvm {
185 class PassConfigImpl {
186 public:
187   // List of passes explicitly substituted by this target. Normally this is
188   // empty, but it is a convenient way to suppress or replace specific passes
189   // that are part of a standard pass pipeline without overridding the entire
190   // pipeline. This mechanism allows target options to inherit a standard pass's
191   // user interface. For example, a target may disable a standard pass by
192   // default by substituting a pass ID of zero, and the user may still enable
193   // that standard pass with an explicit command line option.
194   DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
195
196   /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
197   /// is inserted after each instance of the first one.
198   SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
199 };
200 } // namespace llvm
201
202 // Out of line virtual method.
203 TargetPassConfig::~TargetPassConfig() {
204   delete Impl;
205 }
206
207 // Out of line constructor provides default values for pass options and
208 // registers all common codegen passes.
209 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
210   : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
211     Started(true), Stopped(false), AddingMachinePasses(false), TM(tm),
212     Impl(nullptr), Initialized(false), DisableVerify(false),
213     EnableTailMerge(true) {
214
215   Impl = new PassConfigImpl();
216
217   // Register all target independent codegen passes to activate their PassIDs,
218   // including this pass itself.
219   initializeCodeGen(*PassRegistry::getPassRegistry());
220
221   // Substitute Pseudo Pass IDs for real ones.
222   substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
223   substitutePass(&PostRAMachineLICMID, &MachineLICMID);
224 }
225
226 /// Insert InsertedPassID pass after TargetPassID.
227 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
228                                   IdentifyingPassPtr InsertedPassID) {
229   assert(((!InsertedPassID.isInstance() &&
230            TargetPassID != InsertedPassID.getID()) ||
231           (InsertedPassID.isInstance() &&
232            TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
233          "Insert a pass after itself!");
234   std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
235   Impl->InsertedPasses.push_back(P);
236 }
237
238 /// createPassConfig - Create a pass configuration object to be used by
239 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
240 ///
241 /// Targets may override this to extend TargetPassConfig.
242 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
243   return new TargetPassConfig(this, PM);
244 }
245
246 TargetPassConfig::TargetPassConfig()
247   : ImmutablePass(ID), PM(nullptr) {
248   llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
249 }
250
251 // Helper to verify the analysis is really immutable.
252 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
253   assert(!Initialized && "PassConfig is immutable");
254   Opt = Val;
255 }
256
257 void TargetPassConfig::substitutePass(AnalysisID StandardID,
258                                       IdentifyingPassPtr TargetID) {
259   Impl->TargetPasses[StandardID] = TargetID;
260 }
261
262 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
263   DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
264     I = Impl->TargetPasses.find(ID);
265   if (I == Impl->TargetPasses.end())
266     return ID;
267   return I->second;
268 }
269
270 /// Add a pass to the PassManager if that pass is supposed to be run.  If the
271 /// Started/Stopped flags indicate either that the compilation should start at
272 /// a later pass or that it should stop after an earlier pass, then do not add
273 /// the pass.  Finally, compare the current pass against the StartAfter
274 /// and StopAfter options and change the Started/Stopped flags accordingly.
275 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
276   assert(!Initialized && "PassConfig is immutable");
277
278   // Cache the Pass ID here in case the pass manager finds this pass is
279   // redundant with ones already scheduled / available, and deletes it.
280   // Fundamentally, once we add the pass to the manager, we no longer own it
281   // and shouldn't reference it.
282   AnalysisID PassID = P->getPassID();
283
284   if (Started && !Stopped) {
285     std::string Banner;
286     // Construct banner message before PM->add() as that may delete the pass.
287     if (AddingMachinePasses && (printAfter || verifyAfter))
288       Banner = std::string("After ") + std::string(P->getPassName());
289     PM->add(P);
290     if (AddingMachinePasses) {
291       if (printAfter)
292         addPrintPass(Banner);
293       if (verifyAfter)
294         addVerifyPass(Banner);
295     }
296   } else {
297     delete P;
298   }
299   if (StopAfter == PassID)
300     Stopped = true;
301   if (StartAfter == PassID)
302     Started = true;
303   if (Stopped && !Started)
304     report_fatal_error("Cannot stop compilation after pass that is not run");
305 }
306
307 /// Add a CodeGen pass at this point in the pipeline after checking for target
308 /// and command line overrides.
309 ///
310 /// addPass cannot return a pointer to the pass instance because is internal the
311 /// PassManager and the instance we create here may already be freed.
312 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
313                                      bool printAfter) {
314   IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
315   IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
316   if (!FinalPtr.isValid())
317     return nullptr;
318
319   Pass *P;
320   if (FinalPtr.isInstance())
321     P = FinalPtr.getInstance();
322   else {
323     P = Pass::createPass(FinalPtr.getID());
324     if (!P)
325       llvm_unreachable("Pass ID not registered");
326   }
327   AnalysisID FinalID = P->getPassID();
328   addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
329
330   // Add the passes after the pass P if there is any.
331   for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
332          I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
333        I != E; ++I) {
334     if ((*I).first == PassID) {
335       assert((*I).second.isValid() && "Illegal Pass ID!");
336       Pass *NP;
337       if ((*I).second.isInstance())
338         NP = (*I).second.getInstance();
339       else {
340         NP = Pass::createPass((*I).second.getID());
341         assert(NP && "Pass ID not registered");
342       }
343       addPass(NP, false, false);
344     }
345   }
346   return FinalID;
347 }
348
349 void TargetPassConfig::printAndVerify(const std::string &Banner) {
350   addPrintPass(Banner);
351   addVerifyPass(Banner);
352 }
353
354 void TargetPassConfig::addPrintPass(const std::string &Banner) {
355   if (TM->shouldPrintMachineCode())
356     PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
357 }
358
359 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
360   if (VerifyMachineCode)
361     PM->add(createMachineVerifierPass(Banner));
362 }
363
364 /// Add common target configurable passes that perform LLVM IR to IR transforms
365 /// following machine independent optimization.
366 void TargetPassConfig::addIRPasses() {
367   // Basic AliasAnalysis support.
368   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
369   // BasicAliasAnalysis wins if they disagree. This is intended to help
370   // support "obvious" type-punning idioms.
371   if (UseCFLAA)
372     addPass(createCFLAliasAnalysisPass());
373   addPass(createTypeBasedAliasAnalysisPass());
374   addPass(createScopedNoAliasAAPass());
375   addPass(createBasicAliasAnalysisPass());
376
377   // Before running any passes, run the verifier to determine if the input
378   // coming from the front-end and/or optimizer is valid.
379   if (!DisableVerify) {
380     addPass(createVerifierPass());
381     addPass(createDebugInfoVerifierPass());
382   }
383
384   // Run loop strength reduction before anything else.
385   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
386     addPass(createLoopStrengthReducePass());
387     if (PrintLSR)
388       addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
389   }
390
391   // Run GC lowering passes for builtin collectors
392   // TODO: add a pass insertion point here
393   addPass(createGCLoweringPass());
394   addPass(createShadowStackGCLoweringPass());
395
396   // Make sure that no unreachable blocks are instruction selected.
397   addPass(createUnreachableBlockEliminationPass());
398
399   // Prepare expensive constants for SelectionDAG.
400   if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
401     addPass(createConstantHoistingPass());
402
403   if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
404     addPass(createPartiallyInlineLibCallsPass());
405 }
406
407 /// Turn exception handling constructs into something the code generators can
408 /// handle.
409 void TargetPassConfig::addPassesToHandleExceptions() {
410   switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
411   case ExceptionHandling::SjLj:
412     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
413     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
414     // catch info can get misplaced when a selector ends up more than one block
415     // removed from the parent invoke(s). This could happen when a landing
416     // pad is shared by multiple invokes and is also a target of a normal
417     // edge from elsewhere.
418     addPass(createSjLjEHPreparePass(TM));
419     // FALLTHROUGH
420   case ExceptionHandling::DwarfCFI:
421   case ExceptionHandling::ARM:
422     addPass(createDwarfEHPass(TM));
423     break;
424   case ExceptionHandling::WinEH:
425     // We support using both GCC-style and MSVC-style exceptions on Windows, so
426     // add both preparation passes. Each pass will only actually run if it
427     // recognizes the personality function.
428     addPass(createWinEHPass(TM));
429     addPass(createDwarfEHPass(TM));
430     break;
431   case ExceptionHandling::None:
432     addPass(createLowerInvokePass());
433
434     // The lower invoke pass may create unreachable code. Remove it.
435     addPass(createUnreachableBlockEliminationPass());
436     break;
437   }
438 }
439
440 /// Add pass to prepare the LLVM IR for code generation. This should be done
441 /// before exception handling preparation passes.
442 void TargetPassConfig::addCodeGenPrepare() {
443   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
444     addPass(createCodeGenPreparePass(TM));
445   addPass(createRewriteSymbolsPass());
446 }
447
448 /// Add common passes that perform LLVM IR to IR transforms in preparation for
449 /// instruction selection.
450 void TargetPassConfig::addISelPrepare() {
451   addPreISel();
452
453   // Need to verify DebugInfo *before* creating the stack protector analysis.
454   // It's a function pass, and verifying between it and its users causes a
455   // crash.
456   if (!DisableVerify)
457     addPass(createDebugInfoVerifierPass());
458
459   addPass(createStackProtectorPass(TM));
460
461   if (PrintISelInput)
462     addPass(createPrintFunctionPass(
463         dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
464
465   // All passes which modify the LLVM IR are now complete; run the verifier
466   // to ensure that the IR is valid.
467   if (!DisableVerify)
468     addPass(createVerifierPass());
469 }
470
471 /// Add the complete set of target-independent postISel code generator passes.
472 ///
473 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
474 /// with nontrivial configuration or multiple passes are broken out below in
475 /// add%Stage routines.
476 ///
477 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
478 /// addPre/Post methods with empty header implementations allow injecting
479 /// target-specific fixups just before or after major stages. Additionally,
480 /// targets have the flexibility to change pass order within a stage by
481 /// overriding default implementation of add%Stage routines below. Each
482 /// technique has maintainability tradeoffs because alternate pass orders are
483 /// not well supported. addPre/Post works better if the target pass is easily
484 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
485 /// the target should override the stage instead.
486 ///
487 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
488 /// before/after any target-independent pass. But it's currently overkill.
489 void TargetPassConfig::addMachinePasses() {
490   AddingMachinePasses = true;
491
492   // Insert a machine instr printer pass after the specified pass.
493   // If -print-machineinstrs specified, print machineinstrs after all passes.
494   if (StringRef(PrintMachineInstrs.getValue()).equals(""))
495     TM->Options.PrintMachineCode = true;
496   else if (!StringRef(PrintMachineInstrs.getValue())
497            .equals("option-unspecified")) {
498     const PassRegistry *PR = PassRegistry::getPassRegistry();
499     const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
500     const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
501     assert (TPI && IPI && "Pass ID not registered!");
502     const char *TID = (const char *)(TPI->getTypeInfo());
503     const char *IID = (const char *)(IPI->getTypeInfo());
504     insertPass(TID, IID);
505   }
506
507   // Print the instruction selected machine code...
508   printAndVerify("After Instruction Selection");
509
510   // Expand pseudo-instructions emitted by ISel.
511   addPass(&ExpandISelPseudosID);
512
513   // Add passes that optimize machine instructions in SSA form.
514   if (getOptLevel() != CodeGenOpt::None) {
515     addMachineSSAOptimization();
516   } else {
517     // If the target requests it, assign local variables to stack slots relative
518     // to one another and simplify frame index references where possible.
519     addPass(&LocalStackSlotAllocationID, false);
520   }
521
522   // Run pre-ra passes.
523   addPreRegAlloc();
524
525   // Run register allocation and passes that are tightly coupled with it,
526   // including phi elimination and scheduling.
527   if (getOptimizeRegAlloc())
528     addOptimizedRegAlloc(createRegAllocPass(true));
529   else
530     addFastRegAlloc(createRegAllocPass(false));
531
532   // Run post-ra passes.
533   addPostRegAlloc();
534
535   // Insert prolog/epilog code.  Eliminate abstract frame index references...
536   addPass(&PrologEpilogCodeInserterID);
537
538   /// Add passes that optimize machine instructions after register allocation.
539   if (getOptLevel() != CodeGenOpt::None)
540     addMachineLateOptimization();
541
542   // Expand pseudo instructions before second scheduling pass.
543   addPass(&ExpandPostRAPseudosID);
544
545   // Run pre-sched2 passes.
546   addPreSched2();
547
548   // Second pass scheduler.
549   if (getOptLevel() != CodeGenOpt::None) {
550     if (MISchedPostRA)
551       addPass(&PostMachineSchedulerID);
552     else
553       addPass(&PostRASchedulerID);
554   }
555
556   // GC
557   if (addGCPasses()) {
558     if (PrintGCInfo)
559       addPass(createGCInfoPrinter(dbgs()), false, false);
560   }
561
562   // Basic block placement.
563   if (getOptLevel() != CodeGenOpt::None)
564     addBlockPlacement();
565
566   addPreEmitPass();
567
568   addPass(&StackMapLivenessID, false);
569
570   AddingMachinePasses = false;
571 }
572
573 /// Add passes that optimize machine instructions in SSA form.
574 void TargetPassConfig::addMachineSSAOptimization() {
575   // Pre-ra tail duplication.
576   addPass(&EarlyTailDuplicateID);
577
578   // Optimize PHIs before DCE: removing dead PHI cycles may make more
579   // instructions dead.
580   addPass(&OptimizePHIsID, false);
581
582   // This pass merges large allocas. StackSlotColoring is a different pass
583   // which merges spill slots.
584   addPass(&StackColoringID, false);
585
586   // If the target requests it, assign local variables to stack slots relative
587   // to one another and simplify frame index references where possible.
588   addPass(&LocalStackSlotAllocationID, false);
589
590   // With optimization, dead code should already be eliminated. However
591   // there is one known exception: lowered code for arguments that are only
592   // used by tail calls, where the tail calls reuse the incoming stack
593   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
594   addPass(&DeadMachineInstructionElimID);
595
596   // Allow targets to insert passes that improve instruction level parallelism,
597   // like if-conversion. Such passes will typically need dominator trees and
598   // loop info, just like LICM and CSE below.
599   addILPOpts();
600
601   addPass(&MachineLICMID, false);
602   addPass(&MachineCSEID, false);
603   addPass(&MachineSinkingID);
604
605   addPass(&PeepholeOptimizerID, false);
606   // Clean-up the dead code that may have been generated by peephole
607   // rewriting.
608   addPass(&DeadMachineInstructionElimID);
609 }
610
611 //===---------------------------------------------------------------------===//
612 /// Register Allocation Pass Configuration
613 //===---------------------------------------------------------------------===//
614
615 bool TargetPassConfig::getOptimizeRegAlloc() const {
616   switch (OptimizeRegAlloc) {
617   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
618   case cl::BOU_TRUE:  return true;
619   case cl::BOU_FALSE: return false;
620   }
621   llvm_unreachable("Invalid optimize-regalloc state");
622 }
623
624 /// RegisterRegAlloc's global Registry tracks allocator registration.
625 MachinePassRegistry RegisterRegAlloc::Registry;
626
627 /// A dummy default pass factory indicates whether the register allocator is
628 /// overridden on the command line.
629 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
630 static RegisterRegAlloc
631 defaultRegAlloc("default",
632                 "pick register allocator based on -O option",
633                 useDefaultRegisterAllocator);
634
635 /// -regalloc=... command line option.
636 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
637                RegisterPassParser<RegisterRegAlloc> >
638 RegAlloc("regalloc",
639          cl::init(&useDefaultRegisterAllocator),
640          cl::desc("Register allocator to use"));
641
642
643 /// Instantiate the default register allocator pass for this target for either
644 /// the optimized or unoptimized allocation path. This will be added to the pass
645 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
646 /// in the optimized case.
647 ///
648 /// A target that uses the standard regalloc pass order for fast or optimized
649 /// allocation may still override this for per-target regalloc
650 /// selection. But -regalloc=... always takes precedence.
651 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
652   if (Optimized)
653     return createGreedyRegisterAllocator();
654   else
655     return createFastRegisterAllocator();
656 }
657
658 /// Find and instantiate the register allocation pass requested by this target
659 /// at the current optimization level.  Different register allocators are
660 /// defined as separate passes because they may require different analysis.
661 ///
662 /// This helper ensures that the regalloc= option is always available,
663 /// even for targets that override the default allocator.
664 ///
665 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
666 /// this can be folded into addPass.
667 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
668   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
669
670   // Initialize the global default.
671   if (!Ctor) {
672     Ctor = RegAlloc;
673     RegisterRegAlloc::setDefault(RegAlloc);
674   }
675   if (Ctor != useDefaultRegisterAllocator)
676     return Ctor();
677
678   // With no -regalloc= override, ask the target for a regalloc pass.
679   return createTargetRegisterAllocator(Optimized);
680 }
681
682 /// Return true if the default global register allocator is in use and
683 /// has not be overriden on the command line with '-regalloc=...'
684 bool TargetPassConfig::usingDefaultRegAlloc() const {
685   return RegAlloc.getNumOccurrences() == 0;
686 }
687
688 /// Add the minimum set of target-independent passes that are required for
689 /// register allocation. No coalescing or scheduling.
690 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
691   addPass(&PHIEliminationID, false);
692   addPass(&TwoAddressInstructionPassID, false);
693
694   addPass(RegAllocPass);
695 }
696
697 /// Add standard target-independent passes that are tightly coupled with
698 /// optimized register allocation, including coalescing, machine instruction
699 /// scheduling, and register allocation itself.
700 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
701   addPass(&ProcessImplicitDefsID, false);
702
703   // LiveVariables currently requires pure SSA form.
704   //
705   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
706   // LiveVariables can be removed completely, and LiveIntervals can be directly
707   // computed. (We still either need to regenerate kill flags after regalloc, or
708   // preferably fix the scavenger to not depend on them).
709   addPass(&LiveVariablesID, false);
710
711   // Edge splitting is smarter with machine loop info.
712   addPass(&MachineLoopInfoID, false);
713   addPass(&PHIEliminationID, false);
714
715   // Eventually, we want to run LiveIntervals before PHI elimination.
716   if (EarlyLiveIntervals)
717     addPass(&LiveIntervalsID, false);
718
719   addPass(&TwoAddressInstructionPassID, false);
720   addPass(&RegisterCoalescerID);
721
722   // PreRA instruction scheduling.
723   addPass(&MachineSchedulerID);
724
725   // Add the selected register allocation pass.
726   addPass(RegAllocPass);
727
728   // Allow targets to change the register assignments before rewriting.
729   addPreRewrite();
730
731   // Finally rewrite virtual registers.
732   addPass(&VirtRegRewriterID);
733
734   // Perform stack slot coloring and post-ra machine LICM.
735   //
736   // FIXME: Re-enable coloring with register when it's capable of adding
737   // kill markers.
738   addPass(&StackSlotColoringID);
739
740   // Run post-ra machine LICM to hoist reloads / remats.
741   //
742   // FIXME: can this move into MachineLateOptimization?
743   addPass(&PostRAMachineLICMID);
744 }
745
746 //===---------------------------------------------------------------------===//
747 /// Post RegAlloc Pass Configuration
748 //===---------------------------------------------------------------------===//
749
750 /// Add passes that optimize machine instructions after register allocation.
751 void TargetPassConfig::addMachineLateOptimization() {
752   // Branch folding must be run after regalloc and prolog/epilog insertion.
753   addPass(&BranchFolderPassID);
754
755   // Tail duplication.
756   // Note that duplicating tail just increases code size and degrades
757   // performance for targets that require Structured Control Flow.
758   // In addition it can also make CFG irreducible. Thus we disable it.
759   if (!TM->requiresStructuredCFG())
760     addPass(&TailDuplicateID);
761
762   // Copy propagation.
763   addPass(&MachineCopyPropagationID);
764 }
765
766 /// Add standard GC passes.
767 bool TargetPassConfig::addGCPasses() {
768   addPass(&GCMachineCodeAnalysisID, false);
769   return true;
770 }
771
772 /// Add standard basic block placement passes.
773 void TargetPassConfig::addBlockPlacement() {
774   if (addPass(&MachineBlockPlacementID, false)) {
775     // Run a separate pass to collect block placement statistics.
776     if (EnableBlockPlacementStats)
777       addPass(&MachineBlockPlacementStatsID);
778   }
779 }