LLVM 23.0.0git
PassBuilderPipelines.cpp
Go to the documentation of this file.
1//===- Construction of pass pipelines -------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
14///
15//===----------------------------------------------------------------------===//
16
17#include "llvm/ADT/Statistic.h"
29#include "llvm/IR/PassManager.h"
30#include "llvm/IR/Verifier.h"
31#include "llvm/Pass.h"
160
161using namespace llvm;
162
163namespace llvm {
164
166 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
167 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
169 "Heuristics-based inliner version"),
171 "Use development mode (runtime-loadable model)"),
173 "Use release mode (AOT-compiled model)")));
174
175/// Flag to enable inline deferral during PGO.
176static cl::opt<bool>
177 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
179 cl::desc("Enable inline deferral during PGO"));
180
181static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
182 cl::init(false), cl::Hidden,
183 cl::desc("Enable module inliner"));
184
186 "mandatory-inlining-first", cl::init(false), cl::Hidden,
187 cl::desc("Perform mandatory inlinings module-wide, before performing "
188 "inlining"));
189
191 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
192 cl::desc("Eagerly invalidate more analyses in default pipelines"));
193
195 "enable-merge-functions", cl::init(false), cl::Hidden,
196 cl::desc("Enable function merging as part of the optimization pipeline"));
197
199 "enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden,
200 cl::desc("Run the loop rotation transformation after PGO instrumentation"));
201
202static cl::opt<bool>
203 TriggerCrash("opt-pipeline-trigger-crash", cl::init(false), cl::Hidden,
204 cl::desc("Trigger crash in optimization pipeline"));
205
207 "enable-global-analyses", cl::init(true), cl::Hidden,
208 cl::desc("Enable inter-procedural analyses"));
209
210static cl::opt<bool> RunPartialInlining("enable-partial-inlining",
211 cl::init(false), cl::Hidden,
212 cl::desc("Run Partial inlining pass"));
213
215 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
216 cl::desc("Run cleanup optimization passes after vectorization"));
217
218static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
219 cl::desc("Run the NewGVN pass"));
220
221static cl::opt<bool>
222 EnableLoopInterchange("enable-loopinterchange", cl::init(true), cl::Hidden,
223 cl::desc("Enable the LoopInterchange Pass"));
224
225static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
226 cl::init(false), cl::Hidden,
227 cl::desc("Enable Unroll And Jam Pass"));
228
229static cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
231 cl::desc("Enable the LoopFlatten Pass"));
232
233static cl::opt<bool>
234 EnableInstrumentor("enable-instrumentor", cl::init(false), cl::Hidden,
235 cl::desc("Enable the Instrumentor Pass"));
236
237static cl::opt<bool>
238 EnableDFAJumpThreading("enable-dfa-jump-thread",
239 cl::desc("Enable DFA jump threading"),
240 cl::init(true), cl::Hidden);
241
242static cl::opt<bool>
243 EnableHotColdSplit("hot-cold-split",
244 cl::desc("Enable hot-cold splitting pass"));
245
246static cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false),
248 cl::desc("Enable ir outliner pass"));
249
250static cl::opt<bool>
251 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
252 cl::desc("Disable pre-instrumentation inliner"));
253
255 "preinline-threshold", cl::Hidden, cl::init(75),
256 cl::desc("Control the amount of inlining in pre-instrumentation inliner "
257 "(default = 75)"));
258
259static cl::opt<bool>
260 EnableGVNHoist("enable-gvn-hoist",
261 cl::desc("Enable the GVN hoisting pass (default = off)"));
262
263static cl::opt<bool>
264 EnableGVNSink("enable-gvn-sink",
265 cl::desc("Enable the GVN sinking pass (default = off)"));
266
268 "enable-jump-table-to-switch", cl::init(true),
269 cl::desc("Enable JumpTableToSwitch pass (default = true)"));
270
271// This option is used in simplifying testing SampleFDO optimizations for
272// profile loading.
273static cl::opt<bool>
274 EnableCHR("enable-chr", cl::init(true), cl::Hidden,
275 cl::desc("Enable control height reduction optimization (CHR)"));
276
278 "flattened-profile-used", cl::init(false), cl::Hidden,
279 cl::desc("Indicate the sample profile being used is flattened, i.e., "
280 "no inline hierarchy exists in the profile"));
281
282static cl::opt<bool>
283 EnableMatrix("enable-matrix", cl::init(false), cl::Hidden,
284 cl::desc("Enable lowering of the matrix intrinsics"));
285
287 "enable-mergeicmps", cl::init(true), cl::Hidden,
288 cl::desc("Enable MergeICmps pass in the optimization pipeline"));
289
291 "enable-constraint-elimination", cl::init(true), cl::Hidden,
292 cl::desc(
293 "Enable pass to eliminate conditions based on linear constraints"));
294
296 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
297 cl::desc("Enable the attributor inter-procedural deduction pass"),
299 "enable all full attributor runs"),
301 "enable all attributor-light runs"),
303 "enable module-wide attributor runs"),
305 "enable module-wide attributor-light runs"),
307 "enable call graph SCC attributor runs"),
309 "enable call graph SCC attributor-light runs"),
310 clEnumValN(AttributorRunOption::NONE, "none",
311 "disable attributor runs")));
312
314 "enable-sampled-instrumentation", cl::init(false), cl::Hidden,
315 cl::desc("Enable profile instrumentation sampling (default = off)"));
317 "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
318 cl::desc("Enable the experimental Loop Versioning LICM pass"));
319
321 "instrument-cold-function-only-path", cl::init(""),
322 cl::desc("File path for cold function only instrumentation(requires use "
323 "with --pgo-instrument-cold-function-only)"),
324 cl::Hidden);
325
326// TODO: There is a similar flag in WPD pass, we should consolidate them by
327// parsing the option only once in PassBuilder and share it across both places.
329 "enable-devirtualize-speculatively",
330 cl::desc("Enable speculative devirtualization optimization"),
331 cl::init(false));
332
335
337} // namespace llvm
338
356
357namespace llvm {
359} // namespace llvm
360
362 OptimizationLevel Level) {
363 for (auto &C : PeepholeEPCallbacks)
364 C(FPM, Level);
365}
368 for (auto &C : LateLoopOptimizationsEPCallbacks)
369 C(LPM, Level);
370}
372 OptimizationLevel Level) {
373 for (auto &C : LoopOptimizerEndEPCallbacks)
374 C(LPM, Level);
375}
378 for (auto &C : ScalarOptimizerLateEPCallbacks)
379 C(FPM, Level);
380}
382 OptimizationLevel Level) {
383 for (auto &C : CGSCCOptimizerLateEPCallbacks)
384 C(CGPM, Level);
385}
387 OptimizationLevel Level) {
388 for (auto &C : VectorizerStartEPCallbacks)
389 C(FPM, Level);
390}
392 OptimizationLevel Level) {
393 for (auto &C : VectorizerEndEPCallbacks)
394 C(FPM, Level);
395}
397 OptimizationLevel Level,
399 for (auto &C : OptimizerEarlyEPCallbacks)
400 C(MPM, Level, Phase);
401}
403 OptimizationLevel Level,
405 for (auto &C : OptimizerLastEPCallbacks)
406 C(MPM, Level, Phase);
407}
410 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
411 C(MPM, Level);
412}
415 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
416 C(MPM, Level);
417}
419 OptimizationLevel Level) {
420 for (auto &C : PipelineStartEPCallbacks)
421 C(MPM, Level);
422}
425 for (auto &C : PipelineEarlySimplificationEPCallbacks)
426 C(MPM, Level, Phase);
427}
428
429// Get IR stats with InstCount before/after the optimization pipeline
431 bool IsPreOptimization) {
432 if (AreStatisticsEnabled()) {
433 MPM.addPass(
436 FunctionPropertiesStatisticsPass(IsPreOptimization)));
437 }
438}
439
440// Helper to add AnnotationRemarksPass.
444
445// Helper to check if the current compilation phase is preparing for LTO
450
451// Helper to check if the current compilation phase is preparing for FullLTO
452[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
454}
455
456// Helper to check if the current compilation phase is preparing for ThinLTO
460
461// Helper to check if the current compilation phase is LTO backend
466
467// Helper to check if the current compilation phase is FullLTO backend
471
472// Helper to check if the current compilation phase is ThinLTO backend
476
477// Helper to wrap conditionally Coro passes.
479 // TODO: Skip passes according to Phase.
480 ModulePassManager CoroPM;
481 CoroPM.addPass(CoroEarlyPass());
482 CGSCCPassManager CGPM;
483 CGPM.addPass(CoroSplitPass());
484 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
485 CoroPM.addPass(CoroCleanupPass());
486 CoroPM.addPass(GlobalDCEPass());
487 return CoroConditionalWrapper(std::move(CoroPM));
488}
489
490// TODO: Investigate the cost/benefit of tail call elimination on debugging.
492PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
494
496
498 FPM.addPass(CountVisitsPass());
499
500 // Form SSA out of local memory accesses after breaking apart aggregates into
501 // scalars.
502 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
503
504 // Catch trivial redundancies
505 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
506
507 // Hoisting of scalars and load expressions.
508 FPM.addPass(
509 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
510 FPM.addPass(InstCombinePass());
511
512 FPM.addPass(LibCallsShrinkWrapPass());
513
514 invokePeepholeEPCallbacks(FPM, Level);
515
516 FPM.addPass(
517 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
518
519 // Form canonically associated expression trees, and simplify the trees using
520 // basic mathematical properties. For example, this will form (nearly)
521 // minimal multiplication trees.
522 FPM.addPass(ReassociatePass());
523
524 // Add the primary loop simplification pipeline.
525 // FIXME: Currently this is split into two loop pass pipelines because we run
526 // some function passes in between them. These can and should be removed
527 // and/or replaced by scheduling the loop pass equivalents in the correct
528 // positions. But those equivalent passes aren't powerful enough yet.
529 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
530 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
531 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
532 // `LoopInstSimplify`.
533 LoopPassManager LPM1, LPM2;
534
535 // Simplify the loop body. We do this initially to clean up after other loop
536 // passes run, either when iterating on a loop or on inner loops with
537 // implications on the outer loop.
538 LPM1.addPass(LoopInstSimplifyPass());
539 LPM1.addPass(LoopSimplifyCFGPass());
540
541 // Try to remove as much code from the loop header as possible,
542 // to reduce amount of IR that will have to be duplicated. However,
543 // do not perform speculative hoisting the first time as LICM
544 // will destroy metadata that may not need to be destroyed if run
545 // after loop rotation.
546 // TODO: Investigate promotion cap for O1.
547 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
548 /*AllowSpeculation=*/false));
549
550 LPM1.addPass(
551 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
552 // TODO: Investigate promotion cap for O1.
553 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
554 /*AllowSpeculation=*/true));
555 LPM1.addPass(SimpleLoopUnswitchPass());
557 LPM1.addPass(LoopFlattenPass());
558
559 LPM2.addPass(LoopIdiomRecognizePass());
560 LPM2.addPass(IndVarSimplifyPass());
561
563
564 LPM2.addPass(LoopDeletionPass());
565
566 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
567 // because it changes IR to makes profile annotation in back compile
568 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
569 // attributes so we need to make sure and allow the full unroll pass to pay
570 // attention to it.
571 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
572 PGOOpt->Action != PGOOptions::SampleUse)
573 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
574 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
575 PTO.ForgetAllSCEVInLoopUnroll));
576
578
579 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
580 /*UseMemorySSA=*/true));
581 FPM.addPass(
582 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
583 FPM.addPass(InstCombinePass());
584 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
585 // *All* loop passes must preserve it, in order to be able to use it.
586 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
587 /*UseMemorySSA=*/false));
588
589 // Delete small array after loop unroll.
590 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
591
592 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
593 FPM.addPass(MemCpyOptPass());
594
595 // Sparse conditional constant propagation.
596 // FIXME: It isn't clear why we do this *after* loop passes rather than
597 // before...
598 FPM.addPass(SCCPPass());
599
600 // Delete dead bit computations (instcombine runs after to fold away the dead
601 // computations, and then ADCE will run later to exploit any new DCE
602 // opportunities that creates).
603 FPM.addPass(BDCEPass());
604
605 // Run instcombine after redundancy and dead bit elimination to exploit
606 // opportunities opened up by them.
607 FPM.addPass(InstCombinePass());
608 invokePeepholeEPCallbacks(FPM, Level);
609
610 FPM.addPass(CoroElidePass());
611
613
614 // Finally, do an expensive DCE pass to catch all the dead code exposed by
615 // the simplifications and basic cleanup after all the simplifications.
616 // TODO: Investigate if this is too expensive.
617 FPM.addPass(ADCEPass());
618 FPM.addPass(
619 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
620 FPM.addPass(InstCombinePass());
621 invokePeepholeEPCallbacks(FPM, Level);
622
623 return FPM;
624}
625
629 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
630
631 // The O1 pipeline has a separate pipeline creation function to simplify
632 // construction readability.
633 if (Level.getSpeedupLevel() == 1)
634 return buildO1FunctionSimplificationPipeline(Level, Phase);
635
637
640
641 // Form SSA out of local memory accesses after breaking apart aggregates into
642 // scalars.
644
645 // Catch trivial redundancies
646 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
649
650 // Hoisting of scalars and load expressions.
651 if (EnableGVNHoist)
652 FPM.addPass(GVNHoistPass());
653
654 // Global value numbering based sinking.
655 if (EnableGVNSink) {
656 FPM.addPass(GVNSinkPass());
657 FPM.addPass(
658 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
659 }
660
661 // Speculative execution if the target has divergent branches; otherwise nop.
662 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
663
664 // Optimize based on known information about branches, and cleanup afterward.
667
668 // Jump table to switch conversion.
671
672 FPM.addPass(
673 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
677
678 invokePeepholeEPCallbacks(FPM, Level);
679
680 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
681 // using the size value profile. Don't perform this when optimizing for size.
682 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
684
685 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
686 isInstrumentedPGOUse()));
687 FPM.addPass(
688 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
689
690 // Form canonically associated expression trees, and simplify the trees using
691 // basic mathematical properties. For example, this will form (nearly)
692 // minimal multiplication trees.
694
697
698 // Add the primary loop simplification pipeline.
699 // FIXME: Currently this is split into two loop pass pipelines because we run
700 // some function passes in between them. These can and should be removed
701 // and/or replaced by scheduling the loop pass equivalents in the correct
702 // positions. But those equivalent passes aren't powerful enough yet.
703 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
704 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
705 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
706 // `LoopInstSimplify`.
707 LoopPassManager LPM1, LPM2;
708
709 // Simplify the loop body. We do this initially to clean up after other loop
710 // passes run, either when iterating on a loop or on inner loops with
711 // implications on the outer loop.
712 LPM1.addPass(LoopInstSimplifyPass());
713 LPM1.addPass(LoopSimplifyCFGPass());
714
715 // Try to remove as much code from the loop header as possible,
716 // to reduce amount of IR that will have to be duplicated. However,
717 // do not perform speculative hoisting the first time as LICM
718 // will destroy metadata that may not need to be destroyed if run
719 // after loop rotation.
720 // TODO: Investigate promotion cap for O1.
721 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
722 /*AllowSpeculation=*/false));
723
724 LPM1.addPass(
725 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
726 // TODO: Investigate promotion cap for O1.
727 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
728 /*AllowSpeculation=*/true));
729 LPM1.addPass(
730 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
732 LPM1.addPass(LoopFlattenPass());
733
734 LPM2.addPass(LoopIdiomRecognizePass());
735 LPM2.addPass(IndVarSimplifyPass());
736
737 {
739 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
741 LPM2.addPass(std::move(ExtraPasses));
742 }
743
745
746 LPM2.addPass(LoopDeletionPass());
747
748 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
749 // because it changes IR to makes profile annotation in back compile
750 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
751 // attributes so we need to make sure and allow the full unroll pass to pay
752 // attention to it.
753 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
754 PGOOpt->Action != PGOOptions::SampleUse)
755 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
756 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
757 PTO.ForgetAllSCEVInLoopUnroll));
758
760
761 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
762 /*UseMemorySSA=*/true));
763 FPM.addPass(
764 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
766 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
767 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
768 // *All* loop passes must preserve it, in order to be able to use it.
769 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
770 /*UseMemorySSA=*/false));
771
772 // Delete small array after loop unroll.
774
775 // Try vectorization/scalarization transforms that are both improvements
776 // themselves and can allow further folds with GVN and InstCombine.
777 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
778
779 // Eliminate redundancies.
781 if (RunNewGVN)
782 FPM.addPass(NewGVNPass());
783 else
784 FPM.addPass(GVNPass());
785
786 // Sparse conditional constant propagation.
787 // FIXME: It isn't clear why we do this *after* loop passes rather than
788 // before...
789 FPM.addPass(SCCPPass());
790
791 // Delete dead bit computations (instcombine runs after to fold away the dead
792 // computations, and then ADCE will run later to exploit any new DCE
793 // opportunities that creates).
794 FPM.addPass(BDCEPass());
795
796 // Run instcombine after redundancy and dead bit elimination to exploit
797 // opportunities opened up by them.
799 invokePeepholeEPCallbacks(FPM, Level);
800
801 // Re-consider control flow based optimizations after redundancy elimination,
802 // redo DCE, etc.
805
808
809 // Finally, do an expensive DCE pass to catch all the dead code exposed by
810 // the simplifications and basic cleanup after all the simplifications.
811 // TODO: Investigate if this is too expensive.
812 FPM.addPass(ADCEPass());
813
814 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
815 FPM.addPass(MemCpyOptPass());
816
817 FPM.addPass(DSEPass());
819
821 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
822 /*AllowSpeculation=*/true),
823 /*UseMemorySSA=*/true));
824
825 FPM.addPass(CoroElidePass());
826
828
830 .convertSwitchRangeToICmp(true)
831 .convertSwitchToArithmetic(true)
832 .hoistCommonInsts(true)
833 .sinkCommonInsts(true)));
835 invokePeepholeEPCallbacks(FPM, Level);
836
837 return FPM;
838}
839
840void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
843 MPM.addPass(AssignGUIDPass());
844}
845
846void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
847 OptimizationLevel Level,
848 ThinOrFullLTOPhase LTOPhase) {
849 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
851 return;
852 InlineParams IP;
853
855
856 // FIXME: The hint threshold has the same value used by the regular inliner
857 // when not optimzing for size. This should probably be lowered after
858 // performance testing.
859 // FIXME: this comment is cargo culted from the old pass manager, revisit).
860 IP.HintThreshold = 325;
863 IP, /* MandatoryFirst */ true,
865 CGSCCPassManager &CGPipeline = MIWP.getPM();
866
868 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
869 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
870 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
871 true))); // Merge & remove basic blocks.
872 FPM.addPass(InstCombinePass()); // Combine silly sequences.
873 invokePeepholeEPCallbacks(FPM, Level);
874
875 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
876 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
877
878 MPM.addPass(std::move(MIWP));
879
880 // Delete anything that is now dead to make sure that we don't instrument
881 // dead code. Instrumentation can end up keeping dead code around and
882 // dramatically increase code size.
883 MPM.addPass(GlobalDCEPass());
884}
885
886void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
887 OptimizationLevel Level) {
889 // Disable header duplication in loop rotation at -Oz.
891 createFunctionToLoopPassAdaptor(LoopRotatePass(),
892 /*UseMemorySSA=*/false),
893 PTO.EagerlyInvalidateAnalyses));
894 }
895}
896
897void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
898 OptimizationLevel Level, bool RunProfileGen,
899 bool IsCS, bool AtomicCounterUpdate,
900 std::string ProfileFile,
901 std::string ProfileRemappingFile) {
902 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
903
904 if (!RunProfileGen) {
905 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
906 MPM.addPass(
907 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
908 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
909 // RequireAnalysisPass for PSI before subsequent non-module passes.
910 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
911 return;
912 }
913
914 // Perform PGO instrumentation.
915 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
917
918 addPostPGOLoopRotation(MPM, Level);
919 // Add the profile lowering pass.
920 InstrProfOptions Options;
921 if (!ProfileFile.empty())
922 Options.InstrProfileOutput = ProfileFile;
923 // Do counter promotion at Level greater than O0.
924 Options.DoCounterPromotion = true;
925 Options.UseBFIInPromotion = IsCS;
926 if (EnableSampledInstr) {
927 Options.Sampling = true;
928 // With sampling, there is little beneifit to enable counter promotion.
929 // But note that sampling does work with counter promotion.
930 Options.DoCounterPromotion = false;
931 }
932 Options.Atomic = AtomicCounterUpdate;
933 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
934}
935
937 bool RunProfileGen, bool IsCS,
938 bool AtomicCounterUpdate,
939 std::string ProfileFile,
940 std::string ProfileRemappingFile) {
941 if (!RunProfileGen) {
942 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
943 MPM.addPass(
944 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
945 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
946 // RequireAnalysisPass for PSI before subsequent non-module passes.
948 return;
949 }
950
951 // Perform PGO instrumentation.
954 // Add the profile lowering pass.
956 if (!ProfileFile.empty())
957 Options.InstrProfileOutput = ProfileFile;
958 // Do not do counter promotion at O0.
959 Options.DoCounterPromotion = false;
960 Options.UseBFIInPromotion = IsCS;
961 Options.Atomic = AtomicCounterUpdate;
963}
964
966 return getInlineParamsFromOptLevel(Level.getSpeedupLevel());
967}
968
972 InlineParams IP;
973 if (PTO.InlinerThreshold == -1)
975 else
976 IP = getInlineParams(PTO.InlinerThreshold);
977 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
978 // set hot-caller threshold to 0 to disable hot
979 // callsite inline (as much as possible [1]) because it makes
980 // profile annotation in the backend inaccurate.
981 //
982 // [1] Note the cost of a function could be below zero due to erased
983 // prologue / epilogue.
984 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
986
987 if (PGOOpt)
989
993
994 // Require the GlobalsAA analysis for the module so we can query it within
995 // the CGSCC pipeline.
997 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
998 // Invalidate AAManager so it can be recreated and pick up the newly
999 // available GlobalsAA.
1000 MIWP.addModulePass(
1002 }
1003
1004 // Require the ProfileSummaryAnalysis for the module so we can query it within
1005 // the inliner pass.
1007
1008 // Now begin the main postorder CGSCC pipeline.
1009 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
1010 // manager and trying to emulate its precise behavior. Much of this doesn't
1011 // make a lot of sense and we should revisit the core CGSCC structure.
1012 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
1013
1014 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1015 // generally clean up exception handling overhead. It isn't clear this is
1016 // valuable as the inliner doesn't currently care whether it is inlining an
1017 // invoke or a call.
1018
1020 MainCGPipeline.addPass(AttributorCGSCCPass());
1022 MainCGPipeline.addPass(AttributorLightCGSCCPass());
1023
1024 // Deduce function attributes. We do another run of this after the function
1025 // simplification pipeline, so this only needs to run when it could affect the
1026 // function simplification pipeline, which is only the case with recursive
1027 // functions.
1028 MainCGPipeline.addPass(PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
1029
1030 // When at O3 add argument promotion to the pass pipeline.
1031 // FIXME: It isn't at all clear why this should be limited to O3.
1032 if (Level == OptimizationLevel::O3)
1033 MainCGPipeline.addPass(ArgumentPromotionPass());
1034
1035 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1036 // there are no OpenMP runtime calls present in the module.
1037 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
1038 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
1039
1040 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
1041
1042 // Add the core function simplification pipeline nested inside the
1043 // CGSCC walk.
1046 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
1047
1048 // Finally, deduce any function attributes based on the fully simplified
1049 // function.
1050 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
1051
1052 // Mark that the function is fully simplified and that it shouldn't be
1053 // simplified again if we somehow revisit it due to CGSCC mutations unless
1054 // it's been modified since.
1057
1058 if (!isThinLTOPreLink(Phase)) {
1059 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
1060 MainCGPipeline.addPass(CoroAnnotationElidePass());
1061 }
1062
1063 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
1064 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
1066
1067 return MIWP;
1068}
1069
1074
1076 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
1077 // set hot-caller threshold to 0 to disable hot
1078 // callsite inline (as much as possible [1]) because it makes
1079 // profile annotation in the backend inaccurate.
1080 //
1081 // [1] Note the cost of a function could be below zero due to erased
1082 // prologue / epilogue.
1083 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1084 IP.HotCallSiteThreshold = 0;
1085
1086 if (PGOOpt)
1088
1089 // The inline deferral logic is used to avoid losing some
1090 // inlining chance in future. It is helpful in SCC inliner, in which
1091 // inlining is processed in bottom-up order.
1092 // While in module inliner, the inlining order is a priority-based order
1093 // by default. The inline deferral is unnecessary there. So we disable the
1094 // inline deferral logic in module inliner.
1095 IP.EnableDeferral = false;
1096
1099 MPM.addPass(GlobalOptPass());
1100 MPM.addPass(GlobalDCEPass());
1101 MPM.addPass(AssignGUIDPass());
1102 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
1103 }
1104
1107 PTO.EagerlyInvalidateAnalyses));
1108
1109 if (!isThinLTOPreLink(Phase)) {
1112 MPM.addPass(
1114 }
1115
1116 return MPM;
1117}
1118
1122 assert(Level != OptimizationLevel::O0 &&
1123 "Should not be used for O0 pipeline");
1124
1126 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1127
1129
1130 // Place pseudo probe instrumentation as the first pass of the pipeline to
1131 // minimize the impact of optimization changes.
1132 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1134
1135 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1136
1137 // In ThinLTO mode, when flattened profile is used, all the available
1138 // profile information will be annotated in PreLink phase so there is
1139 // no need to load the profile again in PostLink.
1140 bool LoadSampleProfile =
1141 HasSampleProfile && !(FlattenedProfileUsed && isThinLTOPostLink(Phase));
1142
1143 // During the ThinLTO backend phase we perform early indirect call promotion
1144 // here, before globalopt. Otherwise imported available_externally functions
1145 // look unreferenced and are removed. If we are going to load the sample
1146 // profile then defer until later.
1147 // TODO: See if we can move later and consolidate with the location where
1148 // we perform ICP when we are loading a sample profile.
1149 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1150 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1151 // determine whether the new direct calls are annotated with prof metadata.
1152 // Ideally this should be determined from whether the IR is annotated with
1153 // sample profile, and not whether the a sample profile was provided on the
1154 // command line. E.g. for flattened profiles where we will not be reloading
1155 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1156 // provide the sample profile file.
1157 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1158 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1159
1160 // Create an early function pass manager to cleanup the output of the
1161 // frontend. Not necessary with LTO post link pipelines since the pre link
1162 // pipeline already cleaned up the frontend output.
1163 if (!isThinLTOPostLink(Phase)) {
1164 // Do basic inference of function attributes from known properties of system
1165 // libraries and other oracles.
1167 MPM.addPass(CoroEarlyPass());
1168
1169 FunctionPassManager EarlyFPM;
1170 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1171 // Lower llvm.expect to metadata before attempting transforms.
1172 // Compare/branch metadata may alter the behavior of passes like
1173 // SimplifyCFG.
1175 EarlyFPM.addPass(SimplifyCFGPass());
1177 EarlyFPM.addPass(EarlyCSEPass());
1178 if (Level == OptimizationLevel::O3)
1179 EarlyFPM.addPass(CallSiteSplittingPass());
1181 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1182 }
1183
1184 if (LoadSampleProfile) {
1185 // Annotate sample profile right after early FPM to ensure freshness of
1186 // the debug info.
1188 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1189 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1190 // RequireAnalysisPass for PSI before subsequent non-module passes.
1192 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1193 // for the profile annotation to be accurate in the LTO backend.
1194 if (!isLTOPreLink(Phase))
1195 // We perform early indirect call promotion here, before globalopt.
1196 // This is important for the ThinLTO backend phase because otherwise
1197 // imported available_externally functions look unreferenced and are
1198 // removed.
1199 MPM.addPass(
1200 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1201 }
1202
1203 // Try to perform OpenMP specific optimizations on the module. This is a
1204 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1206
1208 MPM.addPass(AttributorPass());
1211
1212 // Lower type metadata and the type.test intrinsic in the ThinLTO
1213 // post link pipeline after ICP. This is to enable usage of the type
1214 // tests in ICP sequences.
1217
1219
1220 // Interprocedural constant propagation now that basic cleanup has occurred
1221 // and prior to optimizing globals.
1222 // FIXME: This position in the pipeline hasn't been carefully considered in
1223 // years, it should be re-analyzed.
1224 MPM.addPass(
1225 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1226
1227 // Attach metadata to indirect call sites indicating the set of functions
1228 // they may target at run-time. This should follow IPSCCP.
1230
1231 // Optimize globals to try and fold them into constants.
1232 MPM.addPass(GlobalOptPass());
1233
1234 // Create a small function pass pipeline to cleanup after all the global
1235 // optimizations.
1236 FunctionPassManager GlobalCleanupPM;
1237 // FIXME: Should this instead by a run of SROA?
1238 GlobalCleanupPM.addPass(PromotePass());
1239 GlobalCleanupPM.addPass(InstCombinePass());
1240 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1241 GlobalCleanupPM.addPass(
1242 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1243 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1244 PTO.EagerlyInvalidateAnalyses));
1245
1246 // We already asserted this happens in non-FullLTOPostLink earlier.
1247 const bool IsPreLink = !isThinLTOPostLink(Phase);
1248 // Enable contextual profiling instrumentation.
1249 const bool IsCtxProfGen =
1251 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1252 const bool IsPGOInstrGen =
1253 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1254 const bool IsPGOInstrUse =
1255 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1256 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1257 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1258 // enable ctx profiling from the frontend.
1260 "Enabling both instrumented PGO and contextual instrumentation is not "
1261 "supported.");
1262 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1263
1264 assert(
1266 "--instrument-cold-function-only-path is provided but "
1267 "--pgo-instrument-cold-function-only is not enabled");
1268 const bool IsColdFuncOnlyInstrGen = PGOInstrumentColdFunctionOnly &&
1269 IsPGOPreLink &&
1271
1272 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1273 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1274 addPreInlinerPasses(MPM, Level, Phase);
1275
1276 // Add all the requested passes for instrumentation PGO, if requested.
1277 if (IsPGOInstrGen || IsPGOInstrUse) {
1278 addPGOInstrPasses(MPM, Level,
1279 /*RunProfileGen=*/IsPGOInstrGen,
1280 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1281 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1282 } else if (IsCtxProfGen || IsCtxProfUse) {
1284 // In pre-link, we just want the instrumented IR. We use the contextual
1285 // profile in the post-thinlink phase.
1286 // The instrumentation will be removed in post-thinlink after IPO.
1287 if (IsCtxProfUse) {
1288 MPM.addPass(AssignGUIDPass());
1289 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1290 return MPM;
1291 }
1292 // Block further inlining in the instrumented ctxprof case. This avoids
1293 // confusingly collecting profiles for the same GUID corresponding to
1294 // different variants of the function. We could do like PGO and identify
1295 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1296 // thinlto to happen before performing any further optimizations, it's
1297 // unnecessary to collect profiles for non-prevailing copies.
1299 addPostPGOLoopRotation(MPM, Level);
1300 MPM.addPass(AssignGUIDPass());
1302 } else if (IsColdFuncOnlyInstrGen) {
1303 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1304 /* AtomicCounterUpdate */ false,
1306 /* ProfileRemappingFile */ "");
1307 }
1308
1309 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1310 MPM.addPass(PGOIndirectCallPromotion(false, false));
1311
1312 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1313 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile,
1315
1316 if (IsMemprofUse)
1317 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1318
1319 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1320 PGOOpt->Action == PGOOptions::SampleUse))
1321 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1322
1323 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1324
1327 else
1328 MPM.addPass(buildInlinerPipeline(Level, Phase));
1329
1330 // Remove any dead arguments exposed by cleanups, constant folding globals,
1331 // and argument promotion.
1333
1336
1337 if (!isThinLTOPreLink(Phase))
1338 MPM.addPass(CoroCleanupPass());
1339
1340 // Optimize globals now that functions are fully simplified.
1341 MPM.addPass(GlobalOptPass());
1342 MPM.addPass(GlobalDCEPass());
1343
1344 return MPM;
1345}
1346
1347/// TODO: Should LTO cause any differences to this set of passes?
1348void PassBuilder::addVectorPasses(OptimizationLevel Level,
1350 ThinOrFullLTOPhase LTOPhase) {
1353
1354 // Drop dereferenceable assumes after vectorization, as they are no longer
1355 // needed and can inhibit further optimization.
1356 if (!isLTOPreLink(LTOPhase))
1357 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1358
1360 if (isFullLTOPostLink(LTOPhase)) {
1361 // The vectorizer may have significantly shortened a loop body; unroll
1362 // again. Unroll small loops to hide loop backedge latency and saturate any
1363 // parallel execution resources of an out-of-order processor. We also then
1364 // need to clean up redundancies and loop invariant code.
1365 // FIXME: It would be really good to use a loop-integrated instruction
1366 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1367 // across the loop nests.
1368 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1371 LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1373 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1376 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1377 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1378 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1379 // NOTE: we are very late in the pipeline, and we don't have any LICM
1380 // or SimplifyCFG passes scheduled after us, that would cleanup
1381 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1382
1383 // We also turn on struct to vector canonicalization here, which allows
1384 // converting allocas of homogeneous structs into vector allocas when the
1385 // allocas' users are all memory intrinsics. This allows promotion in some
1386 // cases because structs cannot promote to SSA values, but vectors can. We
1387 // only turn this on after memcpyopt runs because this might hinder
1388 // memcpyopt's optimizations if done before. Look at the documentation for
1389 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1391 /*AggregateToVector=*/true)));
1392 }
1393
1394 if (!isFullLTOPostLink(LTOPhase)) {
1395 // Eliminate loads by forwarding stores from the previous iteration to loads
1396 // of the current iteration.
1398 }
1399 // Cleanup after the loop optimization passes.
1400 FPM.addPass(InstCombinePass());
1401
1402 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1403 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1404 // At higher optimization levels, try to clean up any runtime overlap and
1405 // alignment checks inserted by the vectorizer. We want to track correlated
1406 // runtime checks for two inner loops in the same outer loop, fold any
1407 // common computations, hoist loop-invariant aspects out of any outer loop,
1408 // and unswitch the runtime checks if possible. Once hoisted, we may have
1409 // dead (or speculatable) control flows or more combining opportunities.
1410 ExtraPasses.addPass(EarlyCSEPass());
1411 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1412 ExtraPasses.addPass(InstCombinePass());
1413 LoopPassManager LPM;
1414 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1415 /*AllowSpeculation=*/true));
1416 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1418 ExtraPasses.addPass(
1419 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1420 ExtraPasses.addPass(
1421 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1422 ExtraPasses.addPass(InstCombinePass());
1423 FPM.addPass(std::move(ExtraPasses));
1424 }
1425
1426 // Now that we've formed fast to execute loop structures, we do further
1427 // optimizations. These are run afterward as they might block doing complex
1428 // analyses and transforms such as what are needed for loop vectorization.
1429
1430 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1431 // GVN, loop transforms, and others have already run, so it's now better to
1432 // convert to more optimized IR using more aggressive simplify CFG options.
1433 // The extra sinking transform can create larger basic blocks, so do this
1434 // before SLP vectorization.
1435 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1436 .forwardSwitchCondToPhi(true)
1437 .convertSwitchRangeToICmp(true)
1438 .convertSwitchToArithmetic(true)
1439 .convertSwitchToLookupTable(true)
1440 .needCanonicalLoops(false)
1441 .hoistCommonInsts(true)
1442 .sinkCommonInsts(true)));
1443
1444 if (isFullLTOPostLink(LTOPhase)) {
1445 FPM.addPass(SCCPPass());
1446 FPM.addPass(InstCombinePass());
1447 FPM.addPass(BDCEPass());
1448 }
1449
1450 // Optimize parallel scalar instruction chains into SIMD instructions.
1451 if (PTO.SLPVectorization) {
1452 FPM.addPass(SLPVectorizerPass());
1453 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1454 FPM.addPass(EarlyCSEPass());
1455 }
1456 }
1457 // Enhance/cleanup vector code.
1458 FPM.addPass(VectorCombinePass());
1459
1460 if (!isFullLTOPostLink(LTOPhase)) {
1461 FPM.addPass(InstCombinePass());
1462 // Unroll small loops to hide loop backedge latency and saturate any
1463 // parallel execution resources of an out-of-order processor. We also then
1464 // need to clean up redundancies and loop invariant code.
1465 // FIXME: It would be really good to use a loop-integrated instruction
1466 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1467 // across the loop nests.
1468 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1469 if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1471 LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1472 }
1473 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1474 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1475 PTO.ForgetAllSCEVInLoopUnroll)));
1476 FPM.addPass(WarnMissedTransformationsPass());
1477 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1478 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1479 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1480 // NOTE: we are very late in the pipeline, and we don't have any LICM
1481 // or SimplifyCFG passes scheduled after us, that would cleanup
1482 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1483
1484 // We also turn on struct to vector canonicalization here, which allows
1485 // converting allocas of homogeneous structs into vector allocas when the
1486 // allocas' users are all memory intrinsics. This allows promotion in some
1487 // cases because structs cannot promote to SSA values, but vectors can. We
1488 // only turn this on after memcpyopt runs because this might hinder
1489 // memcpyopt's optimizations if done before. Look at the documentation for
1490 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1491 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1492 /*AggregateToVector=*/true)));
1493 }
1494
1495 FPM.addPass(InferAlignmentPass());
1496 FPM.addPass(InstCombinePass());
1497
1498 // This is needed for two reasons:
1499 // 1. It works around problems that instcombine introduces, such as sinking
1500 // expensive FP divides into loops containing multiplications using the
1501 // divide result.
1502 // 2. It helps to clean up some loop-invariant code created by the loop
1503 // unroll pass when IsFullLTO=false.
1505 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1506 /*AllowSpeculation=*/true),
1507 /*UseMemorySSA=*/true));
1508
1509 // Now that we've vectorized and unrolled loops, we may have more refined
1510 // alignment information, try to re-derive it here.
1511 FPM.addPass(AlignmentFromAssumptionsPass());
1512}
1513
1516 ThinOrFullLTOPhase LTOPhase) {
1518
1519 // Run partial inlining pass to partially inline functions that have
1520 // large bodies.
1523
1524 // Remove avail extern fns and globals definitions since we aren't compiling
1525 // an object file for later LTO. For LTO we want to preserve these so they
1526 // are eligible for inlining at link-time. Note if they are unreferenced they
1527 // will be removed by GlobalDCE later, so this only impacts referenced
1528 // available externally globals. Eventually they will be suppressed during
1529 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1530 // may make globals referenced by available external functions dead and saves
1531 // running remaining passes on the eliminated functions. These should be
1532 // preserved during prelinking for link-time inlining decisions.
1533 if (!isLTOPreLink(LTOPhase))
1535
1536 // Do RPO function attribute inference across the module to forward-propagate
1537 // attributes where applicable.
1538 // FIXME: Is this really an optimization rather than a canonicalization?
1540
1541 // Do a post inline PGO instrumentation and use pass. This is a context
1542 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1543 // cross-module inline has not been done yet. The context sensitive
1544 // instrumentation is after all the inlines are done.
1545 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1546 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1547 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1548 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1549 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1550 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1551 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1552 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1553 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1554 }
1555
1556 // Re-compute GlobalsAA here prior to function passes. This is particularly
1557 // useful as the above will have inlined, DCE'ed, and function-attr
1558 // propagated everything. We should at this point have a reasonably minimal
1559 // and richly annotated call graph. By computing aliasing and mod/ref
1560 // information for all local globals here, the late loop passes and notably
1561 // the vectorizer will be able to use them to help recognize vectorizable
1562 // memory operations.
1565
1566 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1567
1568 FunctionPassManager OptimizePM;
1569
1570 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1571 // additional uses of the affected value may be introduced through inlining
1572 // and CSE.
1573 if (!isLTOPreLink(LTOPhase))
1574 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1575
1576 // Scheduling LoopVersioningLICM when inlining is over, because after that
1577 // we may see more accurate aliasing. Reason to run this late is that too
1578 // early versioning may prevent further inlining due to increase of code
1579 // size. Other optimizations which runs later might get benefit of no-alias
1580 // assumption in clone loop.
1582 OptimizePM.addPass(
1584 // LoopVersioningLICM pass might increase new LICM opportunities.
1586 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1587 /*AllowSpeculation=*/true),
1588 /*USeMemorySSA=*/true));
1589 }
1590
1591 OptimizePM.addPass(Float2IntPass());
1593
1594 if (EnableMatrix) {
1595 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1596 OptimizePM.addPass(EarlyCSEPass());
1597 }
1598
1599 // CHR pass should only be applied with the profile information.
1600 // The check is to check the profile summary information in CHR.
1601 if (EnableCHR && Level == OptimizationLevel::O3)
1602 OptimizePM.addPass(ControlHeightReductionPass());
1603
1604 // FIXME: We need to run some loop optimizations to re-rotate loops after
1605 // simplifycfg and others undo their rotation.
1606
1607 // Optimize the loop execution. These passes operate on entire loop nests
1608 // rather than on each loop in an inside-out manner, and so they are actually
1609 // function passes.
1610
1611 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1612
1613 LoopPassManager LPM;
1614 // First rotate loops that may have been un-rotated by prior passes.
1615 // Disable header duplication at -Oz.
1616 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1617 isLTOPreLink(LTOPhase),
1618 /*CheckExitCount=*/true));
1619 // Some loops may have become dead by now. Try to delete them.
1620 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1621 // this may need to be revisited once we run GVN before loop deletion
1622 // in the simplification pipeline.
1623 LPM.addPass(LoopDeletionPass());
1624
1625 if (PTO.LoopInterchange)
1626 LPM.addPass(LoopInterchangePass());
1627
1628 OptimizePM.addPass(
1629 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1630
1631 // FIXME: This may not be the right place in the pipeline.
1632 // We need to have the data to support the right place.
1633 if (PTO.LoopFusion)
1634 OptimizePM.addPass(LoopFusePass());
1635
1636 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1637 // into separate loop that would otherwise inhibit vectorization. This is
1638 // currently only performed for loops marked with the metadata
1639 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1640 OptimizePM.addPass(LoopDistributePass());
1641
1642 // Populates the VFABI attribute with the scalar-to-vector mappings
1643 // from the TargetLibraryInfo.
1644 OptimizePM.addPass(InjectTLIMappings());
1645
1646 addVectorPasses(Level, OptimizePM, LTOPhase);
1647
1648 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1649
1650 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1651 // canonicalization pass that enables other optimizations. As a result,
1652 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1653 // result too early.
1654 OptimizePM.addPass(LoopSinkPass());
1655
1656 // And finally clean up LCSSA form before generating code.
1657 OptimizePM.addPass(InstSimplifyPass());
1658
1659 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1660 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1661 // flattening of blocks.
1662 OptimizePM.addPass(DivRemPairsPass());
1663
1664 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1665 // TODO: move this furter up so that it can be optimized by GVN, etc.
1666 if (EnableMergeICmps)
1667 OptimizePM.addPass(MergeICmpsPass());
1668 OptimizePM.addPass(ExpandMemCmpPass());
1669
1670 // Try to annotate calls that were created during optimization.
1671 OptimizePM.addPass(
1672 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1673
1674 // LoopSink (and other loop passes since the last simplifyCFG) might have
1675 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1676 OptimizePM.addPass(
1678 .convertSwitchRangeToICmp(true)
1679 .convertSwitchToArithmetic(true)
1680 .speculateUnpredictables(true)
1681 .hoistLoadsStoresWithCondFaulting(true)));
1682
1683 // Add the core optimizing pipeline.
1684 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1685 PTO.EagerlyInvalidateAnalyses));
1686
1687 // AllocToken transforms heap allocation calls; this needs to run late after
1688 // other allocation call transformations (such as those in InstCombine).
1689 if (!isLTOPreLink(LTOPhase))
1690 MPM.addPass(AllocTokenPass());
1691
1692 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1693
1694 // Run the Instrumentor pass late.
1696 MPM.addPass(InstrumentorPass(FS));
1697
1698 // Split out cold code. Splitting is done late to avoid hiding context from
1699 // other optimizations and inadvertently regressing performance. The tradeoff
1700 // is that this has a higher code size cost than splitting early.
1701 if (EnableHotColdSplit && !isLTOPreLink(LTOPhase))
1703
1704 // Search the code for similar regions of code. If enough similar regions can
1705 // be found where extracting the regions into their own function will decrease
1706 // the size of the program, we extract the regions, a deduplicate the
1707 // structurally similar regions.
1708 if (EnableIROutliner)
1709 MPM.addPass(IROutlinerPass());
1710
1711 // Now we need to do some global optimization transforms.
1712 // FIXME: It would seem like these should come first in the optimization
1713 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1714 // ordering here.
1715 MPM.addPass(GlobalDCEPass());
1717
1718 // Merge functions if requested. It has a better chance to merge functions
1719 // after ConstantMerge folded jump tables.
1720 if (PTO.MergeFunctions)
1722
1723 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1724 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1725
1726 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1727 if (!isLTOPreLink(LTOPhase))
1729
1730 // Add devirtualization pass only when LTO is not enabled, as otherwise
1731 // the pass is already enabled in the LTO pipeline.
1732 if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1733 // TODO: explore a better pipeline configuration that can improve
1734 // compilation time overhead.
1735 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1736 MPM.addPass(AssignGUIDPass());
1738 /*ExportSummary*/ nullptr,
1739 /*ImportSummary*/ nullptr,
1740 /*DevirtSpeculatively*/ PTO.DevirtualizeSpeculatively));
1742 // Given that the devirtualization creates more opportunities for inlining,
1743 // we run the Inliner again here to maximize the optimization gain we
1744 // get from devirtualization.
1745 // Also, we can't run devirtualization before inlining because the
1746 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1747 // and those passes are only effective after inlining.
1748 if (EnableModuleInliner) {
1752 } else {
1755 /* MandatoryFirst */ true,
1757 }
1758 }
1759
1760 // Attach !implicit.ref metadata from all functions to copyright strings.
1762
1763 return MPM;
1764}
1765
1769 if (Level == OptimizationLevel::O0)
1770 return buildO0DefaultPipeline(Level, Phase);
1771
1773 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1774 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1775 // are not running LTO. If that changes the below checks may need updating.
1777
1778 // If we are invoking this in non-LTO mode, remove any MemProf related
1779 // attributes and metadata, as we don't know whether we are linking with
1780 // a library containing the necessary interfaces.
1783
1784 // Convert @llvm.global.annotations to !annotation metadata.
1786
1787 // Force any function attributes we want the rest of the pipeline to observe.
1789
1790 if (TriggerCrash)
1792
1793 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1795
1796 // Apply module pipeline start EP callback.
1798
1799 // Add the core simplification pipeline.
1801
1802 // Now add the optimization pipeline.
1804
1805 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1806 PGOOpt->Action == PGOOptions::SampleUse)
1808
1809 // Emit annotation remarks.
1811
1812 if (isLTOPreLink(Phase))
1813 addRequiredLTOPreLinkPasses(MPM);
1814
1815 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1816 return MPM;
1817}
1818
1821 bool EmitSummary, bool Verify) {
1823
1824 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1825
1826 if (ThinLTO)
1828 else
1830 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1831 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1832 // bitcode emission runs VerifierPass by default, which registers metadata
1833 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1834 // to get the same behavior.
1835 if (Verify)
1836 MPM.addPass(VerifierPass());
1837 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1838
1839 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1840 // like removing CFI/WPD related instructions. Note, we reuse
1841 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1842 // in FatLtoCleanup.
1843 MPM.addPass(FatLtoCleanup());
1844
1845 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1846 // object code, only in the bitcode section, so drop it before we run
1847 // module optimization and generate machine code. If llvm.type.test() isn't in
1848 // the IR, this won't do anything.
1850
1851 // Use the ThinLTO post-link pipeline with sample profiling
1852 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1853 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1854 else {
1855 // ModuleSimplification does not run the coroutine passes for
1856 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1857 // builds, otherwise they will miscompile.
1858 if (ThinLTO) {
1859 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1860 // consideration.
1861 CGSCCPassManager CGPM;
1865 MPM.addPass(CoroCleanupPass());
1866 }
1867
1868 // otherwise, just use module optimization
1869 MPM.addPass(
1871 // Emit annotation remarks.
1873 }
1874
1875 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1876
1877 return MPM;
1878}
1879
1882 if (Level == OptimizationLevel::O0)
1884
1886
1887 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1888
1889 // Convert @llvm.global.annotations to !annotation metadata.
1891
1892 // Force any function attributes we want the rest of the pipeline to observe.
1894
1895 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1897
1898 // Apply module pipeline start EP callback.
1900
1901 // If we are planning to perform ThinLTO later, we don't bloat the code with
1902 // unrolling/vectorization/... now. Just simplify the module as much as we
1903 // can.
1906 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1907 // thinlto use the contextual info to perform imports; then use the contextual
1908 // profile in the post-thinlink phase.
1909 if (!UseCtxProfile.empty()) {
1910 addRequiredLTOPreLinkPasses(MPM);
1911 return MPM;
1912 }
1913
1914 // Run partial inlining pass to partially inline functions that have
1915 // large bodies.
1916 // FIXME: It isn't clear whether this is really the right place to run this
1917 // in ThinLTO. Because there is another canonicalization and simplification
1918 // phase that will run after the thin link, running this here ends up with
1919 // less information than will be available later and it may grow functions in
1920 // ways that aren't beneficial.
1923
1924 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1925 PGOOpt->Action == PGOOptions::SampleUse)
1927
1928 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1929 // optimization is going to be done in PostLink stage, but clang can't add
1930 // callbacks there in case of in-process ThinLTO called by linker.
1935
1936 // Emit annotation remarks.
1938
1939 // Attach !implicit.ref metadata from all functions to copyright strings.
1941
1942 addRequiredLTOPreLinkPasses(MPM);
1943
1944 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1945
1946 return MPM;
1947}
1948
1950 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1952
1953 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1954
1955 // If we are invoking this without a summary index noting that we are linking
1956 // with a library containing the necessary APIs, remove any MemProf related
1957 // attributes and metadata.
1958 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1960
1961 if (ImportSummary) {
1962 // For ThinLTO we must apply the context disambiguation decisions early, to
1963 // ensure we can correctly match the callsites to summary data.
1966 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1967
1968 // These passes import type identifier resolutions for whole-program
1969 // devirtualization and CFI. They must run early because other passes may
1970 // disturb the specific instruction patterns that these passes look for,
1971 // creating dependencies on resolutions that may not appear in the summary.
1972 //
1973 // For example, GVN may transform the pattern assume(type.test) appearing in
1974 // two basic blocks into assume(phi(type.test, type.test)), which would
1975 // transform a dependency on a WPD resolution into a dependency on a type
1976 // identifier resolution for CFI.
1977 //
1978 // Also, WPD has access to more precise information than ICP and can
1979 // devirtualize more effectively, so it should operate on the IR first.
1980 //
1981 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1982 // metadata and intrinsics.
1983 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1984 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1985 }
1986
1987 if (Level == OptimizationLevel::O0) {
1988 // Run a second time to clean up any type tests left behind by WPD for use
1989 // in ICP.
1992
1993 // AllocToken transforms heap allocation calls; this needs to run late after
1994 // other allocation call transformations (such as those in InstCombine).
1995 MPM.addPass(AllocTokenPass());
1996
1997 // Drop available_externally and unreferenced globals. This is necessary
1998 // with ThinLTO in order to avoid leaving undefined references to dead
1999 // globals in the object file.
2001 MPM.addPass(GlobalDCEPass());
2002 return MPM;
2003 }
2004 if (!UseCtxProfile.empty()) {
2005 MPM.addPass(
2007 } else {
2008 // Add the core simplification pipeline.
2011 }
2012 // Now add the optimization pipeline.
2015
2016 // Emit annotation remarks.
2018
2019 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2020
2021 return MPM;
2022}
2023
2026 // FIXME: We should use a customized pre-link pipeline!
2027 return buildPerModuleDefaultPipeline(Level,
2029}
2030
2033 ModuleSummaryIndex *ExportSummary) {
2035
2036 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2037
2039
2040 // If we are invoking this without a summary index noting that we are linking
2041 // with a library containing the necessary APIs, remove any MemProf related
2042 // attributes and metadata.
2043 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
2045
2046 // Create a function that performs CFI checks for cross-DSO calls with targets
2047 // in the current module.
2048 MPM.addPass(CrossDSOCFIPass());
2049
2050 if (Level == OptimizationLevel::O0) {
2051 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
2052 // metadata and intrinsics.
2053 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2054 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2055 // Run a second time to clean up any type tests left behind by WPD for use
2056 // in ICP.
2058
2060
2061 // AllocToken transforms heap allocation calls; this needs to run late after
2062 // other allocation call transformations (such as those in InstCombine).
2063 MPM.addPass(AllocTokenPass());
2064
2066
2067 // Emit annotation remarks.
2069
2070 return MPM;
2071 }
2072
2073 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2074 // Load sample profile before running the LTO optimization pipeline.
2075 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2076 PGOOpt->ProfileRemappingFile,
2078 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2079 // RequireAnalysisPass for PSI before subsequent non-module passes.
2081 }
2082
2083 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
2085
2086 // Remove unused virtual tables to improve the quality of code generated by
2087 // whole-program devirtualization and bitset lowering.
2088 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2089
2090 // Do basic inference of function attributes from known properties of system
2091 // libraries and other oracles.
2093
2094 if (Level.getSpeedupLevel() > 1) {
2096 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
2097
2098 // Indirect call promotion. This should promote all the targets that are
2099 // left by the earlier promotion pass that promotes intra-module targets.
2100 // This two-step promotion is to save the compile time. For LTO, it should
2101 // produce the same result as if we only do promotion here.
2103 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2104
2105 // Promoting by-reference arguments to by-value exposes more constants to
2106 // IPSCCP.
2107 CGSCCPassManager CGPM;
2110 CGPM.addPass(
2113
2114 // Propagate constants at call sites into the functions they call. This
2115 // opens opportunities for globalopt (and inlining) by substituting function
2116 // pointers passed as arguments to direct uses of functions.
2117 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2118
2119 // Attach metadata to indirect call sites indicating the set of functions
2120 // they may target at run-time. This should follow IPSCCP.
2122 }
2123
2124 // Do RPO function attribute inference across the module to forward-propagate
2125 // attributes where applicable.
2126 // FIXME: Is this really an optimization rather than a canonicalization?
2128
2129 // Use in-range annotations on GEP indices to split globals where beneficial.
2130 MPM.addPass(GlobalSplitPass());
2131
2132 // Run whole program optimization of virtual call when the list of callees
2133 // is fixed.
2134 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2135
2137 // Stop here at -O1.
2138 if (Level == OptimizationLevel::O1) {
2139 // The LowerTypeTestsPass needs to run to lower type metadata and the
2140 // type.test intrinsics. The pass does nothing if CFI is disabled.
2141 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2142 // Run a second time to clean up any type tests left behind by WPD for use
2143 // in ICP (which is performed earlier than this in the regular LTO
2144 // pipeline).
2146
2148
2149 // AllocToken transforms heap allocation calls; this needs to run late after
2150 // other allocation call transformations (such as those in InstCombine).
2151 MPM.addPass(AllocTokenPass());
2152
2154
2155 // Emit annotation remarks.
2157
2158 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2159
2160 return MPM;
2161 }
2162
2163 // TODO: Skip to match buildCoroWrapper.
2164 MPM.addPass(CoroEarlyPass());
2165
2166 // Optimize globals to try and fold them into constants.
2167 MPM.addPass(GlobalOptPass());
2168
2169 // Promote any localized globals to SSA registers.
2171
2172 // Linking modules together can lead to duplicate global constant, only
2173 // keep one copy of each constant.
2175
2176 // Remove unused arguments from functions.
2178
2179 // Reduce the code after globalopt and ipsccp. Both can open up significant
2180 // simplification opportunities, and both can propagate functions through
2181 // function pointers. When this happens, we often have to resolve varargs
2182 // calls, etc, so let instcombine do this.
2183 FunctionPassManager PeepholeFPM;
2184 PeepholeFPM.addPass(InstCombinePass());
2185 if (Level.getSpeedupLevel() > 1)
2186 PeepholeFPM.addPass(AggressiveInstCombinePass());
2187 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2188
2189 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
2190 PTO.EagerlyInvalidateAnalyses));
2191
2192 // Lower variadic functions for supported targets prior to inlining.
2194
2195 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2196 // generally clean up exception handling overhead. It isn't clear this is
2197 // valuable as the inliner doesn't currently care whether it is inlining an
2198 // invoke or a call.
2199 // Run the inliner now.
2200 if (EnableModuleInliner) {
2204 } else {
2207 /* MandatoryFirst */ true,
2210 }
2211
2212 // Perform context disambiguation after inlining, since that would reduce the
2213 // amount of additional cloning required to distinguish the allocation
2214 // contexts.
2217 /*Summary=*/nullptr,
2218 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2219
2220 // Optimize globals again after we ran the inliner.
2221 MPM.addPass(GlobalOptPass());
2222
2223 // Run the OpenMPOpt pass again after global optimizations.
2225
2226 // Garbage collect dead functions.
2227 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2228
2229 // If we didn't decide to inline a function, check to see if we can
2230 // transform it to pass arguments by value instead of by reference.
2231 CGSCCPassManager CGPM;
2237
2239 // The IPO Passes may leave cruft around. Clean up after them.
2240 FPM.addPass(InstCombinePass());
2241 invokePeepholeEPCallbacks(FPM, Level);
2242
2245
2247
2248 // Do a post inline PGO instrumentation and use pass. This is a context
2249 // sensitive PGO pass.
2250 if (PGOOpt) {
2251 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2252 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2253 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2254 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2255 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2256 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2257 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2258 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2259 }
2260
2261 // Break up allocas
2263
2264 // LTO provides additional opportunities for tailcall elimination due to
2265 // link-time inlining, and visibility of nocapture attribute.
2266 FPM.addPass(
2267 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2268
2269 // Run a few AA driver optimizations here and now to cleanup the code.
2270 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
2271 PTO.EagerlyInvalidateAnalyses));
2272
2273 MPM.addPass(
2275
2276 // Require the GlobalsAA analysis for the module so we can query it within
2277 // MainFPM.
2280 // Invalidate AAManager so it can be recreated and pick up the newly
2281 // available GlobalsAA.
2282 MPM.addPass(
2284 }
2285
2286 FunctionPassManager MainFPM;
2288 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
2289 /*AllowSpeculation=*/true),
2290 /*USeMemorySSA=*/true));
2291
2292 if (RunNewGVN)
2293 MainFPM.addPass(NewGVNPass());
2294 else
2295 MainFPM.addPass(GVNPass());
2296
2297 // Remove dead memcpy()'s.
2298 MainFPM.addPass(MemCpyOptPass());
2299
2300 // Nuke dead stores.
2301 MainFPM.addPass(DSEPass());
2302 MainFPM.addPass(MoveAutoInitPass());
2304
2305 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2306
2307 LoopPassManager LPM;
2308 if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
2309 LPM.addPass(LoopFlattenPass());
2310 LPM.addPass(IndVarSimplifyPass());
2311 LPM.addPass(LoopDeletionPass());
2312 // FIXME: Add loop interchange.
2313
2314 // Unroll small loops and perform peeling.
2315 LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
2316 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2317 PTO.ForgetAllSCEVInLoopUnroll));
2318 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2319 // *All* loop passes must preserve it, in order to be able to use it.
2320 MainFPM.addPass(
2321 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2322
2323 MainFPM.addPass(LoopDistributePass());
2324
2325 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2326
2327 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2328
2329 // Run the OpenMPOpt CGSCC pass again late.
2332
2333 invokePeepholeEPCallbacks(MainFPM, Level);
2334 MainFPM.addPass(JumpThreadingPass());
2335 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
2336 PTO.EagerlyInvalidateAnalyses));
2337
2338 // Lower type metadata and the type.test intrinsic. This pass supports
2339 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2340 // to be run at link time if CFI is enabled. This pass does nothing if
2341 // CFI is disabled.
2342 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2343 // Run a second time to clean up any type tests left behind by WPD for use
2344 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2346
2347 // Enable splitting late in the FullLTO post-link pipeline.
2350
2351 // Add late LTO optimization passes.
2352 FunctionPassManager LateFPM;
2353
2354 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2355 // canonicalization pass that enables other optimizations. As a result,
2356 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2357 // result too early.
2358 LateFPM.addPass(LoopSinkPass());
2359
2360 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2361 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2362 // flattening of blocks.
2363 LateFPM.addPass(DivRemPairsPass());
2364
2365 // Delete basic blocks, which optimization passes may have killed.
2367 .convertSwitchRangeToICmp(true)
2368 .convertSwitchToArithmetic(true)
2369 .hoistCommonInsts(true)
2370 .speculateUnpredictables(true)));
2371 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2372
2373 // Drop bodies of available eternally objects to improve GlobalDCE.
2375
2376 // Now that we have optimized the program, discard unreachable functions.
2377 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2378
2379 if (PTO.MergeFunctions)
2381
2383
2384 if (PTO.CallGraphProfile)
2385 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2386
2387 MPM.addPass(CoroCleanupPass());
2388
2389 // AllocToken transforms heap allocation calls; this needs to run late after
2390 // other allocation call transformations (such as those in InstCombine).
2391 MPM.addPass(AllocTokenPass());
2392
2394
2395 // Emit annotation remarks.
2397
2398 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2399
2400 return MPM;
2401}
2402
2406 assert(Level == OptimizationLevel::O0 &&
2407 "buildO0DefaultPipeline should only be used with O0");
2408
2410
2411 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2412
2413 // Perform pseudo probe instrumentation in O0 mode. This is for the
2414 // consistency between different build modes. For example, a LTO build can be
2415 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2416 // the postlink will require pseudo probe instrumentation in the prelink.
2417 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2419
2420 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2421 PGOOpt->Action == PGOOptions::IRUse))
2423 MPM,
2424 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2425 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2426 PGOOpt->ProfileRemappingFile);
2427
2428 // Instrument function entry and exit before all inlining.
2430 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2431
2433
2434 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2436
2437 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2438 // Explicitly disable sample loader inlining and use flattened profile in O0
2439 // pipeline.
2440 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2441 PGOOpt->ProfileRemappingFile,
2443 /*DisableSampleProfileInlining=*/true,
2444 /*UseFlattenedProfile=*/true));
2445 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2446 // RequireAnalysisPass for PSI before subsequent non-module passes.
2448 }
2449
2451
2452 // Build a minimal pipeline based on the semantics required by LLVM,
2453 // which is just that always inlining occurs. Further, disable generating
2454 // lifetime intrinsics to avoid enabling further optimizations during
2455 // code generation.
2457 /*InsertLifetimeIntrinsics=*/false));
2458
2459 if (PTO.MergeFunctions)
2461
2462 if (EnableMatrix)
2463 MPM.addPass(
2465
2466 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2467 CGSCCPassManager CGPM;
2469 if (!CGPM.isEmpty())
2471 }
2472 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2473 LoopPassManager LPM;
2475 if (!LPM.isEmpty()) {
2477 createFunctionToLoopPassAdaptor(std::move(LPM))));
2478 }
2479 }
2480 if (!LoopOptimizerEndEPCallbacks.empty()) {
2481 LoopPassManager LPM;
2483 if (!LPM.isEmpty()) {
2485 createFunctionToLoopPassAdaptor(std::move(LPM))));
2486 }
2487 }
2488 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2491 if (!FPM.isEmpty())
2492 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2493 }
2494
2496
2497 if (!VectorizerStartEPCallbacks.empty()) {
2500 if (!FPM.isEmpty())
2501 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2502 }
2503
2504 if (!VectorizerEndEPCallbacks.empty()) {
2507 if (!FPM.isEmpty())
2508 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2509 }
2510
2512
2513 // AllocToken transforms heap allocation calls; this needs to run late after
2514 // other allocation call transformations (such as those in InstCombine).
2515 if (!isLTOPreLink(Phase))
2516 MPM.addPass(AllocTokenPass());
2517
2519
2521 MPM.addPass(InstrumentorPass(FS));
2522
2523 // Attach !implicit.ref metadata from all functions to copyright strings.
2525
2526 if (isLTOPreLink(Phase))
2527 addRequiredLTOPreLinkPasses(MPM);
2528
2529 // Emit annotation remarks.
2531
2532 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2533
2534 return MPM;
2535}
2536
2538 AAManager AA;
2539
2540 // The order in which these are registered determines their priority when
2541 // being queried.
2542
2543 // Add any target-specific alias analyses that should be run early.
2544 if (TM)
2545 TM->registerEarlyDefaultAliasAnalyses(AA);
2546
2547 // First we register the basic alias analysis that provides the majority of
2548 // per-function local AA logic. This is a stateless, on-demand local set of
2549 // AA techniques.
2550 AA.registerFunctionAnalysis<BasicAA>();
2551
2552 // Next we query fast, specialized alias analyses that wrap IR-embedded
2553 // information about aliasing.
2554 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2555 AA.registerFunctionAnalysis<TypeBasedAA>();
2556
2557 // Add support for querying global aliasing information when available.
2558 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2559 // analysis, all that the `AAManager` can do is query for any *cached*
2560 // results from `GlobalsAA` through a readonly proxy.
2562 AA.registerModuleAnalysis<GlobalsAA>();
2563
2564 // Add target-specific alias analyses.
2565 if (TM)
2566 TM->registerDefaultAliasAnalyses(AA);
2567
2568 return AA;
2569}
2570
2571bool PassBuilder::isInstrumentedPGOUse() const {
2572 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2573 !UseCtxProfile.empty();
2574}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AggressiveInstCombiner - Combine expression patterns to form expressions with fewer,...
Provides passes to inlining "always_inline" functions.
This is the interface for LLVM's primary stateless and local alias analysis.
This file provides the interface for LLVM's Call Graph Profile pass.
This header provides classes for managing passes over SCCs of the call graph.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file provides the interface for a simple, fast CSE pass.
This file provides a pass which clones the current module and runs the provided pass pipeline on the ...
This file provides a pass manager that only runs its passes if the provided marker analysis has been ...
Super simple passes to force specific function attrs from the commandline into the IR for debugging p...
Provides passes for computing function attributes based on interprocedural analyses.
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
This is the interface for a simple mod/ref and alias analysis over globals.
AcceleratorCodeSelection - Identify all functions reachable from a kernel, removing those that are un...
This header defines various interfaces for pass management in LLVM.
Interfaces for passes which infer implicit function attributes from the name and signature of functio...
This file provides the primary interface to the instcombine pass.
Defines passes for running instruction simplification across chunks of IR.
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
See the comments on JumpThreadingPass.
static LVOptions Options
Definition LVOptions.cpp:25
This file implements the Loop Fusion pass.
This header defines the LoopLoadEliminationPass object.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
The header file for the LowerExpectIntrinsic pass as used by the new pass manager.
This pass performs merges of loads and stores on both sides of a.
This file provides the interface for LLVM's Global Value Numbering pass.
This header enumerates the LLVM-provided high-level optimization levels.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
Define option tunables for PGO.
ppc ctr loops PowerPC CTR Loops Verify
static bool isThinLTOPostLink(ThinOrFullLTOPhase Phase)
static void addAnnotationRemarksPass(ModulePassManager &MPM)
static CoroConditionalWrapper buildCoroWrapper(ThinOrFullLTOPhase Phase)
static bool isFullLTOPostLink(ThinOrFullLTOPhase Phase)
static bool isThinLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
static void instructionCountersPass(ModulePassManager &MPM, bool IsPreOptimization)
static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPostLink(ThinOrFullLTOPhase Phase)
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file provides the interface for the pseudo probe implementation for AutoFDO.
This file provides the interface for the sampled PGO loader pass.
This is the interface for a metadata-based scoped no-alias analysis.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
This is the interface for a metadata-based TBAA.
Defines the virtual file system interface vfs::FileSystem.
A manager for alias analyses.
A module pass that rewrites heap allocations to use token-enabled allocation functions based on vario...
Definition AllocToken.h:36
Inlines functions marked as "always_inline".
Argument promotion pass.
Analysis pass providing a never-invalidated alias analysis result.
Simple pass that canonicalizes aliases.
A pass that merges duplicate global constants into a single constant.
This class implements a trivial dead store elimination.
Eliminate dead arguments (and return values) from functions.
A pass that transforms external global definitions into declarations.
Pass embeds a copy of the module optimized with the provided pass pipeline into a global variable.
A pass manager to run a set of extra loop passes if the MarkerTy analysis is present.
Statistics pass for the FunctionPropertiesAnalysis results.
The core GVN pass object.
Definition GVN.h:131
Pass to remove unused function declarations.
Definition GlobalDCE.h:38
Optimize globals that never have their address taken.
Definition GlobalOpt.h:25
Pass to perform split of global variables.
Definition GlobalSplit.h:26
Analysis pass providing a never-invalidated alias analysis result.
Pass to outline cold regions.
Pass to perform interprocedural constant propagation.
Definition SCCP.h:48
Pass to outline similar regions.
Definition IROutliner.h:462
Run instruction simplification across each instruction in the function.
Instrumentation based profiling lowering pass.
The Instrumentor pass.
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
Performs Loop Invariant Code Motion Pass.
Definition LICM.h:66
Loop unroll pass that only does full loop unrolling and peeling.
Performs Loop Idiom Recognize Pass.
Performs Loop Inst Simplify Pass.
A simple loop rotation transformation.
Performs basic CFG simplifications to assist other loop passes.
A pass that does profile-guided sinking of instructions into loops.
Definition LoopSink.h:33
A simple loop rotation transformation.
Loop unroll pass that will support both full and partial unrolling.
Strips MemProf attributes and metadata.
Merge identical functions.
The module inliner pass for the new pass manager.
Module pass, wrapping the inliner pass.
Definition Inliner.h:65
void addModulePass(T Pass)
Add a module pass that runs before the CGSCC passes.
Definition Inliner.h:81
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Simple pass that provides a name to every anonymous globals.
Additional 'norecurse' attribute deduction during postlink LTO phase.
OpenMP optimizations pass.
Definition OpenMPOpt.h:42
static LLVM_ABI const OptimizationLevel O3
Optimize for fast execution as much as possible.
static LLVM_ABI const OptimizationLevel O0
Disable as many optimizations as possible.
static LLVM_ABI const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
static LLVM_ABI const OptimizationLevel O1
Optimize quickly without destroying debuggability.
static LLVM_ABI bool isCtxIRPGOInstrEnabled()
The indirect function call promotion pass.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The profile annotation (profile-instr-use) pass for IR based PGO.
The profile size based optimization pass for memory intrinsics.
Pass to remove unused function declarations.
LLVM_ABI void invokeFullLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModuleInlinerWrapperPass buildInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining as well as the inlining-driven cleanups.
LLVM_ABI void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO, bool EmitSummary, bool Verify=true)
Build a fat object default optimization pipeline.
LLVM_ABI void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI AAManager buildDefaultAAPipeline()
Build the default AAManager with the default alias analysis pipeline registered.
LLVM_ABI void invokeCGSCCOptimizerLateEPCallbacks(CGSCCPassManager &CGPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, ThinLTO-targeting default optimization pipeline to a pass manager.
LLVM_ABI void addPGOInstrPassesForO0(ModulePassManager &MPM, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, std::string ProfileRemappingFile)
Add PGOInstrumenation passes for O0 only.
LLVM_ABI void invokeScalarOptimizerLateEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build a per-module default optimization pipeline.
LLVM_ABI void invokePipelineStartEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI void invokeVectorizerEndEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildO0DefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build an O0 pipeline with the minimal semantically required passes.
LLVM_ABI FunctionPassManager buildFunctionSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM function canonicalization and simplification pipeline.
LLVM_ABI void invokePeepholeEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI void invokePipelineEarlySimplificationEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI void invokeLoopOptimizerEndEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
LLVM_ABI ModulePassManager buildModuleInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining with module inliner pass.
LLVM_ABI ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build a ThinLTO default optimization pipeline to a pass manager.
LLVM_ABI void invokeLateLoopOptimizationsEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
LLVM_ABI void invokeFullLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildModuleSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM module canonicalization and simplification pipeline.
LLVM_ABI ModulePassManager buildModuleOptimizationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase LTOPhase)
Construct the core LLVM module optimization pipeline.
LLVM_ABI void invokeOptimizerLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, LTO-targeting default optimization pipeline to a pass manager.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
bool isEmpty() const
Returns if the pass manager contains any passes.
unsigned LicmMssaNoAccForPromotionCap
Tuning option to disable promotion to scalars in LICM with MemorySSA, if the number of access is too ...
Definition PassBuilder.h:78
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:56
int InlinerThreshold
Tuning option to override the default inliner threshold.
Definition PassBuilder.h:92
bool LoopFusion
Tuning option to enable/disable loop fusion. Its default value is false.
Definition PassBuilder.h:66
bool CallGraphProfile
Tuning option to enable/disable call graph profile.
Definition PassBuilder.h:82
bool MergeFunctions
Tuning option to enable/disable function merging.
Definition PassBuilder.h:89
bool ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition PassBuilder.h:70
unsigned LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition PassBuilder.h:74
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition PassBuilder.h:48
LLVM_ABI PipelineTuningOptions()
Constructor sets pipeline tuning defaults based on cl::opts.
bool LoopUnrolling
Tuning option to enable/disable loop unrolling. Its default value is true.
Definition PassBuilder.h:59
bool LoopInterchange
Tuning option to enable/disable loop interchange.
Definition PassBuilder.h:63
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:52
Reassociate commutative expressions.
Definition Reassociate.h:74
A pass to do RPO deduction and propagation of function attributes.
This pass performs function-level constant propagation and merging.
Definition SCCP.h:30
The sample profiler data loader pass.
Analysis pass providing a never-invalidated alias analysis result.
This pass transforms loops that contain branches or switches on loop- invariant conditions to have mu...
A pass to simplify and canonicalize the CFG of a function.
Definition SimplifyCFG.h:30
Analysis pass providing a never-invalidated alias analysis result.
Optimize scalar/vector interactions in IR using target cost models.
Create a verifier pass.
Definition Verifier.h:133
Interfaces for registering analysis passes, producing common pass manager configurations,...
Abstract Attribute helper functions.
Definition Attributor.h:165
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
@ All
Drop only llvm.assumes using type test value.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > EnableKnowledgeRetention
static cl::opt< bool > RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, cl::desc("Run the NewGVN pass"))
static cl::opt< bool > DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, cl::desc("Disable pre-instrumentation inliner"))
static cl::opt< bool > EnableDFAJumpThreading("enable-dfa-jump-thread", cl::desc("Enable DFA jump threading"), cl::init(true), cl::Hidden)
static cl::opt< bool > PerformMandatoryInliningsFirst("mandatory-inlining-first", cl::init(false), cl::Hidden, cl::desc("Perform mandatory inlinings module-wide, before performing " "inlining"))
static cl::opt< bool > RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden, cl::desc("Run Partial inlining pass"))
static cl::opt< bool > EnableGVNSink("enable-gvn-sink", cl::desc("Enable the GVN sinking pass (default = off)"))
static cl::opt< bool > EnableModuleInliner("enable-module-inliner", cl::init(false), cl::Hidden, cl::desc("Enable module inliner"))
static cl::opt< bool > EnableEagerlyInvalidateAnalyses("eagerly-invalidate-analyses", cl::init(true), cl::Hidden, cl::desc("Eagerly invalidate more analyses in default pipelines"))
static cl::opt< bool > EnableMatrix("enable-matrix", cl::init(false), cl::Hidden, cl::desc("Enable lowering of the matrix intrinsics"))
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
static cl::opt< bool > EnableSampledInstr("enable-sampled-instrumentation", cl::init(false), cl::Hidden, cl::desc("Enable profile instrumentation sampling (default = off)"))
static cl::opt< bool > EnableLoopFlatten("enable-loop-flatten", cl::init(false), cl::Hidden, cl::desc("Enable the LoopFlatten Pass"))
static cl::opt< InliningAdvisorMode > UseInlineAdvisor("enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden, cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"), cl::values(clEnumValN(InliningAdvisorMode::Default, "default", "Heuristics-based inliner version"), clEnumValN(InliningAdvisorMode::Development, "development", "Use development mode (runtime-loadable model)"), clEnumValN(InliningAdvisorMode::Release, "release", "Use release mode (AOT-compiled model)")))
static cl::opt< bool > EnableJumpTableToSwitch("enable-jump-table-to-switch", cl::init(true), cl::desc("Enable JumpTableToSwitch pass (default = true)"))
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
static cl::opt< bool > EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), cl::Hidden, cl::desc("Enable Unroll And Jam Pass"))
@ CGSCC_LIGHT
@ MODULE_LIGHT
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:77
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:85
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
Definition Pass.h:83
@ None
No LTO/ThinLTO behavior needed.
Definition Pass.h:79
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:87
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:81
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
static cl::opt< bool > EnableConstraintElimination("enable-constraint-elimination", cl::init(true), cl::Hidden, cl::desc("Enable pass to eliminate conditions based on linear constraints"))
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
static cl::opt< bool > EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true), cl::Hidden, cl::desc("Enable inline deferral during PGO"))
Flag to enable inline deferral during PGO.
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
LLVM_ABI cl::opt< bool > ForgetSCEVInLoopUnroll
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
static cl::opt< bool > EnablePostPGOLoopRotation("enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden, cl::desc("Run the loop rotation transformation after PGO instrumentation"))
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
static cl::opt< std::string > InstrumentColdFuncOnlyPath("instrument-cold-function-only-path", cl::init(""), cl::desc("File path for cold function only instrumentation(requires use " "with --pgo-instrument-cold-function-only)"), cl::Hidden)
static cl::opt< bool > EnableGlobalAnalyses("enable-global-analyses", cl::init(true), cl::Hidden, cl::desc("Enable inter-procedural analyses"))
static cl::opt< bool > FlattenedProfileUsed("flattened-profile-used", cl::init(false), cl::Hidden, cl::desc("Indicate the sample profile being used is flattened, i.e., " "no inline hierarchy exists in the profile"))
static cl::opt< AttributorRunOption > AttributorRun("attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE), cl::desc("Enable the attributor inter-procedural deduction pass"), cl::values(clEnumValN(AttributorRunOption::FULL, "full", "enable all full attributor runs"), clEnumValN(AttributorRunOption::LIGHT, "light", "enable all attributor-light runs"), clEnumValN(AttributorRunOption::MODULE, "module", "enable module-wide attributor runs"), clEnumValN(AttributorRunOption::MODULE_LIGHT, "module-light", "enable module-wide attributor-light runs"), clEnumValN(AttributorRunOption::CGSCC, "cgscc", "enable call graph SCC attributor runs"), clEnumValN(AttributorRunOption::CGSCC_LIGHT, "cgscc-light", "enable call graph SCC attributor-light runs"), clEnumValN(AttributorRunOption::NONE, "none", "disable attributor runs")))
static cl::opt< bool > EnableLoopInterchange("enable-loopinterchange", cl::init(true), cl::Hidden, cl::desc("Enable the LoopInterchange Pass"))
static cl::opt< bool > ExtraVectorizerPasses("extra-vectorizer-passes", cl::init(false), cl::Hidden, cl::desc("Run cleanup optimization passes after vectorization"))
static cl::opt< bool > EnableHotColdSplit("hot-cold-split", cl::desc("Enable hot-cold splitting pass"))
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
static cl::opt< bool > TriggerCrash("opt-pipeline-trigger-crash", cl::init(false), cl::Hidden, cl::desc("Trigger crash in optimization pipeline"))
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
cl::opt< bool > PGOInstrumentColdFunctionOnly
static cl::opt< bool > EnableCHR("enable-chr", cl::init(true), cl::Hidden, cl::desc("Enable control height reduction optimization (CHR)"))
static cl::opt< bool > EnableMergeFunctions("enable-merge-functions", cl::init(false), cl::Hidden, cl::desc("Enable function merging as part of the optimization pipeline"))
static cl::opt< bool > EnableDevirtualizeSpeculatively("enable-devirtualize-speculatively", cl::desc("Enable speculative devirtualization optimization"), cl::init(false))
static cl::opt< bool > EnableGVNHoist("enable-gvn-hoist", cl::desc("Enable the GVN hoisting pass (default = off)"))
LLVM_ABI cl::opt< unsigned > SetLicmMssaNoAccForPromotionCap
LLVM_ABI InlineParams getInlineParamsFromOptLevel(unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
static cl::opt< bool > EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden, cl::desc("Enable ir outliner pass"))
static cl::opt< int > PreInlineThreshold("preinline-threshold", cl::Hidden, cl::init(75), cl::desc("Control the amount of inlining in pre-instrumentation inliner " "(default = 75)"))
static cl::opt< bool > UseLoopVersioningLICM("enable-loop-versioning-licm", cl::init(false), cl::Hidden, cl::desc("Enable the experimental Loop Versioning LICM pass"))
cl::opt< unsigned > MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden, cl::init(4))
LLVM_ABI cl::opt< unsigned > SetLicmMssaOptCap
static cl::opt< bool > EnableInstrumentor("enable-instrumentor", cl::init(false), cl::Hidden, cl::desc("Enable the Instrumentor Pass"))
static cl::opt< bool > EnableMergeICmps("enable-mergeicmps", cl::init(true), cl::Hidden, cl::desc("Enable MergeICmps pass in the optimization pipeline"))
A DCE pass that assumes instructions are dead until proven otherwise.
Definition ADCE.h:31
Pass to convert @llvm.global.annotations to !annotation metadata.
This pass attempts to minimize the number of assume without loosing any information.
A more lightweight version of the Attributor which only runs attribute inference but no simplificatio...
A more lightweight version of the Attributor which only runs attribute inference but no simplificatio...
Hoist/decompose integer division and remainder instructions to enable CFG improvements and better cod...
Definition DivRemPairs.h:23
A simple and fast domtree-based CSE pass.
Definition EarlyCSE.h:31
Pass which forces specific function attributes into the IR, primarily as a debugging tool.
A simple and fast domtree-based GVN pass to hoist common expressions from sibling branches.
Definition GVN.h:528
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition GVN.h:535
A set of parameters to control various transforms performed by IPSCCP pass.
Definition SCCP.h:35
A pass which infers function attributes from the names and signatures of function declarations in a m...
Provides context on when an inline advisor is constructed in the pipeline (e.g., link phase,...
Thresholds to tune inline cost analysis.
Definition InlineCost.h:207
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:216
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:228
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:209
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition InlineCost.h:241
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:212
Options for the frontend instrumentation based profiling pass.
A no-op pass template which simply forces a specific analysis result to be invalidated.
Pass to forward loads in a loop around the backedge to subsequent iterations.
A set of parameters used to control various transforms performed by the LoopUnroll pass.
The LoopVectorize Pass.
Computes function attributes in post-order over the call graph.
A utility pass template to force an analysis result to be available.