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