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