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 "PassesOptions.h"
18#include "llvm/ADT/Statistic.h"
30#include "llvm/IR/PassManager.h"
31#include "llvm/IR/Verifier.h"
32#include "llvm/Pass.h"
162
163using namespace llvm;
164
165namespace llvm {
167
169
171} // namespace llvm
172
174 const cl::LibraryOptionsContext &LibraryOptions) const {
175 const PassesOptions &Opts = LibraryOptions.get<PassesOptions>();
176 PipelineTuningOptions R = *this;
177 R.LoopInterchange = LoopInterchange.value_or(Opts.enable_loopinterchange);
178 R.ForgetAllSCEVInLoopUnroll = ForgetAllSCEVInLoopUnroll.value_or(
179 getForgetSCEVInLoopUnroll(LibraryOptions));
180 R.LicmMssaOptCap = LicmMssaOptCap.value_or(getLicmMssaOptCap(LibraryOptions));
181 R.LicmMssaNoAccForPromotionCap = LicmMssaNoAccForPromotionCap.value_or(
182 getLicmMssaNoAccForPromotionCap(LibraryOptions));
183 R.MergeFunctions = MergeFunctions.value_or(Opts.enable_merge_functions);
184 R.MaxDevirtIterations =
185 MaxDevirtIterations.value_or(getMaxDevirtIterations(LibraryOptions));
186 R.EagerlyInvalidateAnalyses =
187 EagerlyInvalidateAnalyses.value_or(Opts.eagerly_invalidate_analyses);
188 R.DevirtualizeSpeculatively = DevirtualizeSpeculatively.value_or(
189 Opts.enable_devirtualize_speculatively);
190 return R;
191}
192
194 OptimizationLevel Level) {
195 for (auto &C : PeepholeEPCallbacks)
196 C(FPM, Level);
197}
200 for (auto &C : LateLoopOptimizationsEPCallbacks)
201 C(LPM, Level);
202}
204 OptimizationLevel Level) {
205 for (auto &C : LoopOptimizerEndEPCallbacks)
206 C(LPM, Level);
207}
210 for (auto &C : ScalarOptimizerLateEPCallbacks)
211 C(FPM, Level);
212}
214 OptimizationLevel Level) {
215 for (auto &C : CGSCCOptimizerLateEPCallbacks)
216 C(CGPM, Level);
217}
219 OptimizationLevel Level) {
220 for (auto &C : VectorizerStartEPCallbacks)
221 C(FPM, Level);
222}
224 OptimizationLevel Level) {
225 for (auto &C : VectorizerEndEPCallbacks)
226 C(FPM, Level);
227}
229 OptimizationLevel Level,
231 for (auto &C : OptimizerEarlyEPCallbacks)
232 C(MPM, Level, Phase);
233}
235 OptimizationLevel Level,
237 for (auto &C : OptimizerLastEPCallbacks)
238 C(MPM, Level, Phase);
239}
242 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
243 C(MPM, Level);
244}
247 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
248 C(MPM, Level);
249}
252 for (auto &C : ThinLinkTimeOptimizationEarlyEPCallbacks)
253 C(MPM, Level);
254}
257 for (auto &C : ThinLinkTimeOptimizationLastEPCallbacks)
258 C(MPM, Level);
259}
261 OptimizationLevel Level) {
262 for (auto &C : PipelineStartEPCallbacks)
263 C(MPM, Level);
264}
267 for (auto &C : PipelineEarlySimplificationEPCallbacks)
268 C(MPM, Level, Phase);
269}
270
271// Get IR stats with InstCount before/after the optimization pipeline
273 bool IsPreOptimization) {
274 if (AreStatisticsEnabled()) {
275 MPM.addPass(
278 FunctionPropertiesStatisticsPass(IsPreOptimization)));
279 }
280}
281
282// Add passes to run at the start of the pipeline. This includes things like
283// statistics passes.
285 const PassesOptions &Opts) {
286 instructionCountersPass(MPM, /*IsPreOptimization=*/true);
289}
290
291// Add passes to run at the end of the pipeline. This includes things like
292// statistics passes.
294 const PassesOptions &Opts) {
295 instructionCountersPass(MPM, /*IsPreOptimization=*/false);
298}
299
300// Helper to add AnnotationRemarksPass.
304
305// Helper to check if the current compilation phase is preparing for LTO
310
311// Helper to check if the current compilation phase is preparing for FullLTO
312[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
314}
315
316// Helper to check if the current compilation phase is preparing for ThinLTO
320
321// Helper to check if the current compilation phase is LTO backend
326
327// Helper to check if the current compilation phase is FullLTO backend
331
332// Helper to check if the current compilation phase is ThinLTO backend
336
337// Helper to wrap conditionally Coro passes.
339 // TODO: Skip passes according to Phase.
340 ModulePassManager CoroPM;
341 CoroPM.addPass(CoroEarlyPass());
342 CGSCCPassManager CGPM;
343 CGPM.addPass(CoroSplitPass());
344 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
345 CoroPM.addPass(CoroCleanupPass());
346 CoroPM.addPass(GlobalDCEPass());
347 return CoroConditionalWrapper(std::move(CoroPM));
348}
349
351 OptimizationLevel Level) {
352 return getInlineParamsFromOptLevel(Context, static_cast<unsigned>(Level));
353}
354
356 const LLVMContext &Context,
357 OptimizationLevel Level,
359 const PassesOptions &Opts = getPassesOptions(Context);
360 InlineParams IP = ::getInlineParamsFromOptLevel(Context, Level);
361 if (Opts.enable_module_inliner)
362 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
363 else
365 IP,
366 /* MandatoryFirst */ true,
368}
369
370// TODO: Investigate the cost/benefit of tail call elimination on debugging.
372PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
374
376
378 FPM.addPass(CountVisitsPass());
379
380 // Form SSA out of local memory accesses after breaking apart aggregates into
381 // scalars.
382 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
383
384 // Catch trivial redundancies
385 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
386
387 // Hoisting of scalars and load expressions.
388 FPM.addPass(
389 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
390 FPM.addPass(InstCombinePass());
391
392 FPM.addPass(LibCallsShrinkWrapPass());
393
394 invokePeepholeEPCallbacks(FPM, Level);
395
396 FPM.addPass(
397 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
398
399 // Form canonically associated expression trees, and simplify the trees using
400 // basic mathematical properties. For example, this will form (nearly)
401 // minimal multiplication trees.
402 FPM.addPass(ReassociatePass());
403
404 // Add the primary loop simplification pipeline.
405 // FIXME: Currently this is split into two loop pass pipelines because we run
406 // some function passes in between them. These can and should be removed
407 // and/or replaced by scheduling the loop pass equivalents in the correct
408 // positions. But those equivalent passes aren't powerful enough yet.
409 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
410 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
411 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
412 // `LoopInstSimplify`.
413 LoopPassManager LPM1, LPM2;
414
415 // Simplify the loop body. We do this initially to clean up after other loop
416 // passes run, either when iterating on a loop or on inner loops with
417 // implications on the outer loop.
418 LPM1.addPass(LoopInstSimplifyPass());
419 LPM1.addPass(LoopSimplifyCFGPass());
420
421 // Try to remove as much code from the loop header as possible,
422 // to reduce amount of IR that will have to be duplicated. However,
423 // do not perform speculative hoisting the first time as LICM
424 // will destroy metadata that may not need to be destroyed if run
425 // after loop rotation.
426 // TODO: Investigate promotion cap for O1.
427 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
428 /*AllowSpeculation=*/false));
429
430 LPM1.addPass(
431 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
432 // TODO: Investigate promotion cap for O1.
433 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
434 /*AllowSpeculation=*/true));
435 LPM1.addPass(SimpleLoopUnswitchPass());
436 if (Opts.enable_loop_flatten)
437 LPM1.addPass(LoopFlattenPass());
438
439 LPM2.addPass(LoopIdiomRecognizePass());
440 LPM2.addPass(IndVarSimplifyPass());
441
443
444 LPM2.addPass(LoopDeletionPass());
445
446 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
447 // because it changes IR to makes profile annotation in back compile
448 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
449 // attributes so we need to make sure and allow the full unroll pass to pay
450 // attention to it.
451 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
452 PGOOpt->Action != PGOOptions::SampleUse)
453 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
454 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
455 *PTO.ForgetAllSCEVInLoopUnroll));
456
458
459 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
460 /*UseMemorySSA=*/true));
461 FPM.addPass(
462 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
463 FPM.addPass(InstCombinePass());
464 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
465 // *All* loop passes must preserve it, in order to be able to use it.
466 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
467 /*UseMemorySSA=*/false));
468
469 // Delete small array after loop unroll.
470 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
471
472 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
473 FPM.addPass(MemCpyOptPass());
474
475 // Sparse conditional constant propagation.
476 // FIXME: It isn't clear why we do this *after* loop passes rather than
477 // before...
478 FPM.addPass(SCCPPass());
479
480 // Delete dead bit computations (instcombine runs after to fold away the dead
481 // computations, and then ADCE will run later to exploit any new DCE
482 // opportunities that creates).
483 FPM.addPass(BDCEPass());
484
485 // Run instcombine after redundancy and dead bit elimination to exploit
486 // opportunities opened up by them.
487 FPM.addPass(InstCombinePass());
488 invokePeepholeEPCallbacks(FPM, Level);
489
490 FPM.addPass(CoroElidePass());
491
493
494 // Finally, do an expensive DCE pass to catch all the dead code exposed by
495 // the simplifications and basic cleanup after all the simplifications.
496 // TODO: Investigate if this is too expensive.
497 FPM.addPass(ADCEPass());
498 FPM.addPass(
499 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
500 FPM.addPass(InstCombinePass());
501 invokePeepholeEPCallbacks(FPM, Level);
502
503 return FPM;
504}
505
509 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
510
511 // The O1 pipeline has a separate pipeline creation function to simplify
512 // construction readability.
513 if (Level == OptimizationLevel::O1)
514 return buildO1FunctionSimplificationPipeline(Level, Phase);
515
517
520
521 // Form SSA out of local memory accesses after breaking apart aggregates into
522 // scalars.
524
525 // Catch trivial redundancies
526 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
529
530 // Hoisting of scalars and load expressions.
531 if (Opts.enable_gvn_hoist)
532 FPM.addPass(GVNHoistPass());
533
534 // Global value numbering based sinking.
535 if (Opts.enable_gvn_sink) {
536 FPM.addPass(GVNSinkPass());
537 FPM.addPass(
538 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
539 }
540
541 // Speculative execution if the target has divergent branches; otherwise nop.
542 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
543
544 // Optimize based on known information about branches, and cleanup afterward.
547
548 // Jump table to switch conversion.
549 if (Opts.enable_jump_table_to_switch)
551
552 FPM.addPass(
553 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
557
558 invokePeepholeEPCallbacks(FPM, Level);
559
560 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
561 // using the size value profile. Don't perform this when optimizing for size.
562 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
564
565 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
566 isInstrumentedPGOUse()));
567 FPM.addPass(
568 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
569
570 // Form canonically associated expression trees, and simplify the trees using
571 // basic mathematical properties. For example, this will form (nearly)
572 // minimal multiplication trees.
574
575 if (Opts.enable_constraint_elimination)
577
578 // Add the primary loop simplification pipeline.
579 // FIXME: Currently this is split into two loop pass pipelines because we run
580 // some function passes in between them. These can and should be removed
581 // and/or replaced by scheduling the loop pass equivalents in the correct
582 // positions. But those equivalent passes aren't powerful enough yet.
583 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
584 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
585 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
586 // `LoopInstSimplify`.
587 LoopPassManager LPM1, LPM2;
588
589 // Simplify the loop body. We do this initially to clean up after other loop
590 // passes run, either when iterating on a loop or on inner loops with
591 // implications on the outer loop.
592 LPM1.addPass(LoopInstSimplifyPass());
593 LPM1.addPass(LoopSimplifyCFGPass());
594
595 // Try to remove as much code from the loop header as possible,
596 // to reduce amount of IR that will have to be duplicated. However,
597 // do not perform speculative hoisting the first time as LICM
598 // will destroy metadata that may not need to be destroyed if run
599 // after loop rotation.
600 // TODO: Investigate promotion cap for O1.
601 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
602 /*AllowSpeculation=*/false));
603
604 LPM1.addPass(
605 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
606 // TODO: Investigate promotion cap for O1.
607 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
608 /*AllowSpeculation=*/true));
609 LPM1.addPass(
610 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
611 if (Opts.enable_loop_flatten)
612 LPM1.addPass(LoopFlattenPass());
613
614 LPM2.addPass(LoopIdiomRecognizePass());
615 LPM2.addPass(IndVarSimplifyPass());
616
617 {
619 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
621 LPM2.addPass(std::move(ExtraPasses));
622 }
623
625
626 LPM2.addPass(LoopDeletionPass());
627
628 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
629 // because it changes IR to makes profile annotation in back compile
630 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
631 // attributes so we need to make sure and allow the full unroll pass to pay
632 // attention to it.
633 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
634 PGOOpt->Action != PGOOptions::SampleUse)
635 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
636 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
637 *PTO.ForgetAllSCEVInLoopUnroll));
638
640
641 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
642 /*UseMemorySSA=*/true));
643 FPM.addPass(
644 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
646 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
647 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
648 // *All* loop passes must preserve it, in order to be able to use it.
649 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
650 /*UseMemorySSA=*/false));
651
652 // Delete small array after loop unroll.
654
655 // Try vectorization/scalarization transforms that are both improvements
656 // themselves and can allow further folds with GVN and InstCombine.
657 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
658
659 // Eliminate redundancies.
661 if (Opts.enable_newgvn)
662 FPM.addPass(NewGVNPass());
663 else
664 FPM.addPass(GVNPass());
665
666 // Sparse conditional constant propagation.
667 // FIXME: It isn't clear why we do this *after* loop passes rather than
668 // before...
669 FPM.addPass(SCCPPass());
670
671 // Delete dead bit computations (instcombine runs after to fold away the dead
672 // computations, and then ADCE will run later to exploit any new DCE
673 // opportunities that creates).
674 FPM.addPass(BDCEPass());
675
676 // Run instcombine after redundancy and dead bit elimination to exploit
677 // opportunities opened up by them.
679 invokePeepholeEPCallbacks(FPM, Level);
680
681 // Re-consider control flow based optimizations after redundancy elimination,
682 // redo DCE, etc.
683 if (Opts.enable_dfa_jump_thread)
685
688
689 // Finally, do an expensive DCE pass to catch all the dead code exposed by
690 // the simplifications and basic cleanup after all the simplifications.
691 // TODO: Investigate if this is too expensive.
692 FPM.addPass(ADCEPass());
693
694 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
695 FPM.addPass(MemCpyOptPass());
696
697 FPM.addPass(DSEPass());
699
701 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
702 /*AllowSpeculation=*/true),
703 /*UseMemorySSA=*/true));
704
705 FPM.addPass(CoroElidePass());
706
708
710 .convertSwitchRangeToICmp(true)
711 .convertSwitchToArithmetic(true)
712 .hoistCommonInsts(true)
713 .sinkCommonInsts(true)));
715 invokePeepholeEPCallbacks(FPM, Level);
716
717 return FPM;
718}
719
720void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
723 MPM.addPass(AssignGUIDPass());
724}
725
726void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
727 OptimizationLevel Level,
728 ThinOrFullLTOPhase LTOPhase,
729 bool IgnoreProfile) {
730 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
731 if (Opts.disable_preinline)
732 return;
733 InlineParams IP;
734
735 IP.DefaultThreshold = Opts.preinline_threshold;
736 IP.IgnoreProfile = IgnoreProfile;
737
738 // FIXME: The hint threshold has the same value used by the regular inliner
739 // when not optimzing for size. This should probably be lowered after
740 // performance testing.
741 // FIXME: this comment is cargo culted from the old pass manager, revisit).
742 IP.HintThreshold = 325;
743 IP.OptSizeHintThreshold = Opts.preinline_threshold;
745 IP, /* MandatoryFirst */ true,
747 CGSCCPassManager &CGPipeline = MIWP.getPM();
748
750 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
751 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
752 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
753 true))); // Merge & remove basic blocks.
754 FPM.addPass(InstCombinePass()); // Combine silly sequences.
755 invokePeepholeEPCallbacks(FPM, Level);
756
757 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
758 std::move(FPM), *PTO.EagerlyInvalidateAnalyses));
759
760 MPM.addPass(std::move(MIWP));
761
762 // Delete anything that is now dead to make sure that we don't instrument
763 // dead code. Instrumentation can end up keeping dead code around and
764 // dramatically increase code size.
765 MPM.addPass(GlobalDCEPass());
766}
767
768void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
769 OptimizationLevel Level) {
770 if (Opts.enable_post_pgo_loop_rotation) {
771 // Disable header duplication in loop rotation at -Oz.
773 createFunctionToLoopPassAdaptor(LoopRotatePass(),
774 /*UseMemorySSA=*/false),
775 *PTO.EagerlyInvalidateAnalyses));
776 }
777}
778
779void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
780 OptimizationLevel Level, bool RunProfileGen,
781 bool IsCS, bool AtomicCounterUpdate,
782 std::string ProfileFile,
783 std::string ProfileRemappingFile) {
784 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
785
786 if (!RunProfileGen) {
787 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
788 MPM.addPass(
789 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
790 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
791 // RequireAnalysisPass for PSI before subsequent non-module passes.
792 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
793 return;
794 }
795
796 // Perform PGO instrumentation.
797 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
799
800 addPostPGOLoopRotation(MPM, Level);
801 // Add the profile lowering pass.
802 InstrProfOptions Options;
803 if (!ProfileFile.empty())
804 Options.InstrProfileOutput = ProfileFile;
805 // Do counter promotion at Level greater than O0.
806 Options.DoCounterPromotion = true;
807 Options.UseBFIInPromotion = IsCS;
808 if (Opts.enable_sampled_instrumentation) {
809 Options.Sampling = true;
810 // With sampling, there is little beneifit to enable counter promotion.
811 // But note that sampling does work with counter promotion.
812 Options.DoCounterPromotion = false;
813 }
814 Options.Atomic = AtomicCounterUpdate;
815 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
816}
817
819 bool RunProfileGen, bool IsCS,
820 bool AtomicCounterUpdate,
821 std::string ProfileFile,
822 std::string ProfileRemappingFile) {
823 if (!RunProfileGen) {
824 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
825 MPM.addPass(
826 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
827 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
828 // RequireAnalysisPass for PSI before subsequent non-module passes.
830 return;
831 }
832
833 // Perform PGO instrumentation.
836 // Add the profile lowering pass.
838 if (!ProfileFile.empty())
839 Options.InstrProfileOutput = ProfileFile;
840 // Do not do counter promotion at O0.
841 Options.DoCounterPromotion = false;
842 Options.UseBFIInPromotion = IsCS;
843 Options.Atomic = AtomicCounterUpdate;
845}
846
850 InlineParams IP;
851 if (PTO.InlinerThreshold == -1)
852 IP = ::getInlineParamsFromOptLevel(Context, Level);
853 else
854 IP = getInlineParams(Context, PTO.InlinerThreshold);
855 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
856 // set hot-caller threshold to 0 to disable hot
857 // callsite inline (as much as possible [1]) because it makes
858 // profile annotation in the backend inaccurate.
859 //
860 // [1] Note the cost of a function could be below zero due to erased
861 // prologue / epilogue.
862 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
864
865 if (PGOOpt)
866 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
867
868 ModuleInlinerWrapperPass MIWP(IP, Opts.mandatory_inlining_first,
869 InlineContext{Phase, InlinePass::CGSCCInliner},
870 Opts.enable_ml_inliner,
871 *PTO.MaxDevirtIterations);
872
873 // Require the GlobalsAA analysis for the module so we can query it within
874 // the CGSCC pipeline.
875 if (Opts.enable_global_analyses) {
877 // Invalidate AAManager so it can be recreated and pick up the newly
878 // available GlobalsAA.
879 MIWP.addModulePass(
881 }
882
883 // Require the ProfileSummaryAnalysis for the module so we can query it within
884 // the inliner pass.
886
887 // Now begin the main postorder CGSCC pipeline.
888 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
889 // manager and trying to emulate its precise behavior. Much of this doesn't
890 // make a lot of sense and we should revisit the core CGSCC structure.
891 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
892
893 // Note: historically, the PruneEH pass was run first to deduce nounwind and
894 // generally clean up exception handling overhead. It isn't clear this is
895 // valuable as the inliner doesn't currently care whether it is inlining an
896 // invoke or a call.
897
898 if (Opts.attributor_enable & AttributorRunOption::CGSCC)
899 MainCGPipeline.addPass(AttributorCGSCCPass());
900
901 // Deduce function attributes. We do another run of this after the function
902 // simplification pipeline, so this only needs to run when it could affect the
903 // function simplification pipeline, which is only the case with recursive
904 // functions.
905 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
906 MainCGPipeline.addPass(AttributorLightCGSCCPass());
907 } else {
908 MainCGPipeline.addPass(
909 PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
910 }
911
912 // When at O3 add argument promotion to the pass pipeline.
913 // FIXME: It isn't at all clear why this should be limited to O3.
914 if (Level == OptimizationLevel::O3)
915 MainCGPipeline.addPass(ArgumentPromotionPass());
916
917 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
918 // there are no OpenMP runtime calls present in the module.
919 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
920 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
921
922 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
923
924 // Add the core function simplification pipeline nested inside the
925 // CGSCC walk.
928 *PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
929
930 // Finally, deduce any function attributes based on the fully simplified
931 // function.
932 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
933 MainCGPipeline.addPass(AttributorLightCGSCCPass());
934 else
935 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
936
937 // Mark that the function is fully simplified and that it shouldn't be
938 // simplified again if we somehow revisit it due to CGSCC mutations unless
939 // it's been modified since.
942
943 if (!isThinLTOPreLink(Phase)) {
944 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
945 MainCGPipeline.addPass(CoroAnnotationElidePass());
946 }
947
948 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
951
952 return MIWP;
953}
954
959
960 InlineParams IP = ::getInlineParamsFromOptLevel(Context, Level);
961 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
962 // set hot-caller threshold to 0 to disable hot
963 // callsite inline (as much as possible [1]) because it makes
964 // profile annotation in the backend inaccurate.
965 //
966 // [1] Note the cost of a function could be below zero due to erased
967 // prologue / epilogue.
968 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
970
971 if (PGOOpt)
972 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
973
974 // The inline deferral logic is used to avoid losing some
975 // inlining chance in future. It is helpful in SCC inliner, in which
976 // inlining is processed in bottom-up order.
977 // While in module inliner, the inlining order is a priority-based order
978 // by default. The inline deferral is unnecessary there. So we disable the
979 // inline deferral logic in module inliner.
980 IP.EnableDeferral = false;
981
982 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
984 MPM.addPass(GlobalOptPass());
985 MPM.addPass(GlobalDCEPass());
986 MPM.addPass(AssignGUIDPass());
987 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
988 }
989
992 *PTO.EagerlyInvalidateAnalyses));
993
994 if (!isThinLTOPreLink(Phase)) {
997 MPM.addPass(
999 }
1000
1001 return MPM;
1002}
1003
1006 const ModuleSummaryIndex *ImportSummary) {
1007 assert(Level != OptimizationLevel::O0 &&
1008 "Should not be used for O0 pipeline");
1009
1011 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1012
1013 assert((!ImportSummary || isThinLTOPostLink(Phase)) &&
1014 "ImportSummary is only meaningful in the ThinLTO post link phase");
1015
1017
1018 // Place pseudo probe instrumentation as the first pass of the pipeline to
1019 // minimize the impact of optimization changes.
1020 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1022
1023 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1024
1025 // In ThinLTO mode, when flattened profile is used, all the available
1026 // profile information will be annotated in PreLink phase so there is
1027 // no need to load the profile again in PostLink.
1028 bool LoadSampleProfile = HasSampleProfile && !(Opts.flattened_profile_used &&
1030
1031 // During the ThinLTO backend phase we perform early indirect call promotion
1032 // here, before globalopt. Otherwise imported available_externally functions
1033 // look unreferenced and are removed. If we are going to load the sample
1034 // profile then defer until later.
1035 // TODO: See if we can move later and consolidate with the location where
1036 // we perform ICP when we are loading a sample profile.
1037 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1038 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1039 // determine whether the new direct calls are annotated with prof metadata.
1040 // Ideally this should be determined from whether the IR is annotated with
1041 // sample profile, and not whether the a sample profile was provided on the
1042 // command line. E.g. for flattened profiles where we will not be reloading
1043 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1044 // provide the sample profile file.
1045 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1046 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile,
1047 ImportSummary));
1048
1049 // Create an early function pass manager to cleanup the output of the
1050 // frontend. Not necessary with LTO post link pipelines since the pre link
1051 // pipeline already cleaned up the frontend output.
1052 if (!isThinLTOPostLink(Phase)) {
1053 // Do basic inference of function attributes from known properties of system
1054 // libraries and other oracles.
1056 MPM.addPass(CoroEarlyPass());
1057
1058 FunctionPassManager EarlyFPM;
1059 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1060 // Lower llvm.expect to metadata before attempting transforms.
1061 // Compare/branch metadata may alter the behavior of passes like
1062 // SimplifyCFG.
1064 EarlyFPM.addPass(SimplifyCFGPass());
1066 EarlyFPM.addPass(EarlyCSEPass());
1067 if (Level == OptimizationLevel::O3)
1068 EarlyFPM.addPass(CallSiteSplittingPass());
1070 std::move(EarlyFPM), *PTO.EagerlyInvalidateAnalyses));
1071 }
1072
1073 if (LoadSampleProfile) {
1074 // Annotate sample profile right after early FPM to ensure freshness of
1075 // the debug info.
1077 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1078 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1079 // RequireAnalysisPass for PSI before subsequent non-module passes.
1081 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1082 // for the profile annotation to be accurate in the LTO backend.
1083 if (!isLTOPreLink(Phase))
1084 // We perform early indirect call promotion here, before globalopt.
1085 // This is important for the ThinLTO backend phase because otherwise
1086 // imported available_externally functions look unreferenced and are
1087 // removed.
1089 true /* IsInLTO */, true /* SamplePGO */, ImportSummary));
1090 }
1091
1092 // Try to perform OpenMP specific optimizations on the module. This is a
1093 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1095
1096 if (Opts.attributor_enable & AttributorRunOption::MODULE)
1097 MPM.addPass(AttributorPass());
1098 else if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1100
1101 // Lower type metadata and the type.test intrinsic in the ThinLTO post link
1102 // pipeline after ICP. This is to enable usage of the type tests in ICP
1103 // sequences. It also lets ICP (including the ICP performed by the sample
1104 // profile loader) see the original names of the CFI functions it wants to
1105 // promote to, which LowerTypeTests renames to <name>.cfi.
1106 if (isThinLTOPostLink(Phase)) {
1107 if (ImportSummary)
1108 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1110 }
1111
1113
1114 // Interprocedural constant propagation now that basic cleanup has occurred
1115 // and prior to optimizing globals.
1116 // FIXME: This position in the pipeline hasn't been carefully considered in
1117 // years, it should be re-analyzed.
1118 MPM.addPass(
1119 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1120
1121 // Attach metadata to indirect call sites indicating the set of functions
1122 // they may target at run-time. This should follow IPSCCP.
1124
1125 // Optimize globals to try and fold them into constants.
1126 MPM.addPass(GlobalOptPass());
1127
1128 // Create a small function pass pipeline to cleanup after all the global
1129 // optimizations.
1130 FunctionPassManager GlobalCleanupPM;
1131 // FIXME: Should this instead by a run of SROA?
1132 GlobalCleanupPM.addPass(PromotePass());
1133 GlobalCleanupPM.addPass(InstCombinePass());
1134 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1135 GlobalCleanupPM.addPass(
1136 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1138 std::move(GlobalCleanupPM), *PTO.EagerlyInvalidateAnalyses));
1139
1140 // We already asserted this happens in non-FullLTOPostLink earlier.
1141 const bool IsPreLink = !isThinLTOPostLink(Phase);
1142 // Enable contextual profiling instrumentation.
1143 const bool IsCtxProfGen =
1145 Context.getLibraryOptions());
1146 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1147 const bool IsPGOInstrGen =
1148 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1149 const bool IsPGOInstrUse =
1150 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1151 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1152 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1153 // enable ctx profiling from the frontend.
1155 Context.getLibraryOptions())) &&
1156 "Enabling both instrumented PGO and contextual instrumentation is not "
1157 "supported.");
1158 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1159
1160 assert((Opts.instrument_cold_function_only_path.empty() ||
1161 isPGOInstrumentColdFunctionOnly(Context.getLibraryOptions())) &&
1162 "--instrument-cold-function-only-path is provided but "
1163 "--pgo-instrument-cold-function-only is not enabled");
1164 const bool IsColdFuncOnlyInstrGen =
1165 isPGOInstrumentColdFunctionOnly(Context.getLibraryOptions()) &&
1166 IsPGOPreLink && !Opts.instrument_cold_function_only_path.empty();
1167
1168 // When a memory profile is used together with a sample profile, the
1169 // pre-inliner runs after the sample profile has been loaded. By default make
1170 // it ignore the sample profile, so that the inlining seen by MemProfUsePass
1171 // doesn't depend on the sample profile. Otherwise, a different sample profile
1172 // than the one used to build the memory-profiled binary can cause additional
1173 // inlining (e.g. of newly hot callees) that leads to memprof matching
1174 // failures. This matches the IR PGO pipeline, where the pre-inliner runs
1175 // before the profile is annotated.
1176 const bool PreInlinerIgnoreProfile =
1177 IsMemprofUse && HasSampleProfile && Opts.memprof_preinline_ignore_profile;
1178 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1179 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1180 addPreInlinerPasses(MPM, Level, Phase, PreInlinerIgnoreProfile);
1181
1182 // Add all the requested passes for instrumentation PGO, if requested.
1183 if (IsPGOInstrGen || IsPGOInstrUse) {
1184 addPGOInstrPasses(MPM, Level,
1185 /*RunProfileGen=*/IsPGOInstrGen,
1186 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1187 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1188 } else if (IsCtxProfGen || IsCtxProfUse) {
1190 // In pre-link, we just want the instrumented IR. We use the contextual
1191 // profile in the post-thinlink phase.
1192 // The instrumentation will be removed in post-thinlink after IPO.
1193 if (IsCtxProfUse) {
1194 MPM.addPass(AssignGUIDPass());
1195 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1196 return MPM;
1197 }
1198 // Block further inlining in the instrumented ctxprof case. This avoids
1199 // confusingly collecting profiles for the same GUID corresponding to
1200 // different variants of the function. We could do like PGO and identify
1201 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1202 // thinlto to happen before performing any further optimizations, it's
1203 // unnecessary to collect profiles for non-prevailing copies.
1205 addPostPGOLoopRotation(MPM, Level);
1206 MPM.addPass(AssignGUIDPass());
1208 } else if (IsColdFuncOnlyInstrGen) {
1209 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1210 /* AtomicCounterUpdate */ false,
1211 Opts.instrument_cold_function_only_path.str(),
1212 /* ProfileRemappingFile */ "");
1213 }
1214
1215 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1216 MPM.addPass(PGOIndirectCallPromotion(false, false));
1217
1218 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1220 PGOOpt->CSProfileGenFile, Opts.enable_sampled_instrumentation));
1221
1222 if (IsMemprofUse)
1223 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1224
1225 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1226 PGOOpt->Action == PGOOptions::SampleUse))
1227 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1228
1229 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1230
1231 if (Opts.enable_module_inliner)
1233 else
1234 MPM.addPass(buildInlinerPipeline(Level, Phase));
1235
1236 // Remove any dead arguments exposed by cleanups, constant folding globals,
1237 // and argument promotion.
1239
1242
1243 if (!isThinLTOPreLink(Phase))
1244 MPM.addPass(CoroCleanupPass());
1245
1246 // Optimize globals now that functions are fully simplified.
1247 MPM.addPass(GlobalOptPass());
1248 MPM.addPass(GlobalDCEPass());
1249
1250 return MPM;
1251}
1252
1253/// TODO: Should LTO cause any differences to this set of passes?
1254void PassBuilder::addVectorPasses(OptimizationLevel Level,
1256 ThinOrFullLTOPhase LTOPhase) {
1259
1260 // Drop dereferenceable assumes after vectorization, as they are no longer
1261 // needed and can inhibit further optimization.
1262 if (!isLTOPreLink(LTOPhase))
1263 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1264
1266 if (isFullLTOPostLink(LTOPhase)) {
1267 // The vectorizer may have significantly shortened a loop body; unroll
1268 // again. Unroll small loops to hide loop backedge latency and saturate any
1269 // parallel execution resources of an out-of-order processor. We also then
1270 // need to clean up redundancies and loop invariant code.
1271 // FIXME: It would be really good to use a loop-integrated instruction
1272 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1273 // across the loop nests.
1274 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1275 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling)
1277 LoopUnrollAndJamPass(static_cast<int>(Level))));
1279 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1282 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1283 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1284 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1285 // NOTE: we are very late in the pipeline, and we don't have any LICM
1286 // or SimplifyCFG passes scheduled after us, that would cleanup
1287 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1288
1289 // We also turn on struct to vector canonicalization here, which allows
1290 // converting allocas of homogeneous structs into vector allocas when the
1291 // allocas' users are all memory intrinsics. This allows promotion in some
1292 // cases because structs cannot promote to SSA values, but vectors can. We
1293 // only turn this on after memcpyopt runs because this might hinder
1294 // memcpyopt's optimizations if done before. Look at the documentation for
1295 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1297 /*AggregateToVector=*/true)));
1298 }
1299
1300 if (!isFullLTOPostLink(LTOPhase)) {
1301 // Eliminate loads by forwarding stores from the previous iteration to loads
1302 // of the current iteration.
1304 }
1305 // Cleanup after the loop optimization passes.
1306 FPM.addPass(InstCombinePass());
1307
1308 if (Level > OptimizationLevel::O1 && Opts.extra_vectorizer_passes) {
1309 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1310 // At higher optimization levels, try to clean up any runtime overlap and
1311 // alignment checks inserted by the vectorizer. We want to track correlated
1312 // runtime checks for two inner loops in the same outer loop, fold any
1313 // common computations, hoist loop-invariant aspects out of any outer loop,
1314 // and unswitch the runtime checks if possible. Once hoisted, we may have
1315 // dead (or speculatable) control flows or more combining opportunities.
1316 ExtraPasses.addPass(EarlyCSEPass());
1317 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1318 ExtraPasses.addPass(InstCombinePass());
1319 LoopPassManager LPM;
1320 LPM.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
1321 /*AllowSpeculation=*/true));
1322 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1324 ExtraPasses.addPass(
1325 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1326 ExtraPasses.addPass(
1327 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1328 ExtraPasses.addPass(InstCombinePass());
1329 FPM.addPass(std::move(ExtraPasses));
1330 }
1331
1332 // Now that we've formed fast to execute loop structures, we do further
1333 // optimizations. These are run afterward as they might block doing complex
1334 // analyses and transforms such as what are needed for loop vectorization.
1335
1336 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1337 // GVN, loop transforms, and others have already run, so it's now better to
1338 // convert to more optimized IR using more aggressive simplify CFG options.
1339 // The extra sinking transform can create larger basic blocks, so do this
1340 // before SLP vectorization.
1341 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1342 .forwardSwitchCondToPhi(true)
1343 .convertSwitchRangeToICmp(true)
1344 .convertSwitchToArithmetic(true)
1345 .convertSwitchToLookupTable(true)
1346 .needCanonicalLoops(false)
1347 .hoistCommonInsts(true)
1348 .sinkCommonInsts(true)));
1349
1350 if (isFullLTOPostLink(LTOPhase)) {
1351 FPM.addPass(SCCPPass());
1352 FPM.addPass(InstCombinePass());
1353 FPM.addPass(BDCEPass());
1354 }
1355
1356 // Optimize parallel scalar instruction chains into SIMD instructions.
1357 if (PTO.SLPVectorization) {
1358 FPM.addPass(SLPVectorizerPass());
1359 if (Level >= OptimizationLevel::O2 && Opts.extra_vectorizer_passes) {
1360 FPM.addPass(EarlyCSEPass());
1361 }
1362 }
1363 // Enhance/cleanup vector code.
1364 FPM.addPass(VectorCombinePass());
1365
1366 if (!isFullLTOPostLink(LTOPhase)) {
1367 FPM.addPass(InstCombinePass());
1368 // Unroll small loops to hide loop backedge latency and saturate any
1369 // parallel execution resources of an out-of-order processor. We also then
1370 // need to clean up redundancies and loop invariant code.
1371 // FIXME: It would be really good to use a loop-integrated instruction
1372 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1373 // across the loop nests.
1374 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1375 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling) {
1377 LoopUnrollAndJamPass(static_cast<int>(Level))));
1378 }
1379 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1380 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1381 *PTO.ForgetAllSCEVInLoopUnroll)));
1382 FPM.addPass(WarnMissedTransformationsPass());
1383 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1384 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1385 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1386 // NOTE: we are very late in the pipeline, and we don't have any LICM
1387 // or SimplifyCFG passes scheduled after us, that would cleanup
1388 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1389
1390 // We also turn on struct to vector canonicalization here, which allows
1391 // converting allocas of homogeneous structs into vector allocas when the
1392 // allocas' users are all memory intrinsics. This allows promotion in some
1393 // cases because structs cannot promote to SSA values, but vectors can. We
1394 // only turn this on after memcpyopt runs because this might hinder
1395 // memcpyopt's optimizations if done before. Look at the documentation for
1396 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1397 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1398 /*AggregateToVector=*/true)));
1399 }
1400
1401 FPM.addPass(InferAlignmentPass());
1402 FPM.addPass(InstCombinePass());
1403
1404 // This is needed for two reasons:
1405 // 1. It works around problems that instcombine introduces, such as sinking
1406 // expensive FP divides into loops containing multiplications using the
1407 // divide result.
1408 // 2. It helps to clean up some loop-invariant code created by the loop
1409 // unroll pass when IsFullLTO=false.
1411 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
1412 /*AllowSpeculation=*/true),
1413 /*UseMemorySSA=*/true));
1414
1415 // Now that we've vectorized and unrolled loops, we may have more refined
1416 // alignment information, try to re-derive it here.
1417 FPM.addPass(AlignmentFromAssumptionsPass());
1418}
1419
1422 ThinOrFullLTOPhase LTOPhase) {
1424
1425 // Run partial inlining pass to partially inline functions that have
1426 // large bodies.
1427 if (Opts.enable_partial_inlining)
1429
1430 // Remove avail extern fns and globals definitions since we aren't compiling
1431 // an object file for later LTO. For LTO we want to preserve these so they
1432 // are eligible for inlining at link-time. Note if they are unreferenced they
1433 // will be removed by GlobalDCE later, so this only impacts referenced
1434 // available externally globals. Eventually they will be suppressed during
1435 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1436 // may make globals referenced by available external functions dead and saves
1437 // running remaining passes on the eliminated functions. These should be
1438 // preserved during prelinking for link-time inlining decisions.
1439 if (!isLTOPreLink(LTOPhase))
1441
1442 // Do RPO function attribute inference across the module to forward-propagate
1443 // attributes where applicable.
1444 // FIXME: Is this really an optimization rather than a canonicalization?
1445 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1447 else
1449
1450 // Do a post inline PGO instrumentation and use pass. This is a context
1451 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1452 // cross-module inline has not been done yet. The context sensitive
1453 // instrumentation is after all the inlines are done.
1454 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1455 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1456 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1457 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1458 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1459 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1460 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1461 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1462 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1463 }
1464
1465 // Re-compute GlobalsAA here prior to function passes. This is particularly
1466 // useful as the above will have inlined, DCE'ed, and function-attr
1467 // propagated everything. We should at this point have a reasonably minimal
1468 // and richly annotated call graph. By computing aliasing and mod/ref
1469 // information for all local globals here, the late loop passes and notably
1470 // the vectorizer will be able to use them to help recognize vectorizable
1471 // memory operations.
1472 if (Opts.enable_global_analyses)
1474
1475 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1476
1477 FunctionPassManager OptimizePM;
1478
1479 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1480 // additional uses of the affected value may be introduced through inlining
1481 // and CSE.
1482 if (!isLTOPreLink(LTOPhase))
1483 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1484
1485 // Scheduling LoopVersioningLICM when inlining is over, because after that
1486 // we may see more accurate aliasing. Reason to run this late is that too
1487 // early versioning may prevent further inlining due to increase of code
1488 // size. Other optimizations which runs later might get benefit of no-alias
1489 // assumption in clone loop.
1490 if (Opts.enable_loop_versioning_licm) {
1491 OptimizePM.addPass(
1493 // LoopVersioningLICM pass might increase new LICM opportunities.
1495 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
1496 /*AllowSpeculation=*/true),
1497 /*USeMemorySSA=*/true));
1498 }
1499
1500 OptimizePM.addPass(Float2IntPass());
1501 // Defer until LTO post-link where some constants may become known.
1502 if (!isLTOPreLink(LTOPhase))
1504
1505 if (Opts.enable_matrix) {
1506 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1507 OptimizePM.addPass(EarlyCSEPass());
1508 }
1509
1510 // CHR pass should only be applied with the profile information.
1511 // The check is to check the profile summary information in CHR.
1512 if (Opts.enable_chr && Level == OptimizationLevel::O3)
1513 OptimizePM.addPass(ControlHeightReductionPass());
1514
1515 // FIXME: We need to run some loop optimizations to re-rotate loops after
1516 // simplifycfg and others undo their rotation.
1517
1518 // Optimize the loop execution. These passes operate on entire loop nests
1519 // rather than on each loop in an inside-out manner, and so they are actually
1520 // function passes.
1521
1522 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1523
1524 LoopPassManager LPM;
1525 // First rotate loops that may have been un-rotated by prior passes.
1526 // Disable header duplication at -Oz.
1527 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1528 isLTOPreLink(LTOPhase),
1529 /*CheckExitCount=*/true));
1530 // Some loops may have become dead by now. Try to delete them.
1531 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1532 // this may need to be revisited once we run GVN before loop deletion
1533 // in the simplification pipeline.
1534 LPM.addPass(LoopDeletionPass());
1535
1536 if (*PTO.LoopInterchange)
1537 LPM.addPass(LoopInterchangePass());
1538
1539 OptimizePM.addPass(
1540 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1541
1542 // FIXME: This may not be the right place in the pipeline.
1543 // We need to have the data to support the right place.
1544 if (PTO.LoopFusion)
1545 OptimizePM.addPass(LoopFusePass());
1546
1547 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1548 // into separate loop that would otherwise inhibit vectorization. This is
1549 // currently only performed for loops marked with the metadata
1550 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1551 OptimizePM.addPass(LoopDistributePass());
1552
1553 // Populates the VFABI attribute with the scalar-to-vector mappings
1554 // from the TargetLibraryInfo.
1555 OptimizePM.addPass(InjectTLIMappings());
1556
1557 addVectorPasses(Level, OptimizePM, LTOPhase);
1558
1559 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1560
1561 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1562 // canonicalization pass that enables other optimizations. As a result,
1563 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1564 // result too early.
1565 OptimizePM.addPass(LoopSinkPass());
1566
1567 // And finally clean up LCSSA form before generating code.
1568 OptimizePM.addPass(InstSimplifyPass());
1569
1570 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1571 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1572 // flattening of blocks.
1573 OptimizePM.addPass(DivRemPairsPass());
1574
1575 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1576 // TODO: move this further up so that it can be optimized by GVN, etc.
1577 if (Opts.enable_mergeicmps)
1578 OptimizePM.addPass(MergeICmpsPass());
1579 OptimizePM.addPass(ExpandMemCmpPass());
1580
1581 // Try to annotate calls that were created during optimization.
1582 OptimizePM.addPass(
1583 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1584
1585 // LoopSink (and other loop passes since the last simplifyCFG) might have
1586 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1587 OptimizePM.addPass(
1589 .convertSwitchRangeToICmp(true)
1590 .convertSwitchToArithmetic(true)
1591 .speculateUnpredictables(true)
1592 .hoistLoadsStoresWithCondFaulting(true)));
1593
1594 // Add the core optimizing pipeline.
1596 std::move(OptimizePM), *PTO.EagerlyInvalidateAnalyses));
1597
1598 // AllocToken transforms heap allocation calls; this needs to run late after
1599 // other allocation call transformations (such as those in InstCombine).
1600 if (!isLTOPreLink(LTOPhase))
1601 MPM.addPass(AllocTokenPass());
1602
1603 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1604
1605 // Run the Instrumentor pass late.
1606 if (Opts.enable_instrumentor)
1607 MPM.addPass(InstrumentorPass(FS));
1608
1609 // Split out cold code. Splitting is done late to avoid hiding context from
1610 // other optimizations and inadvertently regressing performance. The tradeoff
1611 // is that this has a higher code size cost than splitting early.
1612 if (Opts.hot_cold_split && !isLTOPreLink(LTOPhase))
1614
1615 // Now we need to do some global optimization transforms.
1616 // FIXME: It would seem like these should come first in the optimization
1617 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1618 // ordering here.
1619 MPM.addPass(GlobalDCEPass());
1621
1622 // Merge functions if requested. It has a better chance to merge functions
1623 // after ConstantMerge folded jump tables.
1624 if (*PTO.MergeFunctions)
1626
1627 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1628 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1629
1630 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1631 if (!isLTOPreLink(LTOPhase))
1633
1634 // Add devirtualization pass only when LTO is not enabled, as otherwise
1635 // the pass is already enabled in the LTO pipeline.
1636 if (*PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1637 // TODO: explore a better pipeline configuration that can improve
1638 // compilation time overhead.
1639 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1641 MPM.addPass(AssignGUIDPass());
1643 /*ExportSummary*/ nullptr,
1644 /*ImportSummary*/ nullptr,
1645 /*DevirtSpeculatively*/ *PTO.DevirtualizeSpeculatively));
1647 // Given that the devirtualization creates more opportunities for inlining,
1648 // we run the Inliner again here to maximize the optimization gain we
1649 // get from devirtualization.
1650 // Also, we can't run devirtualization before inlining because the
1651 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1652 // and those passes are only effective after inlining.
1653 addModuleInlinerPass(MPM, Context, Level, ThinOrFullLTOPhase::None);
1654 }
1655
1656 // Attach !implicit.ref metadata from all functions to copyright strings.
1658
1659 return MPM;
1660}
1661
1665 if (Level == OptimizationLevel::O0)
1666 return buildO0DefaultPipeline(Level, Phase);
1667
1669 addPipelineStartPasses(MPM, Opts);
1670 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1671 // are not running LTO. If that changes the below checks may need updating.
1673
1674 // If we are invoking this in non-LTO mode, remove any MemProf related
1675 // attributes and metadata, as we don't know whether we are linking with
1676 // a library containing the necessary interfaces.
1679
1680 // Convert @llvm.global.annotations to !annotation metadata.
1682
1683 // Force any function attributes we want the rest of the pipeline to observe.
1685
1686 if (Opts.opt_pipeline_trigger_crash)
1688
1689 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1691
1692 // Apply module pipeline start EP callback.
1694
1695 // Add the core simplification pipeline.
1697
1698 // Now add the optimization pipeline.
1700
1701 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1702 PGOOpt->Action == PGOOptions::SampleUse)
1704
1705 // Emit annotation remarks.
1707
1708 if (isLTOPreLink(Phase))
1709 addRequiredLTOPreLinkPasses(MPM);
1710
1711 addPipelineEndPasses(MPM, Opts);
1712 return MPM;
1713}
1714
1717 bool EmitSummary, bool Verify) {
1719
1720 addPipelineStartPasses(MPM, Opts);
1721
1722 if (ThinLTO)
1724 else
1726 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1727 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1728 // bitcode emission runs VerifierPass by default, which registers metadata
1729 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1730 // to get the same behavior.
1731 if (Verify)
1732 MPM.addPass(VerifierPass());
1733 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1734
1735 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1736 // like removing CFI/WPD related instructions. Note, we reuse
1737 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1738 // in FatLtoCleanup; checked-load cleanup is shared the other way, with
1739 // FatLtoCleanup calling lowertypetests::cleanUpTypeCheckedLoad.
1740 MPM.addPass(FatLtoCleanup());
1741
1742 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1743 // object code, only in the bitcode section, so drop it before we run
1744 // module optimization and generate machine code. If llvm.type.test() isn't in
1745 // the IR, this won't do anything.
1747
1748 // Use the ThinLTO post-link pipeline with sample profiling
1749 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1750 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1751 else {
1752 // ModuleSimplification does not run the coroutine passes for
1753 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1754 // builds, otherwise they will miscompile.
1755 if (ThinLTO) {
1756 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1757 // consideration.
1758 CGSCCPassManager CGPM;
1762 MPM.addPass(CoroCleanupPass());
1763 }
1764
1765 // otherwise, just use module optimization
1766 MPM.addPass(
1768 // Emit annotation remarks.
1770 }
1771
1772 addPipelineEndPasses(MPM, Opts);
1773
1774 return MPM;
1775}
1776
1779 if (Level == OptimizationLevel::O0)
1781
1783
1784 addPipelineStartPasses(MPM, Opts);
1785
1786 // Convert @llvm.global.annotations to !annotation metadata.
1788
1789 // Force any function attributes we want the rest of the pipeline to observe.
1791
1792 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1794
1795 // Apply module pipeline start EP callback.
1797
1798 // If we are planning to perform ThinLTO later, we don't bloat the code with
1799 // unrolling/vectorization/... now. Just simplify the module as much as we
1800 // can.
1803 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1804 // thinlto use the contextual info to perform imports; then use the contextual
1805 // profile in the post-thinlink phase.
1806 if (!UseCtxProfile.empty()) {
1807 addRequiredLTOPreLinkPasses(MPM);
1808 return MPM;
1809 }
1810
1811 // Run partial inlining pass to partially inline functions that have
1812 // large bodies.
1813 // FIXME: It isn't clear whether this is really the right place to run this
1814 // in ThinLTO. Because there is another canonicalization and simplification
1815 // phase that will run after the thin link, running this here ends up with
1816 // less information than will be available later and it may grow functions in
1817 // ways that aren't beneficial.
1818 if (Opts.enable_partial_inlining)
1820
1821 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1822 PGOOpt->Action == PGOOptions::SampleUse)
1824
1825 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1826 // optimization is going to be done in PostLink stage, but clang can't add
1827 // callbacks there in case of in-process ThinLTO called by linker.
1832
1833 // Emit annotation remarks.
1835
1836 // Attach !implicit.ref metadata from all functions to copyright strings.
1838
1839 addRequiredLTOPreLinkPasses(MPM);
1840
1841 addPipelineEndPasses(MPM, Opts);
1842
1843 return MPM;
1844}
1845
1847 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1849
1850 addPipelineStartPasses(MPM, Opts);
1851
1853
1854 // If we are invoking this without a summary index noting that we are linking
1855 // with a library containing the necessary APIs, remove any MemProf related
1856 // attributes and metadata.
1857 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1859
1860 if (ImportSummary) {
1861 // For ThinLTO we must apply the context disambiguation decisions early, to
1862 // ensure we can correctly match the callsites to summary data.
1865 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1866
1867 // WholeProgramDevirt imports type identifier resolutions for whole-program
1868 // devirtualization. It must run early because later passes may disturb the
1869 // specific instruction patterns that it looks for, creating dependencies on
1870 // resolutions that may not appear in the summary.
1871 //
1872 // For example, GVN may transform the pattern assume(type.test) appearing in
1873 // two basic blocks into assume(phi(type.test, type.test)), which would
1874 // transform a dependency on a WPD resolution into a dependency on a type
1875 // identifier resolution for CFI.
1876 //
1877 // Also, WPD has access to more precise information than ICP and can
1878 // devirtualize more effectively, so it should operate on the IR first.
1879 //
1880 // It also needs to run at -O0 to lower type metadata and intrinsics.
1881 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1882 }
1883
1884 // LowerTypeTests renames CFI functions to <name>.cfi, so with optimization
1885 // it runs in buildModuleSimplificationPipeline after ICP. Otherwise, lower
1886 // type tests here.
1887 if (Level == OptimizationLevel::O0) {
1888 if (ImportSummary)
1889 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1890 // Run a second time to clean up any type tests left behind by WPD for use
1891 // in ICP.
1894
1895 // AllocToken transforms heap allocation calls; this needs to run late after
1896 // other allocation call transformations (such as those in InstCombine).
1897 MPM.addPass(AllocTokenPass());
1898
1899 // Drop available_externally and unreferenced globals. This is necessary
1900 // with ThinLTO in order to avoid leaving undefined references to dead
1901 // globals in the object file.
1903 MPM.addPass(GlobalDCEPass());
1904
1906
1907 return MPM;
1908 }
1909 if (!UseCtxProfile.empty()) {
1910 // FIXME: Move LowerTypeTestsPass (and DropTypeTestsPass) into
1911 // buildModuleInlinerPipeline after ModuleInlinerPass, which performs ICP.
1912 if (ImportSummary)
1913 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1914 MPM.addPass(
1916 } else {
1917 // Add the core simplification pipeline.
1919 Level, ThinOrFullLTOPhase::ThinLTOPostLink, ImportSummary));
1920 }
1921 // Now add the optimization pipeline.
1924
1926
1927 // Emit annotation remarks.
1929
1930 addPipelineEndPasses(MPM, Opts);
1931
1932 return MPM;
1933}
1934
1937 // FIXME: We should use a customized pre-link pipeline!
1938 return buildPerModuleDefaultPipeline(Level,
1940}
1941
1944 ModuleSummaryIndex *ExportSummary) {
1946
1947 addPipelineStartPasses(MPM, Opts);
1948
1950
1951 // If we are invoking this without a summary index noting that we are linking
1952 // with a library containing the necessary APIs, remove any MemProf related
1953 // attributes and metadata.
1954 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
1956
1957 // Create a function that performs CFI checks for cross-DSO calls with targets
1958 // in the current module.
1959 MPM.addPass(CrossDSOCFIPass());
1960
1961 if (Level == OptimizationLevel::O0) {
1962 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1963 // metadata and intrinsics.
1964 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1965 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1966 // Run a second time to clean up any type tests left behind by WPD for use
1967 // in ICP.
1969
1971
1972 // AllocToken transforms heap allocation calls; this needs to run late after
1973 // other allocation call transformations (such as those in InstCombine).
1974 MPM.addPass(AllocTokenPass());
1975
1977
1978 // Emit annotation remarks.
1980
1981 return MPM;
1982 }
1983
1984 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1985 // Load sample profile before running the LTO optimization pipeline.
1986 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1987 PGOOpt->ProfileRemappingFile,
1989 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1990 // RequireAnalysisPass for PSI before subsequent non-module passes.
1992 }
1993
1994 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1996
1997 // Remove unused virtual tables to improve the quality of code generated by
1998 // whole-program devirtualization and bitset lowering.
1999 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2000
2001 // Do basic inference of function attributes from known properties of system
2002 // libraries and other oracles.
2004
2005 if (Level >= OptimizationLevel::O2) {
2007 CallSiteSplittingPass(), *PTO.EagerlyInvalidateAnalyses));
2008
2009 // Indirect call promotion. This should promote all the targets that are
2010 // left by the earlier promotion pass that promotes intra-module targets.
2011 // This two-step promotion is to save the compile time. For LTO, it should
2012 // produce the same result as if we only do promotion here.
2014 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2015
2016 // Promoting by-reference arguments to by-value exposes more constants to
2017 // IPSCCP.
2018 CGSCCPassManager CGPM;
2019 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
2021 else
2024 CGPM.addPass(
2027
2028 // Propagate constants at call sites into the functions they call. This
2029 // opens opportunities for globalopt (and inlining) by substituting function
2030 // pointers passed as arguments to direct uses of functions.
2031 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2032
2033 // Attach metadata to indirect call sites indicating the set of functions
2034 // they may target at run-time. This should follow IPSCCP.
2036 }
2037
2038 // Do RPO function attribute inference across the module to forward-propagate
2039 // attributes where applicable.
2040 // FIXME: Is this really an optimization rather than a canonicalization?
2041 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
2043 else
2045
2046 // Use in-range annotations on GEP indices to split globals where beneficial.
2047 MPM.addPass(GlobalSplitPass());
2048
2049 // Run whole program optimization of virtual call when the list of callees
2050 // is fixed.
2051 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2052
2054 // Stop here at -O1.
2055 if (Level == OptimizationLevel::O1) {
2057 LowerConstantIntrinsicsPass(), *PTO.EagerlyInvalidateAnalyses));
2058
2059 // The LowerTypeTestsPass needs to run to lower type metadata and the
2060 // type.test intrinsics. The pass does nothing if CFI is disabled.
2061 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2062 // Run a second time to clean up any type tests left behind by WPD for use
2063 // in ICP (which is performed earlier than this in the regular LTO
2064 // pipeline).
2066
2068
2069 // AllocToken transforms heap allocation calls; this needs to run late after
2070 // other allocation call transformations (such as those in InstCombine).
2071 MPM.addPass(AllocTokenPass());
2072
2074
2075 // Emit annotation remarks.
2077
2078 addPipelineEndPasses(MPM, Opts);
2079
2080 return MPM;
2081 }
2082
2083 // TODO: Skip to match buildCoroWrapper.
2084 MPM.addPass(CoroEarlyPass());
2085
2086 // Optimize globals to try and fold them into constants.
2087 MPM.addPass(GlobalOptPass());
2088
2089 // Promote any localized globals to SSA registers.
2091
2092 // Linking modules together can lead to duplicate global constant, only
2093 // keep one copy of each constant.
2095
2096 // Remove unused arguments from functions.
2098
2099 // Reduce the code after globalopt and ipsccp. Both can open up significant
2100 // simplification opportunities, and both can propagate functions through
2101 // function pointers. When this happens, we often have to resolve varargs
2102 // calls, etc, so let instcombine do this.
2103 FunctionPassManager PeepholeFPM;
2104 PeepholeFPM.addPass(InstCombinePass());
2105 if (Level >= OptimizationLevel::O2)
2106 PeepholeFPM.addPass(AggressiveInstCombinePass());
2107 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2108
2110 std::move(PeepholeFPM), *PTO.EagerlyInvalidateAnalyses));
2111
2112 // Lower variadic functions for supported targets prior to inlining.
2114
2115 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2116 // generally clean up exception handling overhead. It isn't clear this is
2117 // valuable as the inliner doesn't currently care whether it is inlining an
2118 // invoke or a call.
2119 // Run the inliner now.
2120 addModuleInlinerPass(MPM, Context, Level,
2122
2123 // Perform context disambiguation after inlining, since that would reduce the
2124 // amount of additional cloning required to distinguish the allocation
2125 // contexts.
2128 /*Summary=*/nullptr,
2129 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2130
2131 // Optimize globals again after we ran the inliner.
2132 MPM.addPass(GlobalOptPass());
2133
2134 // Run the OpenMPOpt pass again after global optimizations.
2136
2137 // Garbage collect dead functions.
2138 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2139
2140 // If we didn't decide to inline a function, check to see if we can
2141 // transform it to pass arguments by value instead of by reference.
2142 CGSCCPassManager CGPM;
2148
2150 // The IPO Passes may leave cruft around. Clean up after them.
2151 FPM.addPass(InstCombinePass());
2152 invokePeepholeEPCallbacks(FPM, Level);
2153
2154 if (Opts.enable_constraint_elimination)
2156
2158
2159 // Do a post inline PGO instrumentation and use pass. This is a context
2160 // sensitive PGO pass.
2161 if (PGOOpt) {
2162 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2163 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2164 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2165 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2166 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2167 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2168 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2169 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2170 }
2171
2172 // Break up allocas
2174
2175 // LTO provides additional opportunities for tailcall elimination due to
2176 // link-time inlining, and visibility of nocapture attribute.
2177 FPM.addPass(
2178 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2179
2180 // Run a few AA driver optimizations here and now to cleanup the code.
2182 std::move(FPM), *PTO.EagerlyInvalidateAnalyses));
2183
2184 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
2185 MPM.addPass(
2187 } else {
2188 MPM.addPass(
2190 }
2191
2192 // Require the GlobalsAA analysis for the module so we can query it within
2193 // MainFPM.
2194 if (Opts.enable_global_analyses) {
2196 // Invalidate AAManager so it can be recreated and pick up the newly
2197 // available GlobalsAA.
2198 MPM.addPass(
2200 }
2201
2202 FunctionPassManager MainFPM;
2204 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
2205 /*AllowSpeculation=*/true),
2206 /*USeMemorySSA=*/true));
2207
2208 if (Opts.enable_newgvn)
2209 MainFPM.addPass(NewGVNPass());
2210 else
2211 MainFPM.addPass(GVNPass());
2212
2213 // Remove dead memcpy()'s.
2214 MainFPM.addPass(MemCpyOptPass());
2215
2216 // Nuke dead stores.
2217 MainFPM.addPass(DSEPass());
2218 MainFPM.addPass(MoveAutoInitPass());
2220
2222
2223 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2224
2225 LoopPassManager LPM;
2226 if (Opts.enable_loop_flatten && Level >= OptimizationLevel::O2)
2227 LPM.addPass(LoopFlattenPass());
2228 LPM.addPass(IndVarSimplifyPass());
2229 LPM.addPass(LoopDeletionPass());
2230 // FIXME: Add loop interchange.
2231
2232 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2233 // *All* loop passes must preserve it, in order to be able to use it.
2234 // TODO: Explore enabling MemorySSA for loop passes after we remove the
2235 // LoopFullUnrollPass.
2236 MainFPM.addPass(
2237 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2238
2239 MainFPM.addPass(LoopDistributePass());
2240
2241 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2242
2243 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2244
2245 // Run the OpenMPOpt CGSCC pass again late.
2248
2249 invokePeepholeEPCallbacks(MainFPM, Level);
2250 MainFPM.addPass(JumpThreadingPass());
2252 std::move(MainFPM), *PTO.EagerlyInvalidateAnalyses));
2253
2254 // Lower type metadata and the type.test intrinsic. This pass supports
2255 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2256 // to be run at link time if CFI is enabled. This pass does nothing if
2257 // CFI is disabled.
2258 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2259 // Run a second time to clean up any type tests left behind by WPD for use
2260 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2262
2263 // Enable splitting late in the FullLTO post-link pipeline.
2264 if (Opts.hot_cold_split)
2266
2267 // Add late LTO optimization passes.
2268 FunctionPassManager LateFPM;
2269
2270 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2271 // canonicalization pass that enables other optimizations. As a result,
2272 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2273 // result too early.
2274 LateFPM.addPass(LoopSinkPass());
2275
2276 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2277 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2278 // flattening of blocks.
2279 LateFPM.addPass(DivRemPairsPass());
2280
2281 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
2282 // TODO: move this further up so that it can be optimized by GVN, etc.
2283 if (Opts.enable_mergeicmps)
2284 LateFPM.addPass(MergeICmpsPass());
2285 LateFPM.addPass(ExpandMemCmpPass());
2286
2287 // Delete basic blocks, which optimization passes may have killed.
2289 .convertSwitchRangeToICmp(true)
2290 .convertSwitchToArithmetic(true)
2291 .hoistCommonInsts(true)
2292 .speculateUnpredictables(true)));
2293 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2294
2295 // Drop bodies of available eternally objects to improve GlobalDCE.
2297
2298 // Now that we have optimized the program, discard unreachable functions.
2299 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2300
2301 if (*PTO.MergeFunctions)
2303
2305
2306 if (PTO.CallGraphProfile)
2307 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2308
2309 MPM.addPass(CoroCleanupPass());
2310
2311 // AllocToken transforms heap allocation calls; this needs to run late after
2312 // other allocation call transformations (such as those in InstCombine).
2313 MPM.addPass(AllocTokenPass());
2314
2316
2317 // Emit annotation remarks.
2319
2320 addPipelineEndPasses(MPM, Opts);
2321
2322 return MPM;
2323}
2324
2328 assert(Level == OptimizationLevel::O0 &&
2329 "buildO0DefaultPipeline should only be used with O0");
2330
2332
2333 addPipelineStartPasses(MPM, Opts);
2334
2335 // Perform pseudo probe instrumentation in O0 mode. This is for the
2336 // consistency between different build modes. For example, a LTO build can be
2337 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2338 // the postlink will require pseudo probe instrumentation in the prelink.
2339 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2341
2342 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2343 PGOOpt->Action == PGOOptions::IRUse))
2345 MPM,
2346 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2347 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2348 PGOOpt->ProfileRemappingFile);
2349
2350 // Instrument function entry and exit before all inlining.
2352 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2353
2355
2356 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2358
2359 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2360 // Explicitly disable sample loader inlining and use flattened profile in O0
2361 // pipeline.
2362 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2363 PGOOpt->ProfileRemappingFile,
2365 /*DisableSampleProfileInlining=*/true,
2366 /*UseFlattenedProfile=*/true));
2367 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2368 // RequireAnalysisPass for PSI before subsequent non-module passes.
2370 }
2371
2373
2374 // Build a minimal pipeline based on the semantics required by LLVM,
2375 // which is just that always inlining occurs. Further, disable generating
2376 // lifetime intrinsics to avoid enabling further optimizations during
2377 // code generation.
2379 /*InsertLifetimeIntrinsics=*/false));
2380
2381 if (*PTO.MergeFunctions)
2383
2384 if (Opts.enable_matrix)
2385 MPM.addPass(
2387
2388 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2389 CGSCCPassManager CGPM;
2391 if (!CGPM.isEmpty())
2393 }
2394 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2395 LoopPassManager LPM;
2397 if (!LPM.isEmpty()) {
2399 createFunctionToLoopPassAdaptor(std::move(LPM))));
2400 }
2401 }
2402 if (!LoopOptimizerEndEPCallbacks.empty()) {
2403 LoopPassManager LPM;
2405 if (!LPM.isEmpty()) {
2407 createFunctionToLoopPassAdaptor(std::move(LPM))));
2408 }
2409 }
2410 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2413 if (!FPM.isEmpty())
2414 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2415 }
2416
2418
2419 if (!VectorizerStartEPCallbacks.empty()) {
2422 if (!FPM.isEmpty())
2423 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2424 }
2425
2426 if (!VectorizerEndEPCallbacks.empty()) {
2429 if (!FPM.isEmpty())
2430 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2431 }
2432
2434
2435 // AllocToken transforms heap allocation calls; this needs to run late after
2436 // other allocation call transformations (such as those in InstCombine).
2437 if (!isLTOPreLink(Phase))
2438 MPM.addPass(AllocTokenPass());
2439
2441
2442 if (Opts.enable_instrumentor)
2443 MPM.addPass(InstrumentorPass(FS));
2444
2445 // Attach !implicit.ref metadata from all functions to copyright strings.
2447
2448 if (isLTOPreLink(Phase))
2449 addRequiredLTOPreLinkPasses(MPM);
2450
2451 // Emit annotation remarks.
2453
2454 addPipelineEndPasses(MPM, Opts);
2455
2456 return MPM;
2457}
2458
2460 AAManager AA;
2461
2462 // The order in which these are registered determines their priority when
2463 // being queried.
2464
2465 // Add any target-specific alias analyses that should be run early.
2466 if (TM)
2467 TM->registerEarlyDefaultAliasAnalyses(AA);
2468
2469 // First we register the basic alias analysis that provides the majority of
2470 // per-function local AA logic. This is a stateless, on-demand local set of
2471 // AA techniques.
2472 AA.registerFunctionAnalysis<BasicAA>();
2473
2474 // Next we query fast, specialized alias analyses that wrap IR-embedded
2475 // information about aliasing.
2476 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2477 AA.registerFunctionAnalysis<TypeBasedAA>();
2478
2479 // Add support for querying global aliasing information when available.
2480 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2481 // analysis, all that the `AAManager` can do is query for any *cached*
2482 // results from `GlobalsAA` through a readonly proxy.
2483 if (Opts.enable_global_analyses)
2484 AA.registerModuleAnalysis<GlobalsAA>();
2485
2486 // Add target-specific alias analyses.
2487 if (TM)
2488 TM->registerDefaultAliasAnalyses(AA);
2489
2490 return AA;
2491}
2492
2493bool PassBuilder::isInstrumentedPGOUse() const {
2494 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2495 !UseCtxProfile.empty();
2496}
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.
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 the GVNHoist pass.
This file provides the interface for the GVNSink pass.
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 void addPipelineEndPasses(ModulePassManager &MPM, const PassesOptions &Opts)
static void addPipelineStartPasses(ModulePassManager &MPM, const PassesOptions &Opts)
static bool isThinLTOPostLink(ThinOrFullLTOPhase Phase)
static void addModuleInlinerPass(ModulePassManager &MPM, const LLVMContext &Context, OptimizationLevel Level, 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.
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.
Pass to remove unused function declarations.
Definition GlobalDCE.h:39
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:71
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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:80
CGSCCPassManager & getPM()
Allow adding more CGSCC passes, besides inlining.
Definition Inliner.h:77
void addLateModulePass(T Pass)
Add a module pass that runs after the CGSCC passes.
Definition Inliner.h:85
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(const cl::LibraryOptionsContext &LibraryOptions)
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 buildModuleSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase, const ModuleSummaryIndex *ImportSummary=nullptr)
Construct the core LLVM module canonicalization and simplification pipeline.
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 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.
Tunable parameters for passes in the default pipelines.
Definition PassBuilder.h:48
std::optional< bool > EagerlyInvalidateAnalyses
std::optional< bool > ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition PassBuilder.h:75
std::optional< unsigned > MaxDevirtIterations
Tuning option to cap how many times the inliner pipeline reruns on an SCC after devirtualizing a call...
Definition PassBuilder.h:99
std::optional< unsigned > LicmMssaNoAccForPromotionCap
Tuning option to disable promotion to scalars in LICM with MemorySSA, if the number of access is too ...
Definition PassBuilder.h:83
std::optional< bool > DevirtualizeSpeculatively
std::optional< unsigned > LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition PassBuilder.h:79
LLVM_ABI PipelineTuningOptions resolve(const cl::LibraryOptionsContext &LibraryOptions) const
Return a copy whose unset members are set from LibraryOptions.
std::optional< bool > LoopInterchange
Tuning option to enable/disable loop interchange.
Definition PassBuilder.h:69
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition PassBuilder.h:55
std::optional< bool > MergeFunctions
Tuning option to enable/disable function merging.
Definition PassBuilder.h:92
bool LoopUnrolling
Tuning option to enable/disable loop unrolling.
Definition PassBuilder.h:66
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:59
Inject MD_prof metadata where it's missing.
Checks that MD_prof is present on every instruction that supports it.
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:134
Interfaces for registering analysis passes, producing common pass manager configurations,...
Abstract Attribute helper functions.
Definition Attributor.h:165
@ 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
LLVM_ABI InlineParams getInlineParams(const LLVMContext &C)
Generate the parameters to tune the inline cost analysis based only on the commandline options.
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
cl::opt< bool > EnableProfcheckInPipeline("enable-profcheck-in-pipeline", cl::init(false), cl::desc("Adds profile verification to the pipeline, erroring if profile " "information is dropped."))
LLVM_ABI unsigned getLicmMssaOptCap(const cl::LibraryOptionsContext &LibraryOptions)
Return -licm-mssa-optimization-cap.
Definition LICM.cpp:120
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
@ 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...
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
@ CGSCC_LIGHT
@ MODULE_LIGHT
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:75
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:83
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
Definition Pass.h:81
@ None
No LTO/ThinLTO behavior needed.
Definition Pass.h:77
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:85
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:79
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
LLVM_ABI InlineParams getInlineParamsFromOptLevel(const LLVMContext &C, unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
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 bool getForgetSCEVInLoopUnroll(const cl::LibraryOptionsContext &LibraryOptions)
Return -forget-scev-loop-unroll.
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI unsigned getLicmMssaNoAccForPromotionCap(const cl::LibraryOptionsContext &LibraryOptions)
Return -licm-mssa-max-acc-promotion.
Definition LICM.cpp:124
LLVM_ABI unsigned getMaxDevirtIterations(const cl::LibraryOptionsContext &)
const PassesOptions & getPassesOptions(const LLVMContext &C)
LLVM_ABI bool isPGOInstrumentColdFunctionOnly(const cl::LibraryOptionsContext &LibraryOptions)
Return the value of -pgo-instrument-cold-function-only in LibraryOptions.
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 GVNHoist.h:23
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition GVNSink.h:23
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:210
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:219
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:231
std::optional< bool > IgnoreProfile
Indicate whether to ignore profile information.
Definition InlineCost.h:252
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:212
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition InlineCost.h:244
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:215
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.