LLVM 24.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"
28#include "llvm/IR/PassManager.h"
29#include "llvm/IR/Verifier.h"
30#include "llvm/Pass.h"
157
158using namespace llvm;
159
160namespace llvm {
161
163 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
164 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
166 "Heuristics-based inliner version"),
168 "Use development mode (runtime-loadable model)"),
170 "Use release mode (AOT-compiled model)")));
171
172/// Flag to enable inline deferral during PGO.
173static cl::opt<bool>
174 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
176 cl::desc("Enable inline deferral during PGO"));
177
178static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
179 cl::init(false), cl::Hidden,
180 cl::desc("Enable module inliner"));
181
183 "mandatory-inlining-first", cl::init(false), cl::Hidden,
184 cl::desc("Perform mandatory inlinings module-wide, before performing "
185 "inlining"));
186
188 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
189 cl::desc("Eagerly invalidate more analyses in default pipelines"));
190
192 "enable-merge-functions", cl::init(false), cl::Hidden,
193 cl::desc("Enable function merging as part of the optimization pipeline"));
194
196 "enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden,
197 cl::desc("Run the loop rotation transformation after PGO instrumentation"));
198
199static cl::opt<bool>
200 TriggerCrash("opt-pipeline-trigger-crash", cl::init(false), cl::Hidden,
201 cl::desc("Trigger crash in optimization pipeline"));
202
204 "enable-global-analyses", cl::init(true), cl::Hidden,
205 cl::desc("Enable inter-procedural analyses"));
206
207static cl::opt<bool> RunPartialInlining("enable-partial-inlining",
208 cl::init(false), cl::Hidden,
209 cl::desc("Run Partial inlining pass"));
210
212 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
213 cl::desc("Run cleanup optimization passes after vectorization"));
214
215static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
216 cl::desc("Run the NewGVN pass"));
217
218static cl::opt<bool>
219 EnableLoopInterchange("enable-loopinterchange", cl::init(true), cl::Hidden,
220 cl::desc("Enable the LoopInterchange Pass"));
221
222static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
223 cl::init(false), cl::Hidden,
224 cl::desc("Enable Unroll And Jam Pass"));
225
226static cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
228 cl::desc("Enable the LoopFlatten Pass"));
229
230static cl::opt<bool>
231 EnableInstrumentor("enable-instrumentor", cl::init(false), cl::Hidden,
232 cl::desc("Enable the Instrumentor Pass"));
233
234static cl::opt<bool>
235 EnableDFAJumpThreading("enable-dfa-jump-thread",
236 cl::desc("Enable DFA jump threading"),
237 cl::init(true), cl::Hidden);
238
239static cl::opt<bool>
240 EnableHotColdSplit("hot-cold-split",
241 cl::desc("Enable hot-cold splitting pass"));
242
243static cl::opt<bool>
244 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
245 cl::desc("Disable pre-instrumentation inliner"));
246
248 "preinline-threshold", cl::Hidden, cl::init(75),
249 cl::desc("Control the amount of inlining in pre-instrumentation inliner "
250 "(default = 75)"));
251
252static cl::opt<bool>
253 EnableGVNHoist("enable-gvn-hoist",
254 cl::desc("Enable the GVN hoisting pass (default = off)"));
255
256static cl::opt<bool>
257 EnableGVNSink("enable-gvn-sink",
258 cl::desc("Enable the GVN sinking pass (default = off)"));
259
261 "enable-jump-table-to-switch", cl::init(true),
262 cl::desc("Enable JumpTableToSwitch pass (default = true)"));
263
264// This option is used in simplifying testing SampleFDO optimizations for
265// profile loading.
266static cl::opt<bool>
267 EnableCHR("enable-chr", cl::init(true), cl::Hidden,
268 cl::desc("Enable control height reduction optimization (CHR)"));
269
271 "flattened-profile-used", cl::init(false), cl::Hidden,
272 cl::desc("Indicate the sample profile being used is flattened, i.e., "
273 "no inline hierarchy exists in the profile"));
274
275static cl::opt<bool>
276 EnableMatrix("enable-matrix", cl::init(false), cl::Hidden,
277 cl::desc("Enable lowering of the matrix intrinsics"));
278
280 "enable-mergeicmps", cl::init(true), cl::Hidden,
281 cl::desc("Enable MergeICmps pass in the optimization pipeline"));
282
284 "enable-constraint-elimination", cl::init(true), cl::Hidden,
285 cl::desc(
286 "Enable pass to eliminate conditions based on linear constraints"));
287
289 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
290 cl::desc("Enable the attributor inter-procedural deduction pass"),
292 "enable all full attributor runs"),
294 "enable all attributor-light runs"),
296 "enable module-wide attributor runs"),
298 "enable module-wide attributor-light runs"),
300 "enable call graph SCC attributor runs"),
302 "enable call graph SCC attributor-light runs"),
303 clEnumValN(AttributorRunOption::NONE, "none",
304 "disable attributor runs")));
305
307 "enable-sampled-instrumentation", cl::init(false), cl::Hidden,
308 cl::desc("Enable profile instrumentation sampling (default = off)"));
310 "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
311 cl::desc("Enable the experimental Loop Versioning LICM pass"));
312
314 "instrument-cold-function-only-path", cl::init(""),
315 cl::desc("File path for cold function only instrumentation(requires use "
316 "with --pgo-instrument-cold-function-only)"),
317 cl::Hidden);
318
319// TODO: There is a similar flag in WPD pass, we should consolidate them by
320// parsing the option only once in PassBuilder and share it across both places.
322 "enable-devirtualize-speculatively",
323 cl::desc("Enable speculative devirtualization optimization"),
324 cl::init(false));
325
328
330} // namespace llvm
331
349
350namespace llvm {
352} // namespace llvm
353
355 OptimizationLevel Level) {
356 for (auto &C : PeepholeEPCallbacks)
357 C(FPM, Level);
358}
361 for (auto &C : LateLoopOptimizationsEPCallbacks)
362 C(LPM, Level);
363}
365 OptimizationLevel Level) {
366 for (auto &C : LoopOptimizerEndEPCallbacks)
367 C(LPM, Level);
368}
371 for (auto &C : ScalarOptimizerLateEPCallbacks)
372 C(FPM, Level);
373}
375 OptimizationLevel Level) {
376 for (auto &C : CGSCCOptimizerLateEPCallbacks)
377 C(CGPM, Level);
378}
380 OptimizationLevel Level) {
381 for (auto &C : VectorizerStartEPCallbacks)
382 C(FPM, Level);
383}
385 OptimizationLevel Level) {
386 for (auto &C : VectorizerEndEPCallbacks)
387 C(FPM, Level);
388}
390 OptimizationLevel Level,
392 for (auto &C : OptimizerEarlyEPCallbacks)
393 C(MPM, Level, Phase);
394}
396 OptimizationLevel Level,
398 for (auto &C : OptimizerLastEPCallbacks)
399 C(MPM, Level, Phase);
400}
403 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
404 C(MPM, Level);
405}
408 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
409 C(MPM, Level);
410}
413 for (auto &C : ThinLinkTimeOptimizationEarlyEPCallbacks)
414 C(MPM, Level);
415}
418 for (auto &C : ThinLinkTimeOptimizationLastEPCallbacks)
419 C(MPM, Level);
420}
422 OptimizationLevel Level) {
423 for (auto &C : PipelineStartEPCallbacks)
424 C(MPM, Level);
425}
428 for (auto &C : PipelineEarlySimplificationEPCallbacks)
429 C(MPM, Level, Phase);
430}
431
432// Get IR stats with InstCount before/after the optimization pipeline
434 bool IsPreOptimization) {
435 if (AreStatisticsEnabled()) {
436 MPM.addPass(
439 FunctionPropertiesStatisticsPass(IsPreOptimization)));
440 }
441}
442
443// Helper to add AnnotationRemarksPass.
447
448// Helper to check if the current compilation phase is preparing for LTO
453
454// Helper to check if the current compilation phase is preparing for FullLTO
455[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
457}
458
459// Helper to check if the current compilation phase is preparing for ThinLTO
463
464// Helper to check if the current compilation phase is LTO backend
469
470// Helper to check if the current compilation phase is FullLTO backend
474
475// Helper to check if the current compilation phase is ThinLTO backend
479
480// Helper to wrap conditionally Coro passes.
482 // TODO: Skip passes according to Phase.
483 ModulePassManager CoroPM;
484 CoroPM.addPass(CoroEarlyPass());
485 CGSCCPassManager CGPM;
486 CGPM.addPass(CoroSplitPass());
487 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
488 CoroPM.addPass(CoroCleanupPass());
489 CoroPM.addPass(GlobalDCEPass());
490 return CoroConditionalWrapper(std::move(CoroPM));
491}
492
493// TODO: Investigate the cost/benefit of tail call elimination on debugging.
495PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
497
499
501 FPM.addPass(CountVisitsPass());
502
503 // Form SSA out of local memory accesses after breaking apart aggregates into
504 // scalars.
505 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
506
507 // Catch trivial redundancies
508 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
509
510 // Hoisting of scalars and load expressions.
511 FPM.addPass(
512 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
513 FPM.addPass(InstCombinePass());
514
515 FPM.addPass(LibCallsShrinkWrapPass());
516
517 invokePeepholeEPCallbacks(FPM, Level);
518
519 FPM.addPass(
520 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
521
522 // Form canonically associated expression trees, and simplify the trees using
523 // basic mathematical properties. For example, this will form (nearly)
524 // minimal multiplication trees.
525 FPM.addPass(ReassociatePass());
526
527 // Add the primary loop simplification pipeline.
528 // FIXME: Currently this is split into two loop pass pipelines because we run
529 // some function passes in between them. These can and should be removed
530 // and/or replaced by scheduling the loop pass equivalents in the correct
531 // positions. But those equivalent passes aren't powerful enough yet.
532 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
533 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
534 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
535 // `LoopInstSimplify`.
536 LoopPassManager LPM1, LPM2;
537
538 // Simplify the loop body. We do this initially to clean up after other loop
539 // passes run, either when iterating on a loop or on inner loops with
540 // implications on the outer loop.
541 LPM1.addPass(LoopInstSimplifyPass());
542 LPM1.addPass(LoopSimplifyCFGPass());
543
544 // Try to remove as much code from the loop header as possible,
545 // to reduce amount of IR that will have to be duplicated. However,
546 // do not perform speculative hoisting the first time as LICM
547 // will destroy metadata that may not need to be destroyed if run
548 // after loop rotation.
549 // TODO: Investigate promotion cap for O1.
550 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
551 /*AllowSpeculation=*/false));
552
553 LPM1.addPass(
554 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
555 // TODO: Investigate promotion cap for O1.
556 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
557 /*AllowSpeculation=*/true));
558 LPM1.addPass(SimpleLoopUnswitchPass());
560 LPM1.addPass(LoopFlattenPass());
561
562 LPM2.addPass(LoopIdiomRecognizePass());
563 LPM2.addPass(IndVarSimplifyPass());
564
566
567 LPM2.addPass(LoopDeletionPass());
568
569 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
570 // because it changes IR to makes profile annotation in back compile
571 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
572 // attributes so we need to make sure and allow the full unroll pass to pay
573 // attention to it.
574 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
575 PGOOpt->Action != PGOOptions::SampleUse)
576 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
577 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
578 PTO.ForgetAllSCEVInLoopUnroll));
579
581
582 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
583 /*UseMemorySSA=*/true));
584 FPM.addPass(
585 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
586 FPM.addPass(InstCombinePass());
587 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
588 // *All* loop passes must preserve it, in order to be able to use it.
589 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
590 /*UseMemorySSA=*/false));
591
592 // Delete small array after loop unroll.
593 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
594
595 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
596 FPM.addPass(MemCpyOptPass());
597
598 // Sparse conditional constant propagation.
599 // FIXME: It isn't clear why we do this *after* loop passes rather than
600 // before...
601 FPM.addPass(SCCPPass());
602
603 // Delete dead bit computations (instcombine runs after to fold away the dead
604 // computations, and then ADCE will run later to exploit any new DCE
605 // opportunities that creates).
606 FPM.addPass(BDCEPass());
607
608 // Run instcombine after redundancy and dead bit elimination to exploit
609 // opportunities opened up by them.
610 FPM.addPass(InstCombinePass());
611 invokePeepholeEPCallbacks(FPM, Level);
612
613 FPM.addPass(CoroElidePass());
614
616
617 // Finally, do an expensive DCE pass to catch all the dead code exposed by
618 // the simplifications and basic cleanup after all the simplifications.
619 // TODO: Investigate if this is too expensive.
620 FPM.addPass(ADCEPass());
621 FPM.addPass(
622 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
623 FPM.addPass(InstCombinePass());
624 invokePeepholeEPCallbacks(FPM, Level);
625
626 return FPM;
627}
628
632 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
633
634 // The O1 pipeline has a separate pipeline creation function to simplify
635 // construction readability.
636 if (Level == OptimizationLevel::O1)
637 return buildO1FunctionSimplificationPipeline(Level, Phase);
638
640
643
644 // Form SSA out of local memory accesses after breaking apart aggregates into
645 // scalars.
647
648 // Catch trivial redundancies
649 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
652
653 // Hoisting of scalars and load expressions.
654 if (EnableGVNHoist)
655 FPM.addPass(GVNHoistPass());
656
657 // Global value numbering based sinking.
658 if (EnableGVNSink) {
659 FPM.addPass(GVNSinkPass());
660 FPM.addPass(
661 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
662 }
663
664 // Speculative execution if the target has divergent branches; otherwise nop.
665 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
666
667 // Optimize based on known information about branches, and cleanup afterward.
670
671 // Jump table to switch conversion.
674
675 FPM.addPass(
676 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
680
681 invokePeepholeEPCallbacks(FPM, Level);
682
683 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
684 // using the size value profile. Don't perform this when optimizing for size.
685 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
687
688 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
689 isInstrumentedPGOUse()));
690 FPM.addPass(
691 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
692
693 // Form canonically associated expression trees, and simplify the trees using
694 // basic mathematical properties. For example, this will form (nearly)
695 // minimal multiplication trees.
697
700
701 // Add the primary loop simplification pipeline.
702 // FIXME: Currently this is split into two loop pass pipelines because we run
703 // some function passes in between them. These can and should be removed
704 // and/or replaced by scheduling the loop pass equivalents in the correct
705 // positions. But those equivalent passes aren't powerful enough yet.
706 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
707 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
708 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
709 // `LoopInstSimplify`.
710 LoopPassManager LPM1, LPM2;
711
712 // Simplify the loop body. We do this initially to clean up after other loop
713 // passes run, either when iterating on a loop or on inner loops with
714 // implications on the outer loop.
715 LPM1.addPass(LoopInstSimplifyPass());
716 LPM1.addPass(LoopSimplifyCFGPass());
717
718 // Try to remove as much code from the loop header as possible,
719 // to reduce amount of IR that will have to be duplicated. However,
720 // do not perform speculative hoisting the first time as LICM
721 // will destroy metadata that may not need to be destroyed if run
722 // after loop rotation.
723 // TODO: Investigate promotion cap for O1.
724 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
725 /*AllowSpeculation=*/false));
726
727 LPM1.addPass(
728 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
729 // TODO: Investigate promotion cap for O1.
730 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
731 /*AllowSpeculation=*/true));
732 LPM1.addPass(
733 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
735 LPM1.addPass(LoopFlattenPass());
736
737 LPM2.addPass(LoopIdiomRecognizePass());
738 LPM2.addPass(IndVarSimplifyPass());
739
740 {
742 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
744 LPM2.addPass(std::move(ExtraPasses));
745 }
746
748
749 LPM2.addPass(LoopDeletionPass());
750
751 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
752 // because it changes IR to makes profile annotation in back compile
753 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
754 // attributes so we need to make sure and allow the full unroll pass to pay
755 // attention to it.
756 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
757 PGOOpt->Action != PGOOptions::SampleUse)
758 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
759 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
760 PTO.ForgetAllSCEVInLoopUnroll));
761
763
764 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
765 /*UseMemorySSA=*/true));
766 FPM.addPass(
767 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
769 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
770 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
771 // *All* loop passes must preserve it, in order to be able to use it.
772 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
773 /*UseMemorySSA=*/false));
774
775 // Delete small array after loop unroll.
777
778 // Try vectorization/scalarization transforms that are both improvements
779 // themselves and can allow further folds with GVN and InstCombine.
780 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
781
782 // Eliminate redundancies.
784 if (RunNewGVN)
785 FPM.addPass(NewGVNPass());
786 else
787 FPM.addPass(GVNPass());
788
789 // Sparse conditional constant propagation.
790 // FIXME: It isn't clear why we do this *after* loop passes rather than
791 // before...
792 FPM.addPass(SCCPPass());
793
794 // Delete dead bit computations (instcombine runs after to fold away the dead
795 // computations, and then ADCE will run later to exploit any new DCE
796 // opportunities that creates).
797 FPM.addPass(BDCEPass());
798
799 // Run instcombine after redundancy and dead bit elimination to exploit
800 // opportunities opened up by them.
802 invokePeepholeEPCallbacks(FPM, Level);
803
804 // Re-consider control flow based optimizations after redundancy elimination,
805 // redo DCE, etc.
808
811
812 // Finally, do an expensive DCE pass to catch all the dead code exposed by
813 // the simplifications and basic cleanup after all the simplifications.
814 // TODO: Investigate if this is too expensive.
815 FPM.addPass(ADCEPass());
816
817 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
818 FPM.addPass(MemCpyOptPass());
819
820 FPM.addPass(DSEPass());
822
824 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
825 /*AllowSpeculation=*/true),
826 /*UseMemorySSA=*/true));
827
828 FPM.addPass(CoroElidePass());
829
831
833 .convertSwitchRangeToICmp(true)
834 .convertSwitchToArithmetic(true)
835 .hoistCommonInsts(true)
836 .sinkCommonInsts(true)));
838 invokePeepholeEPCallbacks(FPM, Level);
839
840 return FPM;
841}
842
843void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
846 MPM.addPass(AssignGUIDPass());
847}
848
849void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
850 OptimizationLevel Level,
851 ThinOrFullLTOPhase LTOPhase) {
852 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
854 return;
855 InlineParams IP;
856
858
859 // FIXME: The hint threshold has the same value used by the regular inliner
860 // when not optimzing for size. This should probably be lowered after
861 // performance testing.
862 // FIXME: this comment is cargo culted from the old pass manager, revisit).
863 IP.HintThreshold = 325;
866 IP, /* MandatoryFirst */ true,
868 CGSCCPassManager &CGPipeline = MIWP.getPM();
869
871 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
872 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
873 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
874 true))); // Merge & remove basic blocks.
875 FPM.addPass(InstCombinePass()); // Combine silly sequences.
876 invokePeepholeEPCallbacks(FPM, Level);
877
878 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
879 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
880
881 MPM.addPass(std::move(MIWP));
882
883 // Delete anything that is now dead to make sure that we don't instrument
884 // dead code. Instrumentation can end up keeping dead code around and
885 // dramatically increase code size.
886 MPM.addPass(GlobalDCEPass());
887}
888
889void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
890 OptimizationLevel Level) {
892 // Disable header duplication in loop rotation at -Oz.
894 createFunctionToLoopPassAdaptor(LoopRotatePass(),
895 /*UseMemorySSA=*/false),
896 PTO.EagerlyInvalidateAnalyses));
897 }
898}
899
900void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
901 OptimizationLevel Level, bool RunProfileGen,
902 bool IsCS, bool AtomicCounterUpdate,
903 std::string ProfileFile,
904 std::string ProfileRemappingFile) {
905 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
906
907 if (!RunProfileGen) {
908 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
909 MPM.addPass(
910 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
911 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
912 // RequireAnalysisPass for PSI before subsequent non-module passes.
913 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
914 return;
915 }
916
917 // Perform PGO instrumentation.
918 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
920
921 addPostPGOLoopRotation(MPM, Level);
922 // Add the profile lowering pass.
923 InstrProfOptions Options;
924 if (!ProfileFile.empty())
925 Options.InstrProfileOutput = ProfileFile;
926 // Do counter promotion at Level greater than O0.
927 Options.DoCounterPromotion = true;
928 Options.UseBFIInPromotion = IsCS;
929 if (EnableSampledInstr) {
930 Options.Sampling = true;
931 // With sampling, there is little beneifit to enable counter promotion.
932 // But note that sampling does work with counter promotion.
933 Options.DoCounterPromotion = false;
934 }
935 Options.Atomic = AtomicCounterUpdate;
936 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
937}
938
940 bool RunProfileGen, bool IsCS,
941 bool AtomicCounterUpdate,
942 std::string ProfileFile,
943 std::string ProfileRemappingFile) {
944 if (!RunProfileGen) {
945 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
946 MPM.addPass(
947 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
948 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
949 // RequireAnalysisPass for PSI before subsequent non-module passes.
951 return;
952 }
953
954 // Perform PGO instrumentation.
957 // Add the profile lowering pass.
959 if (!ProfileFile.empty())
960 Options.InstrProfileOutput = ProfileFile;
961 // Do not do counter promotion at O0.
962 Options.DoCounterPromotion = false;
963 Options.UseBFIInPromotion = IsCS;
964 Options.Atomic = AtomicCounterUpdate;
966}
967
969 return getInlineParamsFromOptLevel(static_cast<unsigned>(Level));
970}
971
975 InlineParams IP;
976 if (PTO.InlinerThreshold == -1)
978 else
979 IP = getInlineParams(PTO.InlinerThreshold);
980 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
981 // set hot-caller threshold to 0 to disable hot
982 // callsite inline (as much as possible [1]) because it makes
983 // profile annotation in the backend inaccurate.
984 //
985 // [1] Note the cost of a function could be below zero due to erased
986 // prologue / epilogue.
987 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
989
990 if (PGOOpt)
992
996
997 // Require the GlobalsAA analysis for the module so we can query it within
998 // the CGSCC pipeline.
1000 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
1001 // Invalidate AAManager so it can be recreated and pick up the newly
1002 // available GlobalsAA.
1003 MIWP.addModulePass(
1005 }
1006
1007 // Require the ProfileSummaryAnalysis for the module so we can query it within
1008 // the inliner pass.
1010
1011 // Now begin the main postorder CGSCC pipeline.
1012 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
1013 // manager and trying to emulate its precise behavior. Much of this doesn't
1014 // make a lot of sense and we should revisit the core CGSCC structure.
1015 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
1016
1017 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1018 // generally clean up exception handling overhead. It isn't clear this is
1019 // valuable as the inliner doesn't currently care whether it is inlining an
1020 // invoke or a call.
1021
1023 MainCGPipeline.addPass(AttributorCGSCCPass());
1025 MainCGPipeline.addPass(AttributorLightCGSCCPass());
1026
1027 // Deduce function attributes. We do another run of this after the function
1028 // simplification pipeline, so this only needs to run when it could affect the
1029 // function simplification pipeline, which is only the case with recursive
1030 // functions.
1031 MainCGPipeline.addPass(PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
1032
1033 // When at O3 add argument promotion to the pass pipeline.
1034 // FIXME: It isn't at all clear why this should be limited to O3.
1035 if (Level == OptimizationLevel::O3)
1036 MainCGPipeline.addPass(ArgumentPromotionPass());
1037
1038 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1039 // there are no OpenMP runtime calls present in the module.
1040 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
1041 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
1042
1043 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
1044
1045 // Add the core function simplification pipeline nested inside the
1046 // CGSCC walk.
1049 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
1050
1051 // Finally, deduce any function attributes based on the fully simplified
1052 // function.
1053 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
1054
1055 // Mark that the function is fully simplified and that it shouldn't be
1056 // simplified again if we somehow revisit it due to CGSCC mutations unless
1057 // it's been modified since.
1060
1061 if (!isThinLTOPreLink(Phase)) {
1062 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
1063 MainCGPipeline.addPass(CoroAnnotationElidePass());
1064 }
1065
1066 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
1067 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
1069
1070 return MIWP;
1071}
1072
1077
1079 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
1080 // set hot-caller threshold to 0 to disable hot
1081 // callsite inline (as much as possible [1]) because it makes
1082 // profile annotation in the backend inaccurate.
1083 //
1084 // [1] Note the cost of a function could be below zero due to erased
1085 // prologue / epilogue.
1086 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1087 IP.HotCallSiteThreshold = 0;
1088
1089 if (PGOOpt)
1091
1092 // The inline deferral logic is used to avoid losing some
1093 // inlining chance in future. It is helpful in SCC inliner, in which
1094 // inlining is processed in bottom-up order.
1095 // While in module inliner, the inlining order is a priority-based order
1096 // by default. The inline deferral is unnecessary there. So we disable the
1097 // inline deferral logic in module inliner.
1098 IP.EnableDeferral = false;
1099
1102 MPM.addPass(GlobalOptPass());
1103 MPM.addPass(GlobalDCEPass());
1104 MPM.addPass(AssignGUIDPass());
1105 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
1106 }
1107
1110 PTO.EagerlyInvalidateAnalyses));
1111
1112 if (!isThinLTOPreLink(Phase)) {
1115 MPM.addPass(
1117 }
1118
1119 return MPM;
1120}
1121
1125 assert(Level != OptimizationLevel::O0 &&
1126 "Should not be used for O0 pipeline");
1127
1129 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1130
1132
1133 // Place pseudo probe instrumentation as the first pass of the pipeline to
1134 // minimize the impact of optimization changes.
1135 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1137
1138 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1139
1140 // In ThinLTO mode, when flattened profile is used, all the available
1141 // profile information will be annotated in PreLink phase so there is
1142 // no need to load the profile again in PostLink.
1143 bool LoadSampleProfile =
1144 HasSampleProfile && !(FlattenedProfileUsed && isThinLTOPostLink(Phase));
1145
1146 // During the ThinLTO backend phase we perform early indirect call promotion
1147 // here, before globalopt. Otherwise imported available_externally functions
1148 // look unreferenced and are removed. If we are going to load the sample
1149 // profile then defer until later.
1150 // TODO: See if we can move later and consolidate with the location where
1151 // we perform ICP when we are loading a sample profile.
1152 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1153 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1154 // determine whether the new direct calls are annotated with prof metadata.
1155 // Ideally this should be determined from whether the IR is annotated with
1156 // sample profile, and not whether the a sample profile was provided on the
1157 // command line. E.g. for flattened profiles where we will not be reloading
1158 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1159 // provide the sample profile file.
1160 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1161 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1162
1163 // Create an early function pass manager to cleanup the output of the
1164 // frontend. Not necessary with LTO post link pipelines since the pre link
1165 // pipeline already cleaned up the frontend output.
1166 if (!isThinLTOPostLink(Phase)) {
1167 // Do basic inference of function attributes from known properties of system
1168 // libraries and other oracles.
1170 MPM.addPass(CoroEarlyPass());
1171
1172 FunctionPassManager EarlyFPM;
1173 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1174 // Lower llvm.expect to metadata before attempting transforms.
1175 // Compare/branch metadata may alter the behavior of passes like
1176 // SimplifyCFG.
1178 EarlyFPM.addPass(SimplifyCFGPass());
1180 EarlyFPM.addPass(EarlyCSEPass());
1181 if (Level == OptimizationLevel::O3)
1182 EarlyFPM.addPass(CallSiteSplittingPass());
1184 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1185 }
1186
1187 if (LoadSampleProfile) {
1188 // Annotate sample profile right after early FPM to ensure freshness of
1189 // the debug info.
1191 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1192 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1193 // RequireAnalysisPass for PSI before subsequent non-module passes.
1195 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1196 // for the profile annotation to be accurate in the LTO backend.
1197 if (!isLTOPreLink(Phase))
1198 // We perform early indirect call promotion here, before globalopt.
1199 // This is important for the ThinLTO backend phase because otherwise
1200 // imported available_externally functions look unreferenced and are
1201 // removed.
1202 MPM.addPass(
1203 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1204 }
1205
1206 // Try to perform OpenMP specific optimizations on the module. This is a
1207 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1209
1211 MPM.addPass(AttributorPass());
1214
1215 // Lower type metadata and the type.test intrinsic in the ThinLTO
1216 // post link pipeline after ICP. This is to enable usage of the type
1217 // tests in ICP sequences.
1220
1222
1223 // Interprocedural constant propagation now that basic cleanup has occurred
1224 // and prior to optimizing globals.
1225 // FIXME: This position in the pipeline hasn't been carefully considered in
1226 // years, it should be re-analyzed.
1227 MPM.addPass(
1228 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1229
1230 // Attach metadata to indirect call sites indicating the set of functions
1231 // they may target at run-time. This should follow IPSCCP.
1233
1234 // Optimize globals to try and fold them into constants.
1235 MPM.addPass(GlobalOptPass());
1236
1237 // Create a small function pass pipeline to cleanup after all the global
1238 // optimizations.
1239 FunctionPassManager GlobalCleanupPM;
1240 // FIXME: Should this instead by a run of SROA?
1241 GlobalCleanupPM.addPass(PromotePass());
1242 GlobalCleanupPM.addPass(InstCombinePass());
1243 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1244 GlobalCleanupPM.addPass(
1245 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1246 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1247 PTO.EagerlyInvalidateAnalyses));
1248
1249 // We already asserted this happens in non-FullLTOPostLink earlier.
1250 const bool IsPreLink = !isThinLTOPostLink(Phase);
1251 // Enable contextual profiling instrumentation.
1252 const bool IsCtxProfGen =
1254 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1255 const bool IsPGOInstrGen =
1256 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1257 const bool IsPGOInstrUse =
1258 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1259 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1260 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1261 // enable ctx profiling from the frontend.
1263 "Enabling both instrumented PGO and contextual instrumentation is not "
1264 "supported.");
1265 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1266
1267 assert(
1269 "--instrument-cold-function-only-path is provided but "
1270 "--pgo-instrument-cold-function-only is not enabled");
1271 const bool IsColdFuncOnlyInstrGen = PGOInstrumentColdFunctionOnly &&
1272 IsPGOPreLink &&
1274
1275 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1276 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1277 addPreInlinerPasses(MPM, Level, Phase);
1278
1279 // Add all the requested passes for instrumentation PGO, if requested.
1280 if (IsPGOInstrGen || IsPGOInstrUse) {
1281 addPGOInstrPasses(MPM, Level,
1282 /*RunProfileGen=*/IsPGOInstrGen,
1283 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1284 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1285 } else if (IsCtxProfGen || IsCtxProfUse) {
1287 // In pre-link, we just want the instrumented IR. We use the contextual
1288 // profile in the post-thinlink phase.
1289 // The instrumentation will be removed in post-thinlink after IPO.
1290 if (IsCtxProfUse) {
1291 MPM.addPass(AssignGUIDPass());
1292 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1293 return MPM;
1294 }
1295 // Block further inlining in the instrumented ctxprof case. This avoids
1296 // confusingly collecting profiles for the same GUID corresponding to
1297 // different variants of the function. We could do like PGO and identify
1298 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1299 // thinlto to happen before performing any further optimizations, it's
1300 // unnecessary to collect profiles for non-prevailing copies.
1302 addPostPGOLoopRotation(MPM, Level);
1303 MPM.addPass(AssignGUIDPass());
1305 } else if (IsColdFuncOnlyInstrGen) {
1306 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1307 /* AtomicCounterUpdate */ false,
1309 /* ProfileRemappingFile */ "");
1310 }
1311
1312 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1313 MPM.addPass(PGOIndirectCallPromotion(false, false));
1314
1315 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1316 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile,
1318
1319 if (IsMemprofUse)
1320 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1321
1322 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1323 PGOOpt->Action == PGOOptions::SampleUse))
1324 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1325
1326 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1327
1330 else
1331 MPM.addPass(buildInlinerPipeline(Level, Phase));
1332
1333 // Remove any dead arguments exposed by cleanups, constant folding globals,
1334 // and argument promotion.
1336
1339
1340 if (!isThinLTOPreLink(Phase))
1341 MPM.addPass(CoroCleanupPass());
1342
1343 // Optimize globals now that functions are fully simplified.
1344 MPM.addPass(GlobalOptPass());
1345 MPM.addPass(GlobalDCEPass());
1346
1347 return MPM;
1348}
1349
1350/// TODO: Should LTO cause any differences to this set of passes?
1351void PassBuilder::addVectorPasses(OptimizationLevel Level,
1353 ThinOrFullLTOPhase LTOPhase) {
1356
1357 // Drop dereferenceable assumes after vectorization, as they are no longer
1358 // needed and can inhibit further optimization.
1359 if (!isLTOPreLink(LTOPhase))
1360 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1361
1363 if (isFullLTOPostLink(LTOPhase)) {
1364 // The vectorizer may have significantly shortened a loop body; unroll
1365 // again. Unroll small loops to hide loop backedge latency and saturate any
1366 // parallel execution resources of an out-of-order processor. We also then
1367 // need to clean up redundancies and loop invariant code.
1368 // FIXME: It would be really good to use a loop-integrated instruction
1369 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1370 // across the loop nests.
1371 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1374 LoopUnrollAndJamPass(static_cast<int>(Level))));
1376 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1379 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1380 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1381 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1382 // NOTE: we are very late in the pipeline, and we don't have any LICM
1383 // or SimplifyCFG passes scheduled after us, that would cleanup
1384 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1385
1386 // We also turn on struct to vector canonicalization here, which allows
1387 // converting allocas of homogeneous structs into vector allocas when the
1388 // allocas' users are all memory intrinsics. This allows promotion in some
1389 // cases because structs cannot promote to SSA values, but vectors can. We
1390 // only turn this on after memcpyopt runs because this might hinder
1391 // memcpyopt's optimizations if done before. Look at the documentation for
1392 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1394 /*AggregateToVector=*/true)));
1395 }
1396
1397 if (!isFullLTOPostLink(LTOPhase)) {
1398 // Eliminate loads by forwarding stores from the previous iteration to loads
1399 // of the current iteration.
1401 }
1402 // Cleanup after the loop optimization passes.
1403 FPM.addPass(InstCombinePass());
1404
1406 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1407 // At higher optimization levels, try to clean up any runtime overlap and
1408 // alignment checks inserted by the vectorizer. We want to track correlated
1409 // runtime checks for two inner loops in the same outer loop, fold any
1410 // common computations, hoist loop-invariant aspects out of any outer loop,
1411 // and unswitch the runtime checks if possible. Once hoisted, we may have
1412 // dead (or speculatable) control flows or more combining opportunities.
1413 ExtraPasses.addPass(EarlyCSEPass());
1414 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1415 ExtraPasses.addPass(InstCombinePass());
1416 LoopPassManager LPM;
1417 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1418 /*AllowSpeculation=*/true));
1419 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1421 ExtraPasses.addPass(
1422 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1423 ExtraPasses.addPass(
1424 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1425 ExtraPasses.addPass(InstCombinePass());
1426 FPM.addPass(std::move(ExtraPasses));
1427 }
1428
1429 // Now that we've formed fast to execute loop structures, we do further
1430 // optimizations. These are run afterward as they might block doing complex
1431 // analyses and transforms such as what are needed for loop vectorization.
1432
1433 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1434 // GVN, loop transforms, and others have already run, so it's now better to
1435 // convert to more optimized IR using more aggressive simplify CFG options.
1436 // The extra sinking transform can create larger basic blocks, so do this
1437 // before SLP vectorization.
1438 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1439 .forwardSwitchCondToPhi(true)
1440 .convertSwitchRangeToICmp(true)
1441 .convertSwitchToArithmetic(true)
1442 .convertSwitchToLookupTable(true)
1443 .needCanonicalLoops(false)
1444 .hoistCommonInsts(true)
1445 .sinkCommonInsts(true)));
1446
1447 if (isFullLTOPostLink(LTOPhase)) {
1448 FPM.addPass(SCCPPass());
1449 FPM.addPass(InstCombinePass());
1450 FPM.addPass(BDCEPass());
1451 }
1452
1453 // Optimize parallel scalar instruction chains into SIMD instructions.
1454 if (PTO.SLPVectorization) {
1455 FPM.addPass(SLPVectorizerPass());
1457 FPM.addPass(EarlyCSEPass());
1458 }
1459 }
1460 // Enhance/cleanup vector code.
1461 FPM.addPass(VectorCombinePass());
1462
1463 if (!isFullLTOPostLink(LTOPhase)) {
1464 FPM.addPass(InstCombinePass());
1465 // Unroll small loops to hide loop backedge latency and saturate any
1466 // parallel execution resources of an out-of-order processor. We also then
1467 // need to clean up redundancies and loop invariant code.
1468 // FIXME: It would be really good to use a loop-integrated instruction
1469 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1470 // across the loop nests.
1471 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1472 if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1474 LoopUnrollAndJamPass(static_cast<int>(Level))));
1475 }
1476 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1477 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1478 PTO.ForgetAllSCEVInLoopUnroll)));
1479 FPM.addPass(WarnMissedTransformationsPass());
1480 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1481 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1482 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1483 // NOTE: we are very late in the pipeline, and we don't have any LICM
1484 // or SimplifyCFG passes scheduled after us, that would cleanup
1485 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1486
1487 // We also turn on struct to vector canonicalization here, which allows
1488 // converting allocas of homogeneous structs into vector allocas when the
1489 // allocas' users are all memory intrinsics. This allows promotion in some
1490 // cases because structs cannot promote to SSA values, but vectors can. We
1491 // only turn this on after memcpyopt runs because this might hinder
1492 // memcpyopt's optimizations if done before. Look at the documentation for
1493 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1494 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1495 /*AggregateToVector=*/true)));
1496 }
1497
1498 FPM.addPass(InferAlignmentPass());
1499 FPM.addPass(InstCombinePass());
1500
1501 // This is needed for two reasons:
1502 // 1. It works around problems that instcombine introduces, such as sinking
1503 // expensive FP divides into loops containing multiplications using the
1504 // divide result.
1505 // 2. It helps to clean up some loop-invariant code created by the loop
1506 // unroll pass when IsFullLTO=false.
1508 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1509 /*AllowSpeculation=*/true),
1510 /*UseMemorySSA=*/true));
1511
1512 // Now that we've vectorized and unrolled loops, we may have more refined
1513 // alignment information, try to re-derive it here.
1514 FPM.addPass(AlignmentFromAssumptionsPass());
1515}
1516
1519 ThinOrFullLTOPhase LTOPhase) {
1521
1522 // Run partial inlining pass to partially inline functions that have
1523 // large bodies.
1526
1527 // Remove avail extern fns and globals definitions since we aren't compiling
1528 // an object file for later LTO. For LTO we want to preserve these so they
1529 // are eligible for inlining at link-time. Note if they are unreferenced they
1530 // will be removed by GlobalDCE later, so this only impacts referenced
1531 // available externally globals. Eventually they will be suppressed during
1532 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1533 // may make globals referenced by available external functions dead and saves
1534 // running remaining passes on the eliminated functions. These should be
1535 // preserved during prelinking for link-time inlining decisions.
1536 if (!isLTOPreLink(LTOPhase))
1538
1539 // Do RPO function attribute inference across the module to forward-propagate
1540 // attributes where applicable.
1541 // FIXME: Is this really an optimization rather than a canonicalization?
1543
1544 // Do a post inline PGO instrumentation and use pass. This is a context
1545 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1546 // cross-module inline has not been done yet. The context sensitive
1547 // instrumentation is after all the inlines are done.
1548 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1549 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1550 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1551 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1552 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1553 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1554 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1555 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1556 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1557 }
1558
1559 // Re-compute GlobalsAA here prior to function passes. This is particularly
1560 // useful as the above will have inlined, DCE'ed, and function-attr
1561 // propagated everything. We should at this point have a reasonably minimal
1562 // and richly annotated call graph. By computing aliasing and mod/ref
1563 // information for all local globals here, the late loop passes and notably
1564 // the vectorizer will be able to use them to help recognize vectorizable
1565 // memory operations.
1568
1569 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1570
1571 FunctionPassManager OptimizePM;
1572
1573 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1574 // additional uses of the affected value may be introduced through inlining
1575 // and CSE.
1576 if (!isLTOPreLink(LTOPhase))
1577 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1578
1579 // Scheduling LoopVersioningLICM when inlining is over, because after that
1580 // we may see more accurate aliasing. Reason to run this late is that too
1581 // early versioning may prevent further inlining due to increase of code
1582 // size. Other optimizations which runs later might get benefit of no-alias
1583 // assumption in clone loop.
1585 OptimizePM.addPass(
1587 // LoopVersioningLICM pass might increase new LICM opportunities.
1589 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1590 /*AllowSpeculation=*/true),
1591 /*USeMemorySSA=*/true));
1592 }
1593
1594 OptimizePM.addPass(Float2IntPass());
1595 // Defer until LTO post-link where some constants may become known.
1596 if (!isLTOPreLink(LTOPhase))
1598
1599 if (EnableMatrix) {
1600 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1601 OptimizePM.addPass(EarlyCSEPass());
1602 }
1603
1604 // CHR pass should only be applied with the profile information.
1605 // The check is to check the profile summary information in CHR.
1606 if (EnableCHR && Level == OptimizationLevel::O3)
1607 OptimizePM.addPass(ControlHeightReductionPass());
1608
1609 // FIXME: We need to run some loop optimizations to re-rotate loops after
1610 // simplifycfg and others undo their rotation.
1611
1612 // Optimize the loop execution. These passes operate on entire loop nests
1613 // rather than on each loop in an inside-out manner, and so they are actually
1614 // function passes.
1615
1616 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1617
1618 LoopPassManager LPM;
1619 // First rotate loops that may have been un-rotated by prior passes.
1620 // Disable header duplication at -Oz.
1621 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1622 isLTOPreLink(LTOPhase),
1623 /*CheckExitCount=*/true));
1624 // Some loops may have become dead by now. Try to delete them.
1625 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1626 // this may need to be revisited once we run GVN before loop deletion
1627 // in the simplification pipeline.
1628 LPM.addPass(LoopDeletionPass());
1629
1630 if (PTO.LoopInterchange)
1631 LPM.addPass(LoopInterchangePass());
1632
1633 OptimizePM.addPass(
1634 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1635
1636 // FIXME: This may not be the right place in the pipeline.
1637 // We need to have the data to support the right place.
1638 if (PTO.LoopFusion)
1639 OptimizePM.addPass(LoopFusePass());
1640
1641 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1642 // into separate loop that would otherwise inhibit vectorization. This is
1643 // currently only performed for loops marked with the metadata
1644 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1645 OptimizePM.addPass(LoopDistributePass());
1646
1647 // Populates the VFABI attribute with the scalar-to-vector mappings
1648 // from the TargetLibraryInfo.
1649 OptimizePM.addPass(InjectTLIMappings());
1650
1651 addVectorPasses(Level, OptimizePM, LTOPhase);
1652
1653 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1654
1655 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1656 // canonicalization pass that enables other optimizations. As a result,
1657 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1658 // result too early.
1659 OptimizePM.addPass(LoopSinkPass());
1660
1661 // And finally clean up LCSSA form before generating code.
1662 OptimizePM.addPass(InstSimplifyPass());
1663
1664 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1665 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1666 // flattening of blocks.
1667 OptimizePM.addPass(DivRemPairsPass());
1668
1669 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1670 // TODO: move this furter up so that it can be optimized by GVN, etc.
1671 if (EnableMergeICmps)
1672 OptimizePM.addPass(MergeICmpsPass());
1673 OptimizePM.addPass(ExpandMemCmpPass());
1674
1675 // Try to annotate calls that were created during optimization.
1676 OptimizePM.addPass(
1677 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1678
1679 // LoopSink (and other loop passes since the last simplifyCFG) might have
1680 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1681 OptimizePM.addPass(
1683 .convertSwitchRangeToICmp(true)
1684 .convertSwitchToArithmetic(true)
1685 .speculateUnpredictables(true)
1686 .hoistLoadsStoresWithCondFaulting(true)));
1687
1688 // Add the core optimizing pipeline.
1689 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1690 PTO.EagerlyInvalidateAnalyses));
1691
1692 // AllocToken transforms heap allocation calls; this needs to run late after
1693 // other allocation call transformations (such as those in InstCombine).
1694 if (!isLTOPreLink(LTOPhase))
1695 MPM.addPass(AllocTokenPass());
1696
1697 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1698
1699 // Run the Instrumentor pass late.
1701 MPM.addPass(InstrumentorPass(FS));
1702
1703 // Split out cold code. Splitting is done late to avoid hiding context from
1704 // other optimizations and inadvertently regressing performance. The tradeoff
1705 // is that this has a higher code size cost than splitting early.
1706 if (EnableHotColdSplit && !isLTOPreLink(LTOPhase))
1708
1709 // Now we need to do some global optimization transforms.
1710 // FIXME: It would seem like these should come first in the optimization
1711 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1712 // ordering here.
1713 MPM.addPass(GlobalDCEPass());
1715
1716 // Merge functions if requested. It has a better chance to merge functions
1717 // after ConstantMerge folded jump tables.
1718 if (PTO.MergeFunctions)
1720
1721 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1722 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1723
1724 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1725 if (!isLTOPreLink(LTOPhase))
1727
1728 // Add devirtualization pass only when LTO is not enabled, as otherwise
1729 // the pass is already enabled in the LTO pipeline.
1730 if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1731 // TODO: explore a better pipeline configuration that can improve
1732 // compilation time overhead.
1733 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1734 MPM.addPass(AssignGUIDPass());
1736 /*ExportSummary*/ nullptr,
1737 /*ImportSummary*/ nullptr,
1738 /*DevirtSpeculatively*/ PTO.DevirtualizeSpeculatively));
1740 // Given that the devirtualization creates more opportunities for inlining,
1741 // we run the Inliner again here to maximize the optimization gain we
1742 // get from devirtualization.
1743 // Also, we can't run devirtualization before inlining because the
1744 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1745 // and those passes are only effective after inlining.
1746 if (EnableModuleInliner) {
1750 } else {
1753 /* MandatoryFirst */ true,
1755 }
1756 }
1757
1758 // Attach !implicit.ref metadata from all functions to copyright strings.
1760
1761 return MPM;
1762}
1763
1767 if (Level == OptimizationLevel::O0)
1768 return buildO0DefaultPipeline(Level, Phase);
1769
1771 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1772 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1773 // are not running LTO. If that changes the below checks may need updating.
1775
1776 // If we are invoking this in non-LTO mode, remove any MemProf related
1777 // attributes and metadata, as we don't know whether we are linking with
1778 // a library containing the necessary interfaces.
1781
1782 // Convert @llvm.global.annotations to !annotation metadata.
1784
1785 // Force any function attributes we want the rest of the pipeline to observe.
1787
1788 if (TriggerCrash)
1790
1791 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1793
1794 // Apply module pipeline start EP callback.
1796
1797 // Add the core simplification pipeline.
1799
1800 // Now add the optimization pipeline.
1802
1803 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1804 PGOOpt->Action == PGOOptions::SampleUse)
1806
1807 // Emit annotation remarks.
1809
1810 if (isLTOPreLink(Phase))
1811 addRequiredLTOPreLinkPasses(MPM);
1812
1813 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1814 return MPM;
1815}
1816
1819 bool EmitSummary, bool Verify) {
1821
1822 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1823
1824 if (ThinLTO)
1826 else
1828 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1829 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1830 // bitcode emission runs VerifierPass by default, which registers metadata
1831 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1832 // to get the same behavior.
1833 if (Verify)
1834 MPM.addPass(VerifierPass());
1835 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1836
1837 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1838 // like removing CFI/WPD related instructions. Note, we reuse
1839 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1840 // in FatLtoCleanup.
1841 MPM.addPass(FatLtoCleanup());
1842
1843 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1844 // object code, only in the bitcode section, so drop it before we run
1845 // module optimization and generate machine code. If llvm.type.test() isn't in
1846 // the IR, this won't do anything.
1848
1849 // Use the ThinLTO post-link pipeline with sample profiling
1850 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1851 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1852 else {
1853 // ModuleSimplification does not run the coroutine passes for
1854 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1855 // builds, otherwise they will miscompile.
1856 if (ThinLTO) {
1857 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1858 // consideration.
1859 CGSCCPassManager CGPM;
1863 MPM.addPass(CoroCleanupPass());
1864 }
1865
1866 // otherwise, just use module optimization
1867 MPM.addPass(
1869 // Emit annotation remarks.
1871 }
1872
1873 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1874
1875 return MPM;
1876}
1877
1880 if (Level == OptimizationLevel::O0)
1882
1884
1885 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1886
1887 // Convert @llvm.global.annotations to !annotation metadata.
1889
1890 // Force any function attributes we want the rest of the pipeline to observe.
1892
1893 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1895
1896 // Apply module pipeline start EP callback.
1898
1899 // If we are planning to perform ThinLTO later, we don't bloat the code with
1900 // unrolling/vectorization/... now. Just simplify the module as much as we
1901 // can.
1904 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1905 // thinlto use the contextual info to perform imports; then use the contextual
1906 // profile in the post-thinlink phase.
1907 if (!UseCtxProfile.empty()) {
1908 addRequiredLTOPreLinkPasses(MPM);
1909 return MPM;
1910 }
1911
1912 // Run partial inlining pass to partially inline functions that have
1913 // large bodies.
1914 // FIXME: It isn't clear whether this is really the right place to run this
1915 // in ThinLTO. Because there is another canonicalization and simplification
1916 // phase that will run after the thin link, running this here ends up with
1917 // less information than will be available later and it may grow functions in
1918 // ways that aren't beneficial.
1921
1922 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1923 PGOOpt->Action == PGOOptions::SampleUse)
1925
1926 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1927 // optimization is going to be done in PostLink stage, but clang can't add
1928 // callbacks there in case of in-process ThinLTO called by linker.
1933
1934 // Emit annotation remarks.
1936
1937 // Attach !implicit.ref metadata from all functions to copyright strings.
1939
1940 addRequiredLTOPreLinkPasses(MPM);
1941
1942 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1943
1944 return MPM;
1945}
1946
1948 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1950
1951 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1952
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
2004
2005 return MPM;
2006 }
2007 if (!UseCtxProfile.empty()) {
2008 MPM.addPass(
2010 } else {
2011 // Add the core simplification pipeline.
2014 }
2015 // Now add the optimization pipeline.
2018
2020
2021 // Emit annotation remarks.
2023
2024 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2025
2026 return MPM;
2027}
2028
2031 // FIXME: We should use a customized pre-link pipeline!
2032 return buildPerModuleDefaultPipeline(Level,
2034}
2035
2038 ModuleSummaryIndex *ExportSummary) {
2040
2041 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2042
2044
2045 // If we are invoking this without a summary index noting that we are linking
2046 // with a library containing the necessary APIs, remove any MemProf related
2047 // attributes and metadata.
2048 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
2050
2051 // Create a function that performs CFI checks for cross-DSO calls with targets
2052 // in the current module.
2053 MPM.addPass(CrossDSOCFIPass());
2054
2055 if (Level == OptimizationLevel::O0) {
2056 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
2057 // metadata and intrinsics.
2058 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2059 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2060 // Run a second time to clean up any type tests left behind by WPD for use
2061 // in ICP.
2063
2065
2066 // AllocToken transforms heap allocation calls; this needs to run late after
2067 // other allocation call transformations (such as those in InstCombine).
2068 MPM.addPass(AllocTokenPass());
2069
2071
2072 // Emit annotation remarks.
2074
2075 return MPM;
2076 }
2077
2078 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2079 // Load sample profile before running the LTO optimization pipeline.
2080 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2081 PGOOpt->ProfileRemappingFile,
2083 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2084 // RequireAnalysisPass for PSI before subsequent non-module passes.
2086 }
2087
2088 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
2090
2091 // Remove unused virtual tables to improve the quality of code generated by
2092 // whole-program devirtualization and bitset lowering.
2093 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2094
2095 // Do basic inference of function attributes from known properties of system
2096 // libraries and other oracles.
2098
2099 if (Level >= OptimizationLevel::O2) {
2101 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
2102
2103 // Indirect call promotion. This should promote all the targets that are
2104 // left by the earlier promotion pass that promotes intra-module targets.
2105 // This two-step promotion is to save the compile time. For LTO, it should
2106 // produce the same result as if we only do promotion here.
2108 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2109
2110 // Promoting by-reference arguments to by-value exposes more constants to
2111 // IPSCCP.
2112 CGSCCPassManager CGPM;
2115 CGPM.addPass(
2118
2119 // Propagate constants at call sites into the functions they call. This
2120 // opens opportunities for globalopt (and inlining) by substituting function
2121 // pointers passed as arguments to direct uses of functions.
2122 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2123
2124 // Attach metadata to indirect call sites indicating the set of functions
2125 // they may target at run-time. This should follow IPSCCP.
2127 }
2128
2129 // Do RPO function attribute inference across the module to forward-propagate
2130 // attributes where applicable.
2131 // FIXME: Is this really an optimization rather than a canonicalization?
2133
2134 // Use in-range annotations on GEP indices to split globals where beneficial.
2135 MPM.addPass(GlobalSplitPass());
2136
2137 // Run whole program optimization of virtual call when the list of callees
2138 // is fixed.
2139 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2140
2142 // Stop here at -O1.
2143 if (Level == OptimizationLevel::O1) {
2145 LowerConstantIntrinsicsPass(), PTO.EagerlyInvalidateAnalyses));
2146
2147 // The LowerTypeTestsPass needs to run to lower type metadata and the
2148 // type.test intrinsics. The pass does nothing if CFI is disabled.
2149 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2150 // Run a second time to clean up any type tests left behind by WPD for use
2151 // in ICP (which is performed earlier than this in the regular LTO
2152 // pipeline).
2154
2156
2157 // AllocToken transforms heap allocation calls; this needs to run late after
2158 // other allocation call transformations (such as those in InstCombine).
2159 MPM.addPass(AllocTokenPass());
2160
2162
2163 // Emit annotation remarks.
2165
2166 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2167
2168 return MPM;
2169 }
2170
2171 // TODO: Skip to match buildCoroWrapper.
2172 MPM.addPass(CoroEarlyPass());
2173
2174 // Optimize globals to try and fold them into constants.
2175 MPM.addPass(GlobalOptPass());
2176
2177 // Promote any localized globals to SSA registers.
2179
2180 // Linking modules together can lead to duplicate global constant, only
2181 // keep one copy of each constant.
2183
2184 // Remove unused arguments from functions.
2186
2187 // Reduce the code after globalopt and ipsccp. Both can open up significant
2188 // simplification opportunities, and both can propagate functions through
2189 // function pointers. When this happens, we often have to resolve varargs
2190 // calls, etc, so let instcombine do this.
2191 FunctionPassManager PeepholeFPM;
2192 PeepholeFPM.addPass(InstCombinePass());
2193 if (Level >= OptimizationLevel::O2)
2194 PeepholeFPM.addPass(AggressiveInstCombinePass());
2195 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2196
2197 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
2198 PTO.EagerlyInvalidateAnalyses));
2199
2200 // Lower variadic functions for supported targets prior to inlining.
2202
2203 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2204 // generally clean up exception handling overhead. It isn't clear this is
2205 // valuable as the inliner doesn't currently care whether it is inlining an
2206 // invoke or a call.
2207 // Run the inliner now.
2208 if (EnableModuleInliner) {
2212 } else {
2215 /* MandatoryFirst */ true,
2218 }
2219
2220 // Perform context disambiguation after inlining, since that would reduce the
2221 // amount of additional cloning required to distinguish the allocation
2222 // contexts.
2225 /*Summary=*/nullptr,
2226 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2227
2228 // Optimize globals again after we ran the inliner.
2229 MPM.addPass(GlobalOptPass());
2230
2231 // Run the OpenMPOpt pass again after global optimizations.
2233
2234 // Garbage collect dead functions.
2235 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2236
2237 // If we didn't decide to inline a function, check to see if we can
2238 // transform it to pass arguments by value instead of by reference.
2239 CGSCCPassManager CGPM;
2245
2247 // The IPO Passes may leave cruft around. Clean up after them.
2248 FPM.addPass(InstCombinePass());
2249 invokePeepholeEPCallbacks(FPM, Level);
2250
2253
2255
2256 // Do a post inline PGO instrumentation and use pass. This is a context
2257 // sensitive PGO pass.
2258 if (PGOOpt) {
2259 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2260 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2261 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2262 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2263 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2264 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2265 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2266 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2267 }
2268
2269 // Break up allocas
2271
2272 // LTO provides additional opportunities for tailcall elimination due to
2273 // link-time inlining, and visibility of nocapture attribute.
2274 FPM.addPass(
2275 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2276
2277 // Run a few AA driver optimizations here and now to cleanup the code.
2278 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
2279 PTO.EagerlyInvalidateAnalyses));
2280
2281 MPM.addPass(
2283
2284 // Require the GlobalsAA analysis for the module so we can query it within
2285 // MainFPM.
2288 // Invalidate AAManager so it can be recreated and pick up the newly
2289 // available GlobalsAA.
2290 MPM.addPass(
2292 }
2293
2294 FunctionPassManager MainFPM;
2296 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
2297 /*AllowSpeculation=*/true),
2298 /*USeMemorySSA=*/true));
2299
2300 if (RunNewGVN)
2301 MainFPM.addPass(NewGVNPass());
2302 else
2303 MainFPM.addPass(GVNPass());
2304
2305 // Remove dead memcpy()'s.
2306 MainFPM.addPass(MemCpyOptPass());
2307
2308 // Nuke dead stores.
2309 MainFPM.addPass(DSEPass());
2310 MainFPM.addPass(MoveAutoInitPass());
2312
2314
2315 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2316
2317 LoopPassManager LPM;
2319 LPM.addPass(LoopFlattenPass());
2320 LPM.addPass(IndVarSimplifyPass());
2321 LPM.addPass(LoopDeletionPass());
2322 // FIXME: Add loop interchange.
2323
2324 // Unroll small loops and perform peeling.
2325 LPM.addPass(LoopFullUnrollPass(static_cast<int>(Level),
2326 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2327 PTO.ForgetAllSCEVInLoopUnroll));
2328 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2329 // *All* loop passes must preserve it, in order to be able to use it.
2330 MainFPM.addPass(
2331 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2332
2333 MainFPM.addPass(LoopDistributePass());
2334
2335 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2336
2337 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2338
2339 // Run the OpenMPOpt CGSCC pass again late.
2342
2343 invokePeepholeEPCallbacks(MainFPM, Level);
2344 MainFPM.addPass(JumpThreadingPass());
2345 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
2346 PTO.EagerlyInvalidateAnalyses));
2347
2348 // Lower type metadata and the type.test intrinsic. This pass supports
2349 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2350 // to be run at link time if CFI is enabled. This pass does nothing if
2351 // CFI is disabled.
2352 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2353 // Run a second time to clean up any type tests left behind by WPD for use
2354 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2356
2357 // Enable splitting late in the FullLTO post-link pipeline.
2360
2361 // Add late LTO optimization passes.
2362 FunctionPassManager LateFPM;
2363
2364 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2365 // canonicalization pass that enables other optimizations. As a result,
2366 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2367 // result too early.
2368 LateFPM.addPass(LoopSinkPass());
2369
2370 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2371 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2372 // flattening of blocks.
2373 LateFPM.addPass(DivRemPairsPass());
2374
2375 // Delete basic blocks, which optimization passes may have killed.
2377 .convertSwitchRangeToICmp(true)
2378 .convertSwitchToArithmetic(true)
2379 .hoistCommonInsts(true)
2380 .speculateUnpredictables(true)));
2381 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2382
2383 // Drop bodies of available eternally objects to improve GlobalDCE.
2385
2386 // Now that we have optimized the program, discard unreachable functions.
2387 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2388
2389 if (PTO.MergeFunctions)
2391
2393
2394 if (PTO.CallGraphProfile)
2395 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2396
2397 MPM.addPass(CoroCleanupPass());
2398
2399 // AllocToken transforms heap allocation calls; this needs to run late after
2400 // other allocation call transformations (such as those in InstCombine).
2401 MPM.addPass(AllocTokenPass());
2402
2404
2405 // Emit annotation remarks.
2407
2408 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2409
2410 return MPM;
2411}
2412
2416 assert(Level == OptimizationLevel::O0 &&
2417 "buildO0DefaultPipeline should only be used with O0");
2418
2420
2421 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2422
2423 // Perform pseudo probe instrumentation in O0 mode. This is for the
2424 // consistency between different build modes. For example, a LTO build can be
2425 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2426 // the postlink will require pseudo probe instrumentation in the prelink.
2427 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2429
2430 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2431 PGOOpt->Action == PGOOptions::IRUse))
2433 MPM,
2434 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2435 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2436 PGOOpt->ProfileRemappingFile);
2437
2438 // Instrument function entry and exit before all inlining.
2440 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2441
2443
2444 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2446
2447 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2448 // Explicitly disable sample loader inlining and use flattened profile in O0
2449 // pipeline.
2450 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2451 PGOOpt->ProfileRemappingFile,
2453 /*DisableSampleProfileInlining=*/true,
2454 /*UseFlattenedProfile=*/true));
2455 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2456 // RequireAnalysisPass for PSI before subsequent non-module passes.
2458 }
2459
2461
2462 // Build a minimal pipeline based on the semantics required by LLVM,
2463 // which is just that always inlining occurs. Further, disable generating
2464 // lifetime intrinsics to avoid enabling further optimizations during
2465 // code generation.
2467 /*InsertLifetimeIntrinsics=*/false));
2468
2469 if (PTO.MergeFunctions)
2471
2472 if (EnableMatrix)
2473 MPM.addPass(
2475
2476 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2477 CGSCCPassManager CGPM;
2479 if (!CGPM.isEmpty())
2481 }
2482 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2483 LoopPassManager LPM;
2485 if (!LPM.isEmpty()) {
2487 createFunctionToLoopPassAdaptor(std::move(LPM))));
2488 }
2489 }
2490 if (!LoopOptimizerEndEPCallbacks.empty()) {
2491 LoopPassManager LPM;
2493 if (!LPM.isEmpty()) {
2495 createFunctionToLoopPassAdaptor(std::move(LPM))));
2496 }
2497 }
2498 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2501 if (!FPM.isEmpty())
2502 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2503 }
2504
2506
2507 if (!VectorizerStartEPCallbacks.empty()) {
2510 if (!FPM.isEmpty())
2511 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2512 }
2513
2514 if (!VectorizerEndEPCallbacks.empty()) {
2517 if (!FPM.isEmpty())
2518 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2519 }
2520
2522
2523 // AllocToken transforms heap allocation calls; this needs to run late after
2524 // other allocation call transformations (such as those in InstCombine).
2525 if (!isLTOPreLink(Phase))
2526 MPM.addPass(AllocTokenPass());
2527
2529
2531 MPM.addPass(InstrumentorPass(FS));
2532
2533 // Attach !implicit.ref metadata from all functions to copyright strings.
2535
2536 if (isLTOPreLink(Phase))
2537 addRequiredLTOPreLinkPasses(MPM);
2538
2539 // Emit annotation remarks.
2541
2542 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2543
2544 return MPM;
2545}
2546
2548 AAManager AA;
2549
2550 // The order in which these are registered determines their priority when
2551 // being queried.
2552
2553 // Add any target-specific alias analyses that should be run early.
2554 if (TM)
2555 TM->registerEarlyDefaultAliasAnalyses(AA);
2556
2557 // First we register the basic alias analysis that provides the majority of
2558 // per-function local AA logic. This is a stateless, on-demand local set of
2559 // AA techniques.
2560 AA.registerFunctionAnalysis<BasicAA>();
2561
2562 // Next we query fast, specialized alias analyses that wrap IR-embedded
2563 // information about aliasing.
2564 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2565 AA.registerFunctionAnalysis<TypeBasedAA>();
2566
2567 // Add support for querying global aliasing information when available.
2568 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2569 // analysis, all that the `AAManager` can do is query for any *cached*
2570 // results from `GlobalsAA` through a readonly proxy.
2572 AA.registerModuleAnalysis<GlobalsAA>();
2573
2574 // Add target-specific alias analyses.
2575 if (TM)
2576 TM->registerDefaultAliasAnalyses(AA);
2577
2578 return AA;
2579}
2580
2581bool PassBuilder::isInstrumentedPGOUse() const {
2582 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2583 !UseCtxProfile.empty();
2584}
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.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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.
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:123
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
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 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 void invokeThinLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, 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 invokeThinLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
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:75
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
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"))
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
@ O3
Optimize for fast execution as much as possible.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
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< 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:521
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition GVN.h:528
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.