LLVM  8.0.1
PassBuilder.cpp
Go to the documentation of this file.
1 //===- Parsing, selection, and construction of pass pipelines -------------===//
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 /// \file
10 ///
11 /// This file provides the implementation of the PassBuilder based on our
12 /// static pass registry as well as related functionality. It also provides
13 /// helpers to aid in analyzing, debugging, and testing passes and pass
14 /// pipelines.
15 ///
16 //===----------------------------------------------------------------------===//
17 
19 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/Analysis/IVUsers.h"
39 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/PassManager.h"
60 #include "llvm/IR/Verifier.h"
61 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/Regex.h"
169 
170 using namespace llvm;
171 
172 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
174 static cl::opt<bool>
175  RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
177  cl::desc("Run Partial inlinining pass"));
178 
179 static cl::opt<bool>
180  RunNewGVN("enable-npm-newgvn", cl::init(false),
182  cl::desc("Run NewGVN instead of GVN"));
183 
185  "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
186  cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
187 
189  "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
190  cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
191 
193  "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
194  cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
195 
197  "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
198  cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
199 
201  "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
202  cl::desc("Run synthetic function entry count generation "
203  "pass"));
204 
205 static Regex DefaultAliasRegex(
206  "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
207 
208 static cl::opt<bool>
209  EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
210  cl::desc("Enable control height reduction optimization (CHR)"));
211 
213 
215  switch (Level) {
216  case PassBuilder::O0:
217  case PassBuilder::O1:
218  case PassBuilder::O2:
219  case PassBuilder::O3:
220  return false;
221 
222  case PassBuilder::Os:
223  case PassBuilder::Oz:
224  return true;
225  }
226  llvm_unreachable("Invalid optimization level!");
227 }
228 
229 namespace {
230 
231 /// No-op module pass which does nothing.
232 struct NoOpModulePass {
234  return PreservedAnalyses::all();
235  }
236  static StringRef name() { return "NoOpModulePass"; }
237 };
238 
239 /// No-op module analysis.
240 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
242  static AnalysisKey Key;
243 
244 public:
245  struct Result {};
246  Result run(Module &, ModuleAnalysisManager &) { return Result(); }
247  static StringRef name() { return "NoOpModuleAnalysis"; }
248 };
249 
250 /// No-op CGSCC pass which does nothing.
251 struct NoOpCGSCCPass {
254  return PreservedAnalyses::all();
255  }
256  static StringRef name() { return "NoOpCGSCCPass"; }
257 };
258 
259 /// No-op CGSCC analysis.
260 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
262  static AnalysisKey Key;
263 
264 public:
265  struct Result {};
267  return Result();
268  }
269  static StringRef name() { return "NoOpCGSCCAnalysis"; }
270 };
271 
272 /// No-op function pass which does nothing.
273 struct NoOpFunctionPass {
275  return PreservedAnalyses::all();
276  }
277  static StringRef name() { return "NoOpFunctionPass"; }
278 };
279 
280 /// No-op function analysis.
281 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
283  static AnalysisKey Key;
284 
285 public:
286  struct Result {};
287  Result run(Function &, FunctionAnalysisManager &) { return Result(); }
288  static StringRef name() { return "NoOpFunctionAnalysis"; }
289 };
290 
291 /// No-op loop pass which does nothing.
292 struct NoOpLoopPass {
295  return PreservedAnalyses::all();
296  }
297  static StringRef name() { return "NoOpLoopPass"; }
298 };
299 
300 /// No-op loop analysis.
301 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
303  static AnalysisKey Key;
304 
305 public:
306  struct Result {};
308  return Result();
309  }
310  static StringRef name() { return "NoOpLoopAnalysis"; }
311 };
312 
317 
318 } // End anonymous namespace.
319 
320 void PassBuilder::invokePeepholeEPCallbacks(
322  for (auto &C : PeepholeEPCallbacks)
323  C(FPM, Level);
324 }
325 
327 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
328  MAM.registerPass([&] { return CREATE_PASS; });
329 #include "PassRegistry.def"
330 
331  for (auto &C : ModuleAnalysisRegistrationCallbacks)
332  C(MAM);
333 }
334 
336 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
337  CGAM.registerPass([&] { return CREATE_PASS; });
338 #include "PassRegistry.def"
339 
340  for (auto &C : CGSCCAnalysisRegistrationCallbacks)
341  C(CGAM);
342 }
343 
345 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
346  FAM.registerPass([&] { return CREATE_PASS; });
347 #include "PassRegistry.def"
348 
349  for (auto &C : FunctionAnalysisRegistrationCallbacks)
350  C(FAM);
351 }
352 
354 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
355  LAM.registerPass([&] { return CREATE_PASS; });
356 #include "PassRegistry.def"
357 
358  for (auto &C : LoopAnalysisRegistrationCallbacks)
359  C(LAM);
360 }
361 
365  bool DebugLogging) {
366  assert(Level != O0 && "Must request optimizations!");
367  FunctionPassManager FPM(DebugLogging);
368 
369  // Form SSA out of local memory accesses after breaking apart aggregates into
370  // scalars.
371  FPM.addPass(SROA());
372 
373  // Catch trivial redundancies
375 
376  // Hoisting of scalars and load expressions.
377  if (EnableGVNHoist)
378  FPM.addPass(GVNHoistPass());
379 
380  // Global value numbering based sinking.
381  if (EnableGVNSink) {
382  FPM.addPass(GVNSinkPass());
383  FPM.addPass(SimplifyCFGPass());
384  }
385 
386  // Speculative execution if the target has divergent branches; otherwise nop.
388 
389  // Optimize based on known information about branches, and cleanup afterward.
390  FPM.addPass(JumpThreadingPass());
392  FPM.addPass(SimplifyCFGPass());
393  if (Level == O3)
395  FPM.addPass(InstCombinePass());
396 
397  if (!isOptimizingForSize(Level))
399 
400  invokePeepholeEPCallbacks(FPM, Level);
401 
402  // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
403  // using the size value profile. Don't perform this when optimizing for size.
404  if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
405  !isOptimizingForSize(Level))
406  FPM.addPass(PGOMemOPSizeOpt());
407 
408  FPM.addPass(TailCallElimPass());
409  FPM.addPass(SimplifyCFGPass());
410 
411  // Form canonically associated expression trees, and simplify the trees using
412  // basic mathematical properties. For example, this will form (nearly)
413  // minimal multiplication trees.
414  FPM.addPass(ReassociatePass());
415 
416  // Add the primary loop simplification pipeline.
417  // FIXME: Currently this is split into two loop pass pipelines because we run
418  // some function passes in between them. These can and should be removed
419  // and/or replaced by scheduling the loop pass equivalents in the correct
420  // positions. But those equivalent passes aren't powerful enough yet.
421  // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
422  // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
423  // fully replace `SimplifyCFGPass`, and the closest to the other we have is
424  // `LoopInstSimplify`.
425  LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
426 
427  // Simplify the loop body. We do this initially to clean up after other loop
428  // passes run, either when iterating on a loop or on inner loops with
429  // implications on the outer loop.
430  LPM1.addPass(LoopInstSimplifyPass());
431  LPM1.addPass(LoopSimplifyCFGPass());
432 
433  // Rotate Loop - disable header duplication at -Oz
434  LPM1.addPass(LoopRotatePass(Level != Oz));
435  LPM1.addPass(LICMPass());
436  LPM1.addPass(SimpleLoopUnswitchPass());
437  LPM2.addPass(IndVarSimplifyPass());
439 
440  for (auto &C : LateLoopOptimizationsEPCallbacks)
441  C(LPM2, Level);
442 
443  LPM2.addPass(LoopDeletionPass());
444  // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
445  // because it changes IR to makes profile annotation in back compile
446  // inaccurate.
447  if (Phase != ThinLTOPhase::PreLink ||
448  !PGOOpt || PGOOpt->SampleProfileFile.empty())
449  LPM2.addPass(LoopFullUnrollPass(Level));
450 
451  for (auto &C : LoopOptimizerEndEPCallbacks)
452  C(LPM2, Level);
453 
454  // We provide the opt remark emitter pass for LICM to use. We only need to do
455  // this once as it is immutable.
457  FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
458  FPM.addPass(SimplifyCFGPass());
459  FPM.addPass(InstCombinePass());
460  FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
461 
462  // Eliminate redundancies.
463  if (Level != O1) {
464  // These passes add substantial compile time so skip them at O1.
466  if (RunNewGVN)
467  FPM.addPass(NewGVNPass());
468  else
469  FPM.addPass(GVN());
470  }
471 
472  // Specially optimize memory movement as it doesn't look like dataflow in SSA.
473  FPM.addPass(MemCpyOptPass());
474 
475  // Sparse conditional constant propagation.
476  // FIXME: It isn't clear why we do this *after* loop passes rather than
477  // before...
478  FPM.addPass(SCCPPass());
479 
480  // Delete dead bit computations (instcombine runs after to fold away the dead
481  // computations, and then ADCE will run later to exploit any new DCE
482  // opportunities that creates).
483  FPM.addPass(BDCEPass());
484 
485  // Run instcombine after redundancy and dead bit elimination to exploit
486  // opportunities opened up by them.
487  FPM.addPass(InstCombinePass());
488  invokePeepholeEPCallbacks(FPM, Level);
489 
490  // Re-consider control flow based optimizations after redundancy elimination,
491  // redo DCE, etc.
492  FPM.addPass(JumpThreadingPass());
494  FPM.addPass(DSEPass());
495  FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
496 
497  for (auto &C : ScalarOptimizerLateEPCallbacks)
498  C(FPM, Level);
499 
500  // Finally, do an expensive DCE pass to catch all the dead code exposed by
501  // the simplifications and basic cleanup after all the simplifications.
502  FPM.addPass(ADCEPass());
503  FPM.addPass(SimplifyCFGPass());
504  FPM.addPass(InstCombinePass());
505  invokePeepholeEPCallbacks(FPM, Level);
506 
507  if (EnableCHR && Level == O3 && PGOOpt &&
508  (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty()))
510 
511  return FPM;
512 }
513 
514 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
516  bool RunProfileGen,
517  std::string ProfileGenFile,
518  std::string ProfileUseFile,
519  std::string ProfileRemappingFile) {
520  // Generally running simplification passes and the inliner with an high
521  // threshold results in smaller executables, but there may be cases where
522  // the size grows, so let's be conservative here and skip this simplification
523  // at -Os/Oz.
524  if (!isOptimizingForSize(Level)) {
525  InlineParams IP;
526 
527  // In the old pass manager, this is a cl::opt. Should still this be one?
528  IP.DefaultThreshold = 75;
529 
530  // FIXME: The hint threshold has the same value used by the regular inliner.
531  // This should probably be lowered after performance testing.
532  // FIXME: this comment is cargo culted from the old pass manager, revisit).
533  IP.HintThreshold = 325;
534 
535  CGSCCPassManager CGPipeline(DebugLogging);
536 
537  CGPipeline.addPass(InlinerPass(IP));
538 
540  FPM.addPass(SROA());
541  FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
542  FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
543  FPM.addPass(InstCombinePass()); // Combine silly sequences.
544  invokePeepholeEPCallbacks(FPM, Level);
545 
546  CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
547 
548  MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
549  }
550 
551  // Delete anything that is now dead to make sure that we don't instrument
552  // dead code. Instrumentation can end up keeping dead code around and
553  // dramatically increase code size.
554  MPM.addPass(GlobalDCEPass());
555 
556  if (RunProfileGen) {
558 
560  FPM.addPass(
562  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
563 
564  // Add the profile lowering pass.
565  InstrProfOptions Options;
566  if (!ProfileGenFile.empty())
567  Options.InstrProfileOutput = ProfileGenFile;
568  Options.DoCounterPromotion = true;
569  MPM.addPass(InstrProfiling(Options));
570  }
571 
572  if (!ProfileUseFile.empty())
573  MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile));
574 }
575 
576 static InlineParams
578  auto O3 = PassBuilder::O3;
579  unsigned OptLevel = Level > O3 ? 2 : Level;
580  unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
581  return getInlineParams(OptLevel, SizeLevel);
582 }
583 
587  bool DebugLogging) {
588  ModulePassManager MPM(DebugLogging);
589 
590  // Do basic inference of function attributes from known properties of system
591  // libraries and other oracles.
593 
594  // Create an early function pass manager to cleanup the output of the
595  // frontend.
596  FunctionPassManager EarlyFPM(DebugLogging);
597  EarlyFPM.addPass(SimplifyCFGPass());
598  EarlyFPM.addPass(SROA());
599  EarlyFPM.addPass(EarlyCSEPass());
600  EarlyFPM.addPass(LowerExpectIntrinsicPass());
601  if (Level == O3)
602  EarlyFPM.addPass(CallSiteSplittingPass());
603 
604  // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
605  // to convert bitcast to direct calls so that they can be inlined during the
606  // profile annotation prepration step.
607  // More details about SamplePGO design can be found in:
608  // https://research.google.com/pubs/pub45290.html
609  // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
610  if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
611  Phase == ThinLTOPhase::PostLink)
612  EarlyFPM.addPass(InstCombinePass());
613  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
614 
615  if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
616  // Annotate sample profile right after early FPM to ensure freshness of
617  // the debug info.
618  MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
619  PGOOpt->ProfileRemappingFile,
620  Phase == ThinLTOPhase::PreLink));
621  // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
622  // for the profile annotation to be accurate in the ThinLTO backend.
623  if (Phase != ThinLTOPhase::PreLink)
624  // We perform early indirect call promotion here, before globalopt.
625  // This is important for the ThinLTO backend phase because otherwise
626  // imported available_externally functions look unreferenced and are
627  // removed.
628  MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
629  true));
630  }
631 
632  // Interprocedural constant propagation now that basic cleanup has occurred
633  // and prior to optimizing globals.
634  // FIXME: This position in the pipeline hasn't been carefully considered in
635  // years, it should be re-analyzed.
636  MPM.addPass(IPSCCPPass());
637 
638  // Attach metadata to indirect call sites indicating the set of functions
639  // they may target at run-time. This should follow IPSCCP.
641 
642  // Optimize globals to try and fold them into constants.
643  MPM.addPass(GlobalOptPass());
644 
645  // Promote any localized globals to SSA registers.
646  // FIXME: Should this instead by a run of SROA?
647  // FIXME: We should probably run instcombine and simplify-cfg afterward to
648  // delete control flows that are dead once globals have been folded to
649  // constants.
651 
652  // Remove any dead arguments exposed by cleanups and constand folding
653  // globals.
655 
656  // Create a small function pass pipeline to cleanup after all the global
657  // optimizations.
658  FunctionPassManager GlobalCleanupPM(DebugLogging);
659  GlobalCleanupPM.addPass(InstCombinePass());
660  invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
661 
662  GlobalCleanupPM.addPass(SimplifyCFGPass());
663  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
664 
665  // Add all the requested passes for instrumentation PGO, if requested.
666  if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
667  (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
668  addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
669  PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile,
670  PGOOpt->ProfileRemappingFile);
671  MPM.addPass(PGOIndirectCallPromotion(false, false));
672  }
673 
674  // Synthesize function entry counts for non-PGO compilation.
675  if (EnableSyntheticCounts && !PGOOpt)
677 
678  // Require the GlobalsAA analysis for the module so we can query it within
679  // the CGSCC pipeline.
681 
682  // Require the ProfileSummaryAnalysis for the module so we can query it within
683  // the inliner pass.
685 
686  // Now begin the main postorder CGSCC pipeline.
687  // FIXME: The current CGSCC pipeline has its origins in the legacy pass
688  // manager and trying to emulate its precise behavior. Much of this doesn't
689  // make a lot of sense and we should revisit the core CGSCC structure.
690  CGSCCPassManager MainCGPipeline(DebugLogging);
691 
692  // Note: historically, the PruneEH pass was run first to deduce nounwind and
693  // generally clean up exception handling overhead. It isn't clear this is
694  // valuable as the inliner doesn't currently care whether it is inlining an
695  // invoke or a call.
696 
697  // Run the inliner first. The theory is that we are walking bottom-up and so
698  // the callees have already been fully optimized, and we want to inline them
699  // into the callers so that our optimizations can reflect that.
700  // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
701  // because it makes profile annotation in the backend inaccurate.
703  if (Phase == ThinLTOPhase::PreLink &&
704  PGOOpt && !PGOOpt->SampleProfileFile.empty())
705  IP.HotCallSiteThreshold = 0;
706  MainCGPipeline.addPass(InlinerPass(IP));
707 
708  // Now deduce any function attributes based in the current code.
709  MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
710 
711  // When at O3 add argument promotion to the pass pipeline.
712  // FIXME: It isn't at all clear why this should be limited to O3.
713  if (Level == O3)
714  MainCGPipeline.addPass(ArgumentPromotionPass());
715 
716  // Lastly, add the core function simplification pipeline nested inside the
717  // CGSCC walk.
719  buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
720 
721  // We only want to do hot cold splitting once for ThinLTO, during the
722  // post-link ThinLTO.
723  if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink)
725 
726  for (auto &C : CGSCCOptimizerLateEPCallbacks)
727  C(MainCGPipeline, Level);
728 
729  // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
730  // to detect when we devirtualize indirect calls and iterate the SCC passes
731  // in that case to try and catch knock-on inlining or function attrs
732  // opportunities. Then we add it to the module pipeline by walking the SCCs
733  // in postorder (or bottom-up).
734  MPM.addPass(
736  std::move(MainCGPipeline), MaxDevirtIterations)));
737 
738  return MPM;
739 }
740 
743  bool DebugLogging) {
744  ModulePassManager MPM(DebugLogging);
745 
746  // Optimize globals now that the module is fully simplified.
747  MPM.addPass(GlobalOptPass());
748  MPM.addPass(GlobalDCEPass());
749 
750  // Run partial inlining pass to partially inline functions that have
751  // large bodies.
752  if (RunPartialInlining)
754 
755  // Remove avail extern fns and globals definitions since we aren't compiling
756  // an object file for later LTO. For LTO we want to preserve these so they
757  // are eligible for inlining at link-time. Note if they are unreferenced they
758  // will be removed by GlobalDCE later, so this only impacts referenced
759  // available externally globals. Eventually they will be suppressed during
760  // codegen, but eliminating here enables more opportunity for GlobalDCE as it
761  // may make globals referenced by available external functions dead and saves
762  // running remaining passes on the eliminated functions.
764 
765  // Do RPO function attribute inference across the module to forward-propagate
766  // attributes where applicable.
767  // FIXME: Is this really an optimization rather than a canonicalization?
769 
770  // Re-require GloblasAA here prior to function passes. This is particularly
771  // useful as the above will have inlined, DCE'ed, and function-attr
772  // propagated everything. We should at this point have a reasonably minimal
773  // and richly annotated call graph. By computing aliasing and mod/ref
774  // information for all local globals here, the late loop passes and notably
775  // the vectorizer will be able to use them to help recognize vectorizable
776  // memory operations.
778 
779  FunctionPassManager OptimizePM(DebugLogging);
780  OptimizePM.addPass(Float2IntPass());
781  // FIXME: We need to run some loop optimizations to re-rotate loops after
782  // simplify-cfg and others undo their rotation.
783 
784  // Optimize the loop execution. These passes operate on entire loop nests
785  // rather than on each loop in an inside-out manner, and so they are actually
786  // function passes.
787 
788  for (auto &C : VectorizerStartEPCallbacks)
789  C(OptimizePM, Level);
790 
791  // First rotate loops that may have been un-rotated by prior passes.
792  OptimizePM.addPass(
794 
795  // Distribute loops to allow partial vectorization. I.e. isolate dependences
796  // into separate loop that would otherwise inhibit vectorization. This is
797  // currently only performed for loops marked with the metadata
798  // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
799  OptimizePM.addPass(LoopDistributePass());
800 
801  // Now run the core loop vectorizer.
802  OptimizePM.addPass(LoopVectorizePass());
803 
804  // Eliminate loads by forwarding stores from the previous iteration to loads
805  // of the current iteration.
806  OptimizePM.addPass(LoopLoadEliminationPass());
807 
808  // Cleanup after the loop optimization passes.
809  OptimizePM.addPass(InstCombinePass());
810 
811  // Now that we've formed fast to execute loop structures, we do further
812  // optimizations. These are run afterward as they might block doing complex
813  // analyses and transforms such as what are needed for loop vectorization.
814 
815  // Cleanup after loop vectorization, etc. Simplification passes like CVP and
816  // GVN, loop transforms, and others have already run, so it's now better to
817  // convert to more optimized IR using more aggressive simplify CFG options.
818  // The extra sinking transform can create larger basic blocks, so do this
819  // before SLP vectorization.
821  forwardSwitchCondToPhi(true).
822  convertSwitchToLookupTable(true).
823  needCanonicalLoops(false).
824  sinkCommonInsts(true)));
825 
826  // Optimize parallel scalar instruction chains into SIMD instructions.
827  OptimizePM.addPass(SLPVectorizerPass());
828 
829  OptimizePM.addPass(InstCombinePass());
830 
831  // Unroll small loops to hide loop backedge latency and saturate any parallel
832  // execution resources of an out-of-order processor. We also then need to
833  // clean up redundancies and loop invariant code.
834  // FIXME: It would be really good to use a loop-integrated instruction
835  // combiner for cleanup here so that the unrolling and LICM can be pipelined
836  // across the loop nests.
837  // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
838  if (EnableUnrollAndJam) {
839  OptimizePM.addPass(
841  }
842  OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(Level)));
844  OptimizePM.addPass(InstCombinePass());
846  OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
847 
848  // Now that we've vectorized and unrolled loops, we may have more refined
849  // alignment information, try to re-derive it here.
851 
852  // LoopSink pass sinks instructions hoisted by LICM, which serves as a
853  // canonicalization pass that enables other optimizations. As a result,
854  // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
855  // result too early.
856  OptimizePM.addPass(LoopSinkPass());
857 
858  // And finally clean up LCSSA form before generating code.
859  OptimizePM.addPass(InstSimplifyPass());
860 
861  // This hoists/decomposes div/rem ops. It should run after other sink/hoist
862  // passes to avoid re-sinking, but before SimplifyCFG because it can allow
863  // flattening of blocks.
864  OptimizePM.addPass(DivRemPairsPass());
865 
866  // LoopSink (and other loop passes since the last simplifyCFG) might have
867  // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
868  OptimizePM.addPass(SimplifyCFGPass());
869 
870  // Optimize PHIs by speculating around them when profitable. Note that this
871  // pass needs to be run after any PRE or similar pass as it is essentially
872  // inserting redudnancies into the progrem. This even includes SimplifyCFG.
873  OptimizePM.addPass(SpeculateAroundPHIsPass());
874 
875  for (auto &C : OptimizerLastEPCallbacks)
876  C(OptimizePM, Level);
877 
878  // Add the core optimizing pipeline.
879  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
880 
881  MPM.addPass(CGProfilePass());
882 
883  // Now we need to do some global optimization transforms.
884  // FIXME: It would seem like these should come first in the optimization
885  // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
886  // ordering here.
887  MPM.addPass(GlobalDCEPass());
888  MPM.addPass(ConstantMergePass());
889 
890  return MPM;
891 }
892 
895  bool DebugLogging) {
896  assert(Level != O0 && "Must request optimizations for the default pipeline!");
897 
898  ModulePassManager MPM(DebugLogging);
899 
900  // Force any function attributes we want the rest of the pipeline to observe.
902 
903  // Apply module pipeline start EP callback.
904  for (auto &C : PipelineStartEPCallbacks)
905  C(MPM);
906 
907  if (PGOOpt && PGOOpt->SamplePGOSupport)
909 
910  // Add the core simplification pipeline.
911  MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
912  DebugLogging));
913 
914  // Now add the optimization pipeline.
915  MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
916 
917  return MPM;
918 }
919 
922  bool DebugLogging) {
923  assert(Level != O0 && "Must request optimizations for the default pipeline!");
924 
925  ModulePassManager MPM(DebugLogging);
926 
927  // Force any function attributes we want the rest of the pipeline to observe.
929 
930  if (PGOOpt && PGOOpt->SamplePGOSupport)
932 
933  // Apply module pipeline start EP callback.
934  for (auto &C : PipelineStartEPCallbacks)
935  C(MPM);
936 
937  // If we are planning to perform ThinLTO later, we don't bloat the code with
938  // unrolling/vectorization/... now. Just simplify the module as much as we
939  // can.
940  MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
941  DebugLogging));
942 
943  // Run partial inlining pass to partially inline functions that have
944  // large bodies.
945  // FIXME: It isn't clear whether this is really the right place to run this
946  // in ThinLTO. Because there is another canonicalization and simplification
947  // phase that will run after the thin link, running this here ends up with
948  // less information than will be available later and it may grow functions in
949  // ways that aren't beneficial.
950  if (RunPartialInlining)
952 
953  // Reduce the size of the IR as much as possible.
954  MPM.addPass(GlobalOptPass());
955 
956  return MPM;
957 }
958 
960  OptimizationLevel Level, bool DebugLogging,
961  const ModuleSummaryIndex *ImportSummary) {
962  ModulePassManager MPM(DebugLogging);
963 
964  if (ImportSummary) {
965  // These passes import type identifier resolutions for whole-program
966  // devirtualization and CFI. They must run early because other passes may
967  // disturb the specific instruction patterns that these passes look for,
968  // creating dependencies on resolutions that may not appear in the summary.
969  //
970  // For example, GVN may transform the pattern assume(type.test) appearing in
971  // two basic blocks into assume(phi(type.test, type.test)), which would
972  // transform a dependency on a WPD resolution into a dependency on a type
973  // identifier resolution for CFI.
974  //
975  // Also, WPD has access to more precise information than ICP and can
976  // devirtualize more effectively, so it should operate on the IR first.
977  MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
978  MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
979  }
980 
981  // Force any function attributes we want the rest of the pipeline to observe.
983 
984  // During the ThinLTO backend phase we perform early indirect call promotion
985  // here, before globalopt. Otherwise imported available_externally functions
986  // look unreferenced and are removed.
987  // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
988  // with SamplePGO.
989  if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
990  MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
991  false /* SamplePGO */));
992 
993  // Add the core simplification pipeline.
994  MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
995  DebugLogging));
996 
997  // Now add the optimization pipeline.
998  MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
999 
1000  return MPM;
1001 }
1002 
1005  bool DebugLogging) {
1006  assert(Level != O0 && "Must request optimizations for the default pipeline!");
1007  // FIXME: We should use a customized pre-link pipeline!
1008  return buildPerModuleDefaultPipeline(Level, DebugLogging);
1009 }
1010 
1013  ModuleSummaryIndex *ExportSummary) {
1014  assert(Level != O0 && "Must request optimizations for the default pipeline!");
1015  ModulePassManager MPM(DebugLogging);
1016 
1017  if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
1018  // Load sample profile before running the LTO optimization pipeline.
1019  MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
1020  PGOOpt->ProfileRemappingFile,
1021  false /* ThinLTOPhase::PreLink */));
1022  }
1023 
1024  // Remove unused virtual tables to improve the quality of code generated by
1025  // whole-program devirtualization and bitset lowering.
1026  MPM.addPass(GlobalDCEPass());
1027 
1028  // Force any function attributes we want the rest of the pipeline to observe.
1030 
1031  // Do basic inference of function attributes from known properties of system
1032  // libraries and other oracles.
1034 
1035  if (Level > 1) {
1036  FunctionPassManager EarlyFPM(DebugLogging);
1037  EarlyFPM.addPass(CallSiteSplittingPass());
1038  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1039 
1040  // Indirect call promotion. This should promote all the targets that are
1041  // left by the earlier promotion pass that promotes intra-module targets.
1042  // This two-step promotion is to save the compile time. For LTO, it should
1043  // produce the same result as if we only do promotion here.
1045  true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
1046  // Propagate constants at call sites into the functions they call. This
1047  // opens opportunities for globalopt (and inlining) by substituting function
1048  // pointers passed as arguments to direct uses of functions.
1049  MPM.addPass(IPSCCPPass());
1050 
1051  // Attach metadata to indirect call sites indicating the set of functions
1052  // they may target at run-time. This should follow IPSCCP.
1054  }
1055 
1056  // Now deduce any function attributes based in the current code.
1059 
1060  // Do RPO function attribute inference across the module to forward-propagate
1061  // attributes where applicable.
1062  // FIXME: Is this really an optimization rather than a canonicalization?
1064 
1065  // Use inragne annotations on GEP indices to split globals where beneficial.
1066  MPM.addPass(GlobalSplitPass());
1067 
1068  // Run whole program optimization of virtual call when the list of callees
1069  // is fixed.
1070  MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1071 
1072  // Stop here at -O1.
1073  if (Level == 1) {
1074  // The LowerTypeTestsPass needs to run to lower type metadata and the
1075  // type.test intrinsics. The pass does nothing if CFI is disabled.
1076  MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1077  return MPM;
1078  }
1079 
1080  // Optimize globals to try and fold them into constants.
1081  MPM.addPass(GlobalOptPass());
1082 
1083  // Promote any localized globals to SSA registers.
1085 
1086  // Linking modules together can lead to duplicate global constant, only
1087  // keep one copy of each constant.
1088  MPM.addPass(ConstantMergePass());
1089 
1090  // Remove unused arguments from functions.
1092 
1093  // Reduce the code after globalopt and ipsccp. Both can open up significant
1094  // simplification opportunities, and both can propagate functions through
1095  // function pointers. When this happens, we often have to resolve varargs
1096  // calls, etc, so let instcombine do this.
1097  FunctionPassManager PeepholeFPM(DebugLogging);
1098  if (Level == O3)
1099  PeepholeFPM.addPass(AggressiveInstCombinePass());
1100  PeepholeFPM.addPass(InstCombinePass());
1101  invokePeepholeEPCallbacks(PeepholeFPM, Level);
1102 
1103  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
1104 
1105  // Note: historically, the PruneEH pass was run first to deduce nounwind and
1106  // generally clean up exception handling overhead. It isn't clear this is
1107  // valuable as the inliner doesn't currently care whether it is inlining an
1108  // invoke or a call.
1109  // Run the inliner now.
1112 
1113  // Optimize globals again after we ran the inliner.
1114  MPM.addPass(GlobalOptPass());
1115 
1116  // Garbage collect dead functions.
1117  // FIXME: Add ArgumentPromotion pass after once it's ported.
1118  MPM.addPass(GlobalDCEPass());
1119 
1120  FunctionPassManager FPM(DebugLogging);
1121  // The IPO Passes may leave cruft around. Clean up after them.
1122  FPM.addPass(InstCombinePass());
1123  invokePeepholeEPCallbacks(FPM, Level);
1124 
1125  FPM.addPass(JumpThreadingPass());
1126 
1127  // Break up allocas
1128  FPM.addPass(SROA());
1129 
1130  // Run a few AA driver optimizations here and now to cleanup the code.
1131  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1132 
1135  // FIXME: here we run IP alias analysis in the legacy PM.
1136 
1137  FunctionPassManager MainFPM;
1138 
1139  // FIXME: once we fix LoopPass Manager, add LICM here.
1140  // FIXME: once we provide support for enabling MLSM, add it here.
1141  // FIXME: once we provide support for enabling NewGVN, add it here.
1142  if (RunNewGVN)
1143  MainFPM.addPass(NewGVNPass());
1144  else
1145  MainFPM.addPass(GVN());
1146 
1147  // Remove dead memcpy()'s.
1148  MainFPM.addPass(MemCpyOptPass());
1149 
1150  // Nuke dead stores.
1151  MainFPM.addPass(DSEPass());
1152 
1153  // FIXME: at this point, we run a bunch of loop passes:
1154  // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1155  // loopVectorize. Enable them once the remaining issue with LPM
1156  // are sorted out.
1157 
1158  MainFPM.addPass(InstCombinePass());
1159  MainFPM.addPass(SimplifyCFGPass());
1160  MainFPM.addPass(SCCPPass());
1161  MainFPM.addPass(InstCombinePass());
1162  MainFPM.addPass(BDCEPass());
1163 
1164  // FIXME: We may want to run SLPVectorizer here.
1165  // After vectorization, assume intrinsics may tell us more
1166  // about pointer alignments.
1167 #if 0
1168  MainFPM.add(AlignmentFromAssumptionsPass());
1169 #endif
1170 
1171  // FIXME: Conditionally run LoadCombine here, after it's ported
1172  // (in case we still have this pass, given its questionable usefulness).
1173 
1174  MainFPM.addPass(InstCombinePass());
1175  invokePeepholeEPCallbacks(MainFPM, Level);
1176  MainFPM.addPass(JumpThreadingPass());
1177  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1178 
1179  // Create a function that performs CFI checks for cross-DSO calls with
1180  // targets in the current module.
1181  MPM.addPass(CrossDSOCFIPass());
1182 
1183  // Lower type metadata and the type.test intrinsic. This pass supports
1184  // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1185  // to be run at link time if CFI is enabled. This pass does nothing if
1186  // CFI is disabled.
1187  MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1188 
1189  // Add late LTO optimization passes.
1190  // Delete basic blocks, which optimization passes may have killed.
1192 
1193  // Drop bodies of available eternally objects to improve GlobalDCE.
1195 
1196  // Now that we have optimized the program, discard unreachable functions.
1197  MPM.addPass(GlobalDCEPass());
1198 
1199  // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
1200  return MPM;
1201 }
1202 
1204  AAManager AA;
1205 
1206  // The order in which these are registered determines their priority when
1207  // being queried.
1208 
1209  // First we register the basic alias analysis that provides the majority of
1210  // per-function local AA logic. This is a stateless, on-demand local set of
1211  // AA techniques.
1213 
1214  // Next we query fast, specialized alias analyses that wrap IR-embedded
1215  // information about aliasing.
1218 
1219  // Add support for querying global aliasing information when available.
1220  // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1221  // analysis, all that the `AAManager` can do is query for any *cached*
1222  // results from `GlobalsAA` through a readonly proxy.
1224 
1225  return AA;
1226 }
1227 
1229  if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1230  return None;
1231  int Count;
1232  if (Name.getAsInteger(0, Count) || Count <= 0)
1233  return None;
1234  return Count;
1235 }
1236 
1238  if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1239  return None;
1240  int Count;
1241  if (Name.getAsInteger(0, Count) || Count <= 0)
1242  return None;
1243  return Count;
1244 }
1245 
1247  if (!Name.consume_front(PassName))
1248  return false;
1249  // normal pass name w/o parameters == default parameters
1250  if (Name.empty())
1251  return true;
1252  return Name.startswith("<") && Name.endswith(">");
1253 }
1254 
1255 namespace {
1256 
1257 /// This performs customized parsing of pass name with parameters.
1258 ///
1259 /// We do not need parametrization of passes in textual pipeline very often,
1260 /// yet on a rare occasion ability to specify parameters right there can be
1261 /// useful.
1262 ///
1263 /// \p Name - parameterized specification of a pass from a textual pipeline
1264 /// is a string in a form of :
1265 /// PassName '<' parameter-list '>'
1266 ///
1267 /// Parameter list is being parsed by the parser callable argument, \p Parser,
1268 /// It takes a string-ref of parameters and returns either StringError or a
1269 /// parameter list in a form of a custom parameters type, all wrapped into
1270 /// Expected<> template class.
1271 ///
1272 template <typename ParametersParseCallableT>
1273 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1274  StringRef PassName) -> decltype(Parser(StringRef{})) {
1275  using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1276 
1277  StringRef Params = Name;
1278  if (!Params.consume_front(PassName)) {
1279  assert(false &&
1280  "unable to strip pass name from parametrized pass specification");
1281  }
1282  if (Params.empty())
1283  return ParametersT{};
1284  if (!Params.consume_front("<") || !Params.consume_back(">")) {
1285  assert(false && "invalid format for parametrized pass name");
1286  }
1287 
1288  Expected<ParametersT> Result = Parser(Params);
1289  assert((Result || Result.template errorIsA<StringError>()) &&
1290  "Pass parameter parser can only return StringErrors.");
1291  return std::move(Result);
1292 }
1293 
1294 /// Parser of parameters for LoopUnroll pass.
1295 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1296  LoopUnrollOptions UnrollOpts;
1297  while (!Params.empty()) {
1298  StringRef ParamName;
1299  std::tie(ParamName, Params) = Params.split(';');
1300  int OptLevel = StringSwitch<int>(ParamName)
1301  .Case("O0", 0)
1302  .Case("O1", 1)
1303  .Case("O2", 2)
1304  .Case("O3", 3)
1305  .Default(-1);
1306  if (OptLevel >= 0) {
1307  UnrollOpts.setOptLevel(OptLevel);
1308  continue;
1309  }
1310 
1311  bool Enable = !ParamName.consume_front("no-");
1312  if (ParamName == "partial") {
1313  UnrollOpts.setPartial(Enable);
1314  } else if (ParamName == "peeling") {
1315  UnrollOpts.setPeeling(Enable);
1316  } else if (ParamName == "runtime") {
1317  UnrollOpts.setRuntime(Enable);
1318  } else if (ParamName == "upperbound") {
1319  UnrollOpts.setUpperBound(Enable);
1320  } else {
1321  return make_error<StringError>(
1322  formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1324  }
1325  }
1326  return UnrollOpts;
1327 }
1328 
1329 } // namespace
1330 
1331 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1332 /// alias.
1334  return Name.startswith("default") || Name.startswith("thinlto") ||
1335  Name.startswith("lto");
1336 }
1337 
1338 /// Tests whether registered callbacks will accept a given pass name.
1339 ///
1340 /// When parsing a pipeline text, the type of the outermost pipeline may be
1341 /// omitted, in which case the type is automatically determined from the first
1342 /// pass name in the text. This may be a name that is handled through one of the
1343 /// callbacks. We check this through the oridinary parsing callbacks by setting
1344 /// up a dummy PassManager in order to not force the client to also handle this
1345 /// type of query.
1346 template <typename PassManagerT, typename CallbacksT>
1347 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1348  if (!Callbacks.empty()) {
1349  PassManagerT DummyPM;
1350  for (auto &CB : Callbacks)
1351  if (CB(Name, DummyPM, {}))
1352  return true;
1353  }
1354  return false;
1355 }
1356 
1357 template <typename CallbacksT>
1358 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1359  // Manually handle aliases for pre-configured pipeline fragments.
1361  return DefaultAliasRegex.match(Name);
1362 
1363  // Explicitly handle pass manager names.
1364  if (Name == "module")
1365  return true;
1366  if (Name == "cgscc")
1367  return true;
1368  if (Name == "function")
1369  return true;
1370 
1371  // Explicitly handle custom-parsed pass names.
1372  if (parseRepeatPassName(Name))
1373  return true;
1374 
1375 #define MODULE_PASS(NAME, CREATE_PASS) \
1376  if (Name == NAME) \
1377  return true;
1378 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1379  if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1380  return true;
1381 #include "PassRegistry.def"
1382 
1383  return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1384 }
1385 
1386 template <typename CallbacksT>
1387 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1388  // Explicitly handle pass manager names.
1389  if (Name == "cgscc")
1390  return true;
1391  if (Name == "function")
1392  return true;
1393 
1394  // Explicitly handle custom-parsed pass names.
1395  if (parseRepeatPassName(Name))
1396  return true;
1397  if (parseDevirtPassName(Name))
1398  return true;
1399 
1400 #define CGSCC_PASS(NAME, CREATE_PASS) \
1401  if (Name == NAME) \
1402  return true;
1403 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1404  if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1405  return true;
1406 #include "PassRegistry.def"
1407 
1408  return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1409 }
1410 
1411 template <typename CallbacksT>
1412 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1413  // Explicitly handle pass manager names.
1414  if (Name == "function")
1415  return true;
1416  if (Name == "loop")
1417  return true;
1418 
1419  // Explicitly handle custom-parsed pass names.
1420  if (parseRepeatPassName(Name))
1421  return true;
1422 
1423 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1424  if (Name == NAME) \
1425  return true;
1426 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1427  if (checkParametrizedPassName(Name, NAME)) \
1428  return true;
1429 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1430  if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1431  return true;
1432 #include "PassRegistry.def"
1433 
1434  return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1435 }
1436 
1437 template <typename CallbacksT>
1438 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1439  // Explicitly handle pass manager names.
1440  if (Name == "loop")
1441  return true;
1442 
1443  // Explicitly handle custom-parsed pass names.
1444  if (parseRepeatPassName(Name))
1445  return true;
1446 
1447 #define LOOP_PASS(NAME, CREATE_PASS) \
1448  if (Name == NAME) \
1449  return true;
1450 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1451  if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1452  return true;
1453 #include "PassRegistry.def"
1454 
1455  return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1456 }
1457 
1459 PassBuilder::parsePipelineText(StringRef Text) {
1460  std::vector<PipelineElement> ResultPipeline;
1461 
1462  SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1463  &ResultPipeline};
1464  for (;;) {
1465  std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1466  size_t Pos = Text.find_first_of(",()");
1467  Pipeline.push_back({Text.substr(0, Pos), {}});
1468 
1469  // If we have a single terminating name, we're done.
1470  if (Pos == Text.npos)
1471  break;
1472 
1473  char Sep = Text[Pos];
1474  Text = Text.substr(Pos + 1);
1475  if (Sep == ',')
1476  // Just a name ending in a comma, continue.
1477  continue;
1478 
1479  if (Sep == '(') {
1480  // Push the inner pipeline onto the stack to continue processing.
1481  PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1482  continue;
1483  }
1484 
1485  assert(Sep == ')' && "Bogus separator!");
1486  // When handling the close parenthesis, we greedily consume them to avoid
1487  // empty strings in the pipeline.
1488  do {
1489  // If we try to pop the outer pipeline we have unbalanced parentheses.
1490  if (PipelineStack.size() == 1)
1491  return None;
1492 
1493  PipelineStack.pop_back();
1494  } while (Text.consume_front(")"));
1495 
1496  // Check if we've finished parsing.
1497  if (Text.empty())
1498  break;
1499 
1500  // Otherwise, the end of an inner pipeline always has to be followed by
1501  // a comma, and then we can continue.
1502  if (!Text.consume_front(","))
1503  return None;
1504  }
1505 
1506  if (PipelineStack.size() > 1)
1507  // Unbalanced paretheses.
1508  return None;
1509 
1510  assert(PipelineStack.back() == &ResultPipeline &&
1511  "Wrong pipeline at the bottom of the stack!");
1512  return {std::move(ResultPipeline)};
1513 }
1514 
1515 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1516  const PipelineElement &E,
1517  bool VerifyEachPass, bool DebugLogging) {
1518  auto &Name = E.Name;
1519  auto &InnerPipeline = E.InnerPipeline;
1520 
1521  // First handle complex passes like the pass managers which carry pipelines.
1522  if (!InnerPipeline.empty()) {
1523  if (Name == "module") {
1524  ModulePassManager NestedMPM(DebugLogging);
1525  if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1526  VerifyEachPass, DebugLogging))
1527  return Err;
1528  MPM.addPass(std::move(NestedMPM));
1529  return Error::success();
1530  }
1531  if (Name == "cgscc") {
1532  CGSCCPassManager CGPM(DebugLogging);
1533  if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1534  DebugLogging))
1535  return Err;
1536  MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1537  return Error::success();
1538  }
1539  if (Name == "function") {
1540  FunctionPassManager FPM(DebugLogging);
1541  if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1542  VerifyEachPass, DebugLogging))
1543  return Err;
1544  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1545  return Error::success();
1546  }
1547  if (auto Count = parseRepeatPassName(Name)) {
1548  ModulePassManager NestedMPM(DebugLogging);
1549  if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1550  VerifyEachPass, DebugLogging))
1551  return Err;
1552  MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1553  return Error::success();
1554  }
1555 
1556  for (auto &C : ModulePipelineParsingCallbacks)
1557  if (C(Name, MPM, InnerPipeline))
1558  return Error::success();
1559 
1560  // Normal passes can't have pipelines.
1561  return make_error<StringError>(
1562  formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1564  ;
1565  }
1566 
1567  // Manually handle aliases for pre-configured pipeline fragments.
1569  SmallVector<StringRef, 3> Matches;
1570  if (!DefaultAliasRegex.match(Name, &Matches))
1571  return make_error<StringError>(
1572  formatv("unknown default pipeline alias '{0}'", Name).str(),
1574 
1575  assert(Matches.size() == 3 && "Must capture two matched strings!");
1576 
1577  OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1578  .Case("O0", O0)
1579  .Case("O1", O1)
1580  .Case("O2", O2)
1581  .Case("O3", O3)
1582  .Case("Os", Os)
1583  .Case("Oz", Oz);
1584  if (L == O0)
1585  // At O0 we do nothing at all!
1586  return Error::success();
1587 
1588  if (Matches[1] == "default") {
1589  MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1590  } else if (Matches[1] == "thinlto-pre-link") {
1591  MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1592  } else if (Matches[1] == "thinlto") {
1593  MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
1594  } else if (Matches[1] == "lto-pre-link") {
1595  MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1596  } else {
1597  assert(Matches[1] == "lto" && "Not one of the matched options!");
1598  MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
1599  }
1600  return Error::success();
1601  }
1602 
1603  // Finally expand the basic registered passes from the .inc file.
1604 #define MODULE_PASS(NAME, CREATE_PASS) \
1605  if (Name == NAME) { \
1606  MPM.addPass(CREATE_PASS); \
1607  return Error::success(); \
1608  }
1609 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1610  if (Name == "require<" NAME ">") { \
1611  MPM.addPass( \
1612  RequireAnalysisPass< \
1613  std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1614  return Error::success(); \
1615  } \
1616  if (Name == "invalidate<" NAME ">") { \
1617  MPM.addPass(InvalidateAnalysisPass< \
1618  std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1619  return Error::success(); \
1620  }
1621 #include "PassRegistry.def"
1622 
1623  for (auto &C : ModulePipelineParsingCallbacks)
1624  if (C(Name, MPM, InnerPipeline))
1625  return Error::success();
1626  return make_error<StringError>(
1627  formatv("unknown module pass '{0}'", Name).str(),
1629 }
1630 
1631 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1632  const PipelineElement &E, bool VerifyEachPass,
1633  bool DebugLogging) {
1634  auto &Name = E.Name;
1635  auto &InnerPipeline = E.InnerPipeline;
1636 
1637  // First handle complex passes like the pass managers which carry pipelines.
1638  if (!InnerPipeline.empty()) {
1639  if (Name == "cgscc") {
1640  CGSCCPassManager NestedCGPM(DebugLogging);
1641  if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1642  VerifyEachPass, DebugLogging))
1643  return Err;
1644  // Add the nested pass manager with the appropriate adaptor.
1645  CGPM.addPass(std::move(NestedCGPM));
1646  return Error::success();
1647  }
1648  if (Name == "function") {
1649  FunctionPassManager FPM(DebugLogging);
1650  if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1651  VerifyEachPass, DebugLogging))
1652  return Err;
1653  // Add the nested pass manager with the appropriate adaptor.
1654  CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1655  return Error::success();
1656  }
1657  if (auto Count = parseRepeatPassName(Name)) {
1658  CGSCCPassManager NestedCGPM(DebugLogging);
1659  if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1660  VerifyEachPass, DebugLogging))
1661  return Err;
1662  CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1663  return Error::success();
1664  }
1665  if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1666  CGSCCPassManager NestedCGPM(DebugLogging);
1667  if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1668  VerifyEachPass, DebugLogging))
1669  return Err;
1670  CGPM.addPass(
1671  createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1672  return Error::success();
1673  }
1674 
1675  for (auto &C : CGSCCPipelineParsingCallbacks)
1676  if (C(Name, CGPM, InnerPipeline))
1677  return Error::success();
1678 
1679  // Normal passes can't have pipelines.
1680  return make_error<StringError>(
1681  formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1683  }
1684 
1685 // Now expand the basic registered passes from the .inc file.
1686 #define CGSCC_PASS(NAME, CREATE_PASS) \
1687  if (Name == NAME) { \
1688  CGPM.addPass(CREATE_PASS); \
1689  return Error::success(); \
1690  }
1691 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1692  if (Name == "require<" NAME ">") { \
1693  CGPM.addPass(RequireAnalysisPass< \
1694  std::remove_reference<decltype(CREATE_PASS)>::type, \
1695  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1696  CGSCCUpdateResult &>()); \
1697  return Error::success(); \
1698  } \
1699  if (Name == "invalidate<" NAME ">") { \
1700  CGPM.addPass(InvalidateAnalysisPass< \
1701  std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1702  return Error::success(); \
1703  }
1704 #include "PassRegistry.def"
1705 
1706  for (auto &C : CGSCCPipelineParsingCallbacks)
1707  if (C(Name, CGPM, InnerPipeline))
1708  return Error::success();
1709  return make_error<StringError>(
1710  formatv("unknown cgscc pass '{0}'", Name).str(),
1712 }
1713 
1714 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1715  const PipelineElement &E,
1716  bool VerifyEachPass, bool DebugLogging) {
1717  auto &Name = E.Name;
1718  auto &InnerPipeline = E.InnerPipeline;
1719 
1720  // First handle complex passes like the pass managers which carry pipelines.
1721  if (!InnerPipeline.empty()) {
1722  if (Name == "function") {
1723  FunctionPassManager NestedFPM(DebugLogging);
1724  if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1725  VerifyEachPass, DebugLogging))
1726  return Err;
1727  // Add the nested pass manager with the appropriate adaptor.
1728  FPM.addPass(std::move(NestedFPM));
1729  return Error::success();
1730  }
1731  if (Name == "loop") {
1732  LoopPassManager LPM(DebugLogging);
1733  if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1734  DebugLogging))
1735  return Err;
1736  // Add the nested pass manager with the appropriate adaptor.
1737  FPM.addPass(
1738  createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
1739  return Error::success();
1740  }
1741  if (auto Count = parseRepeatPassName(Name)) {
1742  FunctionPassManager NestedFPM(DebugLogging);
1743  if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
1744  VerifyEachPass, DebugLogging))
1745  return Err;
1746  FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1747  return Error::success();
1748  }
1749 
1750  for (auto &C : FunctionPipelineParsingCallbacks)
1751  if (C(Name, FPM, InnerPipeline))
1752  return Error::success();
1753 
1754  // Normal passes can't have pipelines.
1755  return make_error<StringError>(
1756  formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1758  }
1759 
1760 // Now expand the basic registered passes from the .inc file.
1761 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1762  if (Name == NAME) { \
1763  FPM.addPass(CREATE_PASS); \
1764  return Error::success(); \
1765  }
1766 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1767  if (checkParametrizedPassName(Name, NAME)) { \
1768  auto Params = parsePassParameters(PARSER, Name, NAME); \
1769  if (!Params) \
1770  return Params.takeError(); \
1771  FPM.addPass(CREATE_PASS(Params.get())); \
1772  return Error::success(); \
1773  }
1774 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1775  if (Name == "require<" NAME ">") { \
1776  FPM.addPass( \
1777  RequireAnalysisPass< \
1778  std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1779  return Error::success(); \
1780  } \
1781  if (Name == "invalidate<" NAME ">") { \
1782  FPM.addPass(InvalidateAnalysisPass< \
1783  std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1784  return Error::success(); \
1785  }
1786 #include "PassRegistry.def"
1787 
1788  for (auto &C : FunctionPipelineParsingCallbacks)
1789  if (C(Name, FPM, InnerPipeline))
1790  return Error::success();
1791  return make_error<StringError>(
1792  formatv("unknown function pass '{0}'", Name).str(),
1794 }
1795 
1796 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1797  bool VerifyEachPass, bool DebugLogging) {
1798  StringRef Name = E.Name;
1799  auto &InnerPipeline = E.InnerPipeline;
1800 
1801  // First handle complex passes like the pass managers which carry pipelines.
1802  if (!InnerPipeline.empty()) {
1803  if (Name == "loop") {
1804  LoopPassManager NestedLPM(DebugLogging);
1805  if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1806  VerifyEachPass, DebugLogging))
1807  return Err;
1808  // Add the nested pass manager with the appropriate adaptor.
1809  LPM.addPass(std::move(NestedLPM));
1810  return Error::success();
1811  }
1812  if (auto Count = parseRepeatPassName(Name)) {
1813  LoopPassManager NestedLPM(DebugLogging);
1814  if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
1815  VerifyEachPass, DebugLogging))
1816  return Err;
1817  LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1818  return Error::success();
1819  }
1820 
1821  for (auto &C : LoopPipelineParsingCallbacks)
1822  if (C(Name, LPM, InnerPipeline))
1823  return Error::success();
1824 
1825  // Normal passes can't have pipelines.
1826  return make_error<StringError>(
1827  formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1829  }
1830 
1831 // Now expand the basic registered passes from the .inc file.
1832 #define LOOP_PASS(NAME, CREATE_PASS) \
1833  if (Name == NAME) { \
1834  LPM.addPass(CREATE_PASS); \
1835  return Error::success(); \
1836  }
1837 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1838  if (Name == "require<" NAME ">") { \
1839  LPM.addPass(RequireAnalysisPass< \
1840  std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1841  LoopAnalysisManager, LoopStandardAnalysisResults &, \
1842  LPMUpdater &>()); \
1843  return Error::success(); \
1844  } \
1845  if (Name == "invalidate<" NAME ">") { \
1846  LPM.addPass(InvalidateAnalysisPass< \
1847  std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1848  return Error::success(); \
1849  }
1850 #include "PassRegistry.def"
1851 
1852  for (auto &C : LoopPipelineParsingCallbacks)
1853  if (C(Name, LPM, InnerPipeline))
1854  return Error::success();
1855  return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1857 }
1858 
1859 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1860 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1861  if (Name == NAME) { \
1862  AA.registerModuleAnalysis< \
1863  std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1864  return true; \
1865  }
1866 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1867  if (Name == NAME) { \
1868  AA.registerFunctionAnalysis< \
1869  std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1870  return true; \
1871  }
1872 #include "PassRegistry.def"
1873 
1874  for (auto &C : AAParsingCallbacks)
1875  if (C(Name, AA))
1876  return true;
1877  return false;
1878 }
1879 
1880 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1881  ArrayRef<PipelineElement> Pipeline,
1882  bool VerifyEachPass,
1883  bool DebugLogging) {
1884  for (const auto &Element : Pipeline) {
1885  if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1886  return Err;
1887  // FIXME: No verifier support for Loop passes!
1888  }
1889  return Error::success();
1890 }
1891 
1892 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1893  ArrayRef<PipelineElement> Pipeline,
1894  bool VerifyEachPass,
1895  bool DebugLogging) {
1896  for (const auto &Element : Pipeline) {
1897  if (auto Err =
1898  parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1899  return Err;
1900  if (VerifyEachPass)
1901  FPM.addPass(VerifierPass());
1902  }
1903  return Error::success();
1904 }
1905 
1906 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1907  ArrayRef<PipelineElement> Pipeline,
1908  bool VerifyEachPass,
1909  bool DebugLogging) {
1910  for (const auto &Element : Pipeline) {
1911  if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1912  return Err;
1913  // FIXME: No verifier support for CGSCC passes!
1914  }
1915  return Error::success();
1916 }
1917 
1920  CGSCCAnalysisManager &CGAM,
1921  ModuleAnalysisManager &MAM) {
1922  MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1923  MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1924  CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1925  FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1926  FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1927  FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1928  LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1929 }
1930 
1931 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1932  ArrayRef<PipelineElement> Pipeline,
1933  bool VerifyEachPass,
1934  bool DebugLogging) {
1935  for (const auto &Element : Pipeline) {
1936  if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1937  return Err;
1938  if (VerifyEachPass)
1939  MPM.addPass(VerifierPass());
1940  }
1941  return Error::success();
1942 }
1943 
1944 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1945 // FIXME: Should this routine accept a TargetMachine or require the caller to
1946 // pre-populate the analysis managers with target-specific stuff?
1948  StringRef PipelineText,
1949  bool VerifyEachPass, bool DebugLogging) {
1950  auto Pipeline = parsePipelineText(PipelineText);
1951  if (!Pipeline || Pipeline->empty())
1952  return make_error<StringError>(
1953  formatv("invalid pipeline '{0}'", PipelineText).str(),
1955 
1956  // If the first name isn't at the module layer, wrap the pipeline up
1957  // automatically.
1958  StringRef FirstName = Pipeline->front().Name;
1959 
1960  if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1961  if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1962  Pipeline = {{"cgscc", std::move(*Pipeline)}};
1963  } else if (isFunctionPassName(FirstName,
1964  FunctionPipelineParsingCallbacks)) {
1965  Pipeline = {{"function", std::move(*Pipeline)}};
1966  } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
1967  Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1968  } else {
1969  for (auto &C : TopLevelPipelineParsingCallbacks)
1970  if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1971  return Error::success();
1972 
1973  // Unknown pass or pipeline name!
1974  auto &InnerPipeline = Pipeline->front().InnerPipeline;
1975  return make_error<StringError>(
1976  formatv("unknown {0} name '{1}'",
1977  (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1978  .str(),
1980  }
1981  }
1982 
1983  if (auto Err =
1984  parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1985  return Err;
1986  return Error::success();
1987 }
1988 
1989 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1991  StringRef PipelineText,
1992  bool VerifyEachPass, bool DebugLogging) {
1993  auto Pipeline = parsePipelineText(PipelineText);
1994  if (!Pipeline || Pipeline->empty())
1995  return make_error<StringError>(
1996  formatv("invalid pipeline '{0}'", PipelineText).str(),
1998 
1999  StringRef FirstName = Pipeline->front().Name;
2000  if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
2001  return make_error<StringError>(
2002  formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2003  PipelineText)
2004  .str(),
2006 
2007  if (auto Err =
2008  parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2009  return Err;
2010  return Error::success();
2011 }
2012 
2013 // Primary pass pipeline description parsing routine for a \c
2014 // FunctionPassManager
2016  StringRef PipelineText,
2017  bool VerifyEachPass, bool DebugLogging) {
2018  auto Pipeline = parsePipelineText(PipelineText);
2019  if (!Pipeline || Pipeline->empty())
2020  return make_error<StringError>(
2021  formatv("invalid pipeline '{0}'", PipelineText).str(),
2023 
2024  StringRef FirstName = Pipeline->front().Name;
2025  if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
2026  return make_error<StringError>(
2027  formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2028  PipelineText)
2029  .str(),
2031 
2032  if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2033  DebugLogging))
2034  return Err;
2035  return Error::success();
2036 }
2037 
2038 // Primary pass pipeline description parsing routine for a \c LoopPassManager
2040  StringRef PipelineText,
2041  bool VerifyEachPass, bool DebugLogging) {
2042  auto Pipeline = parsePipelineText(PipelineText);
2043  if (!Pipeline || Pipeline->empty())
2044  return make_error<StringError>(
2045  formatv("invalid pipeline '{0}'", PipelineText).str(),
2047 
2048  if (auto Err =
2049  parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2050  return Err;
2051 
2052  return Error::success();
2053 }
2054 
2056  // If the pipeline just consists of the word 'default' just replace the AA
2057  // manager with our default one.
2058  if (PipelineText == "default") {
2059  AA = buildDefaultAAPipeline();
2060  return Error::success();
2061  }
2062 
2063  while (!PipelineText.empty()) {
2064  StringRef Name;
2065  std::tie(Name, PipelineText) = PipelineText.split(',');
2066  if (!parseAAPassName(AA, Name))
2067  return make_error<StringError>(
2068  formatv("unknown alias analysis name '{0}'", Name).str(),
2070  }
2071 
2072  return Error::success();
2073 }
Super simple passes to force specific function attrs from the commandline into the IR for debugging p...
Defines passes for running instruction simplification across chunks of IR.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:152
Analysis pass providing a never-invalidated alias analysis result.
A set of parameters used to control various transforms performed by the LoopUnroll pass...
uint64_t CallInst * C
Computes function attributes in post-order over the call graph.
Definition: FunctionAttrs.h:51
A simple loop rotation transformation.
Definition: LoopRotation.h:24
A simple and fast domtree-based CSE pass.
Definition: EarlyCSE.h:31
The profile annotation (profile-instr-use) pass for IR based PGO.
Thresholds to tune inline cost analysis.
Definition: InlineCost.h:154
Interfaces for registering analysis passes, producing common pass manager configurations, and parsing of pass pipelines.
AAManager buildDefaultAAPipeline()
Build the default AAManager with the default alias analysis pipeline registered.
Eliminate dead arguments (and return values) from functions.
This is the interface for LLVM&#39;s inclusion-based alias analysis implemented with CFL graph reachabili...
This class represents lattice values for constants.
Definition: AllocatorList.h:24
static Optional< int > parseRepeatPassName(StringRef Name)
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
This is the interface to build a ModuleSummaryIndex for a module.
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition: GVN.h:306
InnerAnalysisManagerProxy< LoopAnalysisManager, Function > LoopAnalysisManagerFunctionProxy
A proxy from a LoopAnalysisManager to a Function.
Performs basic CFG simplifications to assist other loop passes.
This file provides the interface for LLVM&#39;s Scalar Replacement of Aggregates pass.
This file implements a simple N^2 alias analysis accuracy evaluator.
InnerAnalysisManagerProxy< CGSCCAnalysisManager, Module > CGSCCAnalysisManagerModuleProxy
A proxy from a CGSCCAnalysisManager to a Module.
Implements a lazy call graph analysis and related passes for the new pass manager.
RepeatedPass< PassT > createRepeatedPass(int Count, PassT P)
Definition: PassManager.h:1437
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
This is the interface for a metadata-based scoped no-alias analysis.
void registerModuleAnalysis()
Register a specific AA result.
LoopUnrollOptions & setUpperBound(bool UpperBound)
Enables or disables the use of trip count upper bound in loop unrolling.
ModuleToPostOrderCGSCCPassAdaptor< CGSCCPassT > createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
CGSCCToFunctionPassAdaptor< FunctionPassT > createCGSCCToFunctionPassAdaptor(FunctionPassT Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Pass to remove unused function declarations.
OptimizationLevel
LLVM-provided high-level optimization levels.
Definition: PassBuilder.h:98
ModulePassManager buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level, bool DebugLogging=false)
Build a pre-link, ThinLTO-targeting default optimization pipeline to a pass manager.
This file provides the interface for LLVM&#39;s PGO Instrumentation lowering pass.
OuterAnalysisManagerProxy< FunctionAnalysisManager, Loop, LoopStandardAnalysisResults & > FunctionAnalysisManagerLoopProxy
A proxy from a FunctionAnalysisManager to a Loop.
static cl::opt< bool > EnableEarlyCSEMemSSA("enable-npm-earlycse-memssa", cl::init(true), cl::Hidden, cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"))
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
F(f)
Loop unroll pass that only does full loop unrolling.
Loop unroll pass that will support both full and partial unrolling.
Pass to perform split of global variables.
Definition: GlobalSplit.h:27
This pass transforms loops that contain branches or switches on loop- invariant conditions to have mu...
A DCE pass that assumes instructions are dead until proven otherwise.
Definition: ADCE.h:32
static cl::opt< bool > EnableSyntheticCounts("enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, cl::desc("Run synthetic function entry count generation " "pass"))
A utility pass template to force an analysis result to be available.
Definition: PassManager.h:1349
static cl::opt< bool > EnableGVNHoist("enable-npm-gvn-hoist", cl::init(false), cl::Hidden, cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"))
Reassociate commutative expressions.
Definition: Reassociate.h:72
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
cl::opt< bool > EnableHotColdSplit
Run instruction simplification across each instruction in the function.
Pass to forward loads in a loop around the backedge to subsequent iterations.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool endswith(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:279
A pass that transforms external global definitions into declarations.
This pass handles simple speculating of instructions around PHIs when doing so is profitable for a pa...
A simple and fast domtree-based GVN pass to hoist common expressions from sibling branches...
Definition: GVN.h:299
amdgpu Simplify well known AMD library false Value Value const Twine & Name
This is the interface for a SCEV-based alias analysis.
ModulePassManager buildModuleSimplificationPipeline(OptimizationLevel Level, ThinLTOPhase Phase, bool DebugLogging=false)
Construct the core LLVM module canonicalization and simplification pipeline.
A pass to do RPO deduction and propagation of function attributes.
Definition: FunctionAttrs.h:70
Optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition: InlineCost.h:159
LLVM_ATTRIBUTE_ALWAYS_INLINE bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition: StringRef.h:689
Similar to O2 but tries to optimize for small code size instead of fast execution without triggering ...
Definition: PassBuilder.h:168
Instrumentation based profiling lowering pass.
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:822
static cl::opt< bool > EnableGVNSink("enable-npm-gvn-sink", cl::init(false), cl::Hidden, cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"))
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
Definition: PassManager.h:1121
Hoist/decompose integer division and remainder instructions to enable CFG improvements and better cod...
Definition: DivRemPairs.h:24
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE R Default(T Value)
Definition: StringSwitch.h:203
OuterAnalysisManagerProxy< CGSCCAnalysisManager, Function > CGSCCAnalysisManagerFunctionProxy
A proxy from a CGSCCAnalysisManager to a Function.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
Key
PAL metadata keys.
A very specialized mode that will optimize for code size at any and all costs.
Definition: PassBuilder.h:177
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
The sample profiler data loader pass.
Definition: SampleProfile.h:26
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
FunctionToLoopPassAdaptor< LoopPassT > createFunctionToLoopPassAdaptor(LoopPassT Pass, bool DebugLogging=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
LLVM_ATTRIBUTE_ALWAYS_INLINE bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:678
static bool isModulePassName(StringRef Name, CallbacksT &Callbacks)
falkor hwpf fix Falkor HW Prefetch Fix Late Phase
This file provides the interface for a simple, fast CSE pass.
This file provides the interface for the GCOV style profiler pass.
Performs Loop Invariant Code Motion Pass.
Definition: LICM.h:43
The core GVN pass object.
Definition: GVN.h:69
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM)
Cross register the analysis managers through their proxies.
Pass to remove unused function declarations.
Definition: GlobalDCE.h:30
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
A lazily constructed view of the call graph of a module.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
A pass that does profile-guided sinking of instructions into loops.
Definition: LoopSink.h:34
void registerFunctionAnalysis()
Register a specific AA result.
This class implements a trivial dead store elimination.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Argument promotion pass.
OuterAnalysisManagerProxy< ModuleAnalysisManager, LazyCallGraph::SCC, LazyCallGraph & > ModuleAnalysisManagerCGSCCProxy
A proxy from a ModuleAnalysisManager to an SCC.
LoopUnrollOptions & setPartial(bool Partial)
Enables or disables partial unrolling.
Pass to perform interprocedural constant propagation.
Definition: SCCP.h:31
A pass which infers function attributes from the names and signatures of function declarations in a m...
static cl::opt< unsigned > MaxDevirtIterations("pm-max-devirt-iterations", cl::ReallyHidden, cl::init(4))
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
This is the interface for LLVM&#39;s unification-based alias analysis implemented with CFL graph reachabi...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level)
static bool checkParametrizedPassName(StringRef Name, StringRef PassName)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
This is the interface for a metadata-based TBAA.
static Regex DefaultAliasRegex("^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$")
ModuleToFunctionPassAdaptor< FunctionPassT > createModuleToFunctionPassAdaptor(FunctionPassT Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
Definition: PassManager.h:1333
This file provides the interface for LLVM&#39;s Global Value Numbering pass which eliminates fully redund...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides the primary interface to the instcombine pass.
Disable as many optimizations as possible.
Definition: PassBuilder.h:102
FunctionPassManager buildFunctionSimplificationPipeline(OptimizationLevel Level, ThinLTOPhase Phase, bool DebugLogging=false)
Construct the core LLVM function canonicalization and simplification pipeline.
A manager for alias analyses.
ModulePassManager buildLTOPreLinkDefaultPipeline(OptimizationLevel Level, bool DebugLogging=false)
Build a pre-link, LTO-targeting default optimization pipeline to a pass manager.
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:383
static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks)
The inliner pass for the new pass manager.
Definition: Inliner.h:95
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
Analysis pass providing a never-invalidated alias analysis result.
This file provides the interface for LLVM&#39;s Global Value Numbering pass.
ThinLTOPhase
ThinLTO phase.
Definition: PassBuilder.h:85
Optimize for fast execution as much as possible.
Definition: PassBuilder.h:156
ModulePassManager buildModuleOptimizationPipeline(OptimizationLevel Level, bool DebugLogging=false)
Construct the core LLVM module optimization pipeline.
static cl::opt< bool > EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden, cl::desc("Enable control height reduction optimization (CHR)"))
DevirtSCCRepeatedPass< PassT > createDevirtSCCRepeatedPass(PassT Pass, int MaxIterations)
A function to deduce a function pass type and wrap it in the templated adaptor.
A simple loop rotation transformation.
static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks)
Tests whether registered callbacks will accept a given pass name.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
std::string InstrProfileOutput
size_t size() const
Definition: SmallVector.h:53
Create a verifier pass.
Definition: Verifier.h:137
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, const ModuleSummaryIndex *ImportSummary)
Build an ThinLTO default optimization pipeline to a pass manager.
static cl::opt< bool > EnableUnrollAndJam("enable-npm-unroll-and-jam", cl::init(false), cl::Hidden, cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"))
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:497
This file provides the interface for LLVM&#39;s Loop Data Prefetching Pass.
Provides passes to inlining "always_inline" functions.
This file provides the primary interface to the aggressive instcombine pass.
LoopUnrollOptions & setOptLevel(int O)
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
This header defines the LoopLoadEliminationPass object.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:327
InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options...
static Optional< int > parseDevirtPassName(StringRef Name)
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Definition: PassBuilder.h:140
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:727
This pass performs &#39;jump threading&#39;, which looks at blocks that have multiple predecessors and multip...
Definition: JumpThreading.h:78
A pass to simplify and canonicalize the CFG of a function.
Definition: SimplifyCFG.h:30
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText, bool VerifyEachPass=true, bool DebugLogging=false)
Parse a textual pass pipeline description into a ModulePassManager.
static InlineParams getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level)
The instrumentation (profile-instr-gen) pass for IR based PGO.
This pass converts vector operations into scalar operations, in order to expose optimization opportun...
A pass that merges duplicate global constants into a single constant.
Definition: ConstantMerge.h:30
Analysis pass providing a never-invalidated alias analysis result.
Options for the frontend instrumentation based profiling pass.
LLVM_ATTRIBUTE_ALWAYS_INLINE StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:70
This pass performs merges of loads and stores on both sides of a.
The indirect function call promotion pass.
Interfaces for passes which infer implicit function attributes from the name and signature of functio...
Analysis pass providing a never-invalidated alias analysis result.
LoopUnrollOptions & setRuntime(bool Runtime)
Enables or disables unrolling of loops with runtime trip count.
static const size_t npos
Definition: StringRef.h:51
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:465
Pass which forces specific function attributes into the IR, primarily as a debugging tool...
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:395
The header file for the LowerExpectIntrinsic pass as used by the new pass manager.
Pass to outline cold regions.
Provides passes for computing function attributes based on interprocedural analyses.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
Definition: PassManager.h:1250
This header provides classes for managing passes over SCCs of the call graph.
This file defines passes to print out IR in various granularities.
void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
static bool startsWithDefaultPipelineAliasPrefix(StringRef Name)
Tests whether a pass name starts with a valid prefix for a default pipeline alias.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file provides the interface for LLVM&#39;s Call Graph Profile pass.
Optimize quickly without destroying debuggability.
Definition: PassBuilder.h:122
The profile size based optimization pass for memory intrinsics.
See the comments on JumpThreadingPass.
An SCC of the call graph.
static const char * name
Performs Loop Inst Simplify Pass.
The LoopVectorize Pass.
Definition: LoopVectorize.h:80
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks)
bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr)
matches - Match the regex against a given String.
Definition: Regex.cpp:73
An optimization pass providing Scalar Replacement of Aggregates.
Definition: SROA.h:66
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, bool DebugLogging=false)
Build a per-module default optimization pipeline.
A container for analyses that lazily runs them and caches their results.
static cl::opt< bool > RunPartialInlining("enable-npm-partial-inlining", cl::init(false), cl::Hidden, cl::ZeroOrMore, cl::desc("Run Partial inlinining pass"))
A set of parameters used to control the transforms in the SimplifyCFG pass.
Definition: Local.h:65
void addPass(PassT Pass)
Definition: PassManager.h:542
This pass exposes codegen information to IR-level passes.
This pass performs function-level constant propagation and merging.
Definition: SCCP.h:37
This header defines various interfaces for pass management in LLVM.
LoopUnrollOptions & setPeeling(bool Peeling)
Enables or disables loop peeling.
static cl::opt< bool > RunNewGVN("enable-npm-newgvn", cl::init(false), cl::Hidden, cl::ZeroOrMore, cl::desc("Run NewGVN instead of GVN"))
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:71
This file provides the interface for the sampled PGO loader pass.
Optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition: InlineCost.h:171
int DefaultThreshold
The default threshold to start with for a callee.
Definition: InlineCost.h:156
Optimize globals that never have their address taken.
Definition: GlobalOpt.h:26
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
Performs Loop Idiom Recognize Pass.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:78
static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks)