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"
29#include "llvm/IR/PassManager.h"
30#include "llvm/IR/Verifier.h"
31#include "llvm/Pass.h"
160
161using namespace llvm;
162
163namespace llvm {
165
167} // namespace llvm
168
170 const PassesOptions &Opts = PassesOptions::Global;
171 LoopInterleaving = true;
172 LoopVectorization = true;
173 SLPVectorization = false;
174 LoopUnrolling = true;
175 LoopInterchange = Opts.enable_loopinterchange;
176 LoopFusion = false;
180 CallGraphProfile = true;
181 UnifiedLTO = false;
182 MergeFunctions = Opts.enable_merge_functions;
183 InlinerThreshold = -1;
184 EagerlyInvalidateAnalyses = Opts.eagerly_invalidate_analyses;
185 DevirtualizeSpeculatively = Opts.enable_devirtualize_speculatively;
186}
187
188namespace llvm {
190} // namespace llvm
191
193 OptimizationLevel Level) {
194 for (auto &C : PeepholeEPCallbacks)
195 C(FPM, Level);
196}
199 for (auto &C : LateLoopOptimizationsEPCallbacks)
200 C(LPM, Level);
201}
203 OptimizationLevel Level) {
204 for (auto &C : LoopOptimizerEndEPCallbacks)
205 C(LPM, Level);
206}
209 for (auto &C : ScalarOptimizerLateEPCallbacks)
210 C(FPM, Level);
211}
213 OptimizationLevel Level) {
214 for (auto &C : CGSCCOptimizerLateEPCallbacks)
215 C(CGPM, Level);
216}
218 OptimizationLevel Level) {
219 for (auto &C : VectorizerStartEPCallbacks)
220 C(FPM, Level);
221}
223 OptimizationLevel Level) {
224 for (auto &C : VectorizerEndEPCallbacks)
225 C(FPM, Level);
226}
228 OptimizationLevel Level,
230 for (auto &C : OptimizerEarlyEPCallbacks)
231 C(MPM, Level, Phase);
232}
234 OptimizationLevel Level,
236 for (auto &C : OptimizerLastEPCallbacks)
237 C(MPM, Level, Phase);
238}
241 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
242 C(MPM, Level);
243}
246 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
247 C(MPM, Level);
248}
251 for (auto &C : ThinLinkTimeOptimizationEarlyEPCallbacks)
252 C(MPM, Level);
253}
256 for (auto &C : ThinLinkTimeOptimizationLastEPCallbacks)
257 C(MPM, Level);
258}
260 OptimizationLevel Level) {
261 for (auto &C : PipelineStartEPCallbacks)
262 C(MPM, Level);
263}
266 for (auto &C : PipelineEarlySimplificationEPCallbacks)
267 C(MPM, Level, Phase);
268}
269
270// Get IR stats with InstCount before/after the optimization pipeline
272 bool IsPreOptimization) {
273 if (AreStatisticsEnabled()) {
274 MPM.addPass(
277 FunctionPropertiesStatisticsPass(IsPreOptimization)));
278 }
279}
280
281// Helper to add AnnotationRemarksPass.
285
286// Helper to check if the current compilation phase is preparing for LTO
291
292// Helper to check if the current compilation phase is preparing for FullLTO
293[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
295}
296
297// Helper to check if the current compilation phase is preparing for ThinLTO
301
302// Helper to check if the current compilation phase is LTO backend
307
308// Helper to check if the current compilation phase is FullLTO backend
312
313// Helper to check if the current compilation phase is ThinLTO backend
317
318// Helper to wrap conditionally Coro passes.
320 // TODO: Skip passes according to Phase.
321 ModulePassManager CoroPM;
322 CoroPM.addPass(CoroEarlyPass());
323 CGSCCPassManager CGPM;
324 CGPM.addPass(CoroSplitPass());
325 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
326 CoroPM.addPass(CoroCleanupPass());
327 CoroPM.addPass(GlobalDCEPass());
328 return CoroConditionalWrapper(std::move(CoroPM));
329}
330
332 return getInlineParamsFromOptLevel(static_cast<unsigned>(Level));
333}
334
336 const PassesOptions &Opts,
337 OptimizationLevel Level,
340 if (Opts.enable_module_inliner)
341 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
342 else
344 IP,
345 /* MandatoryFirst */ true,
347}
348
349// TODO: Investigate the cost/benefit of tail call elimination on debugging.
351PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
353
355
357 FPM.addPass(CountVisitsPass());
358
359 // Form SSA out of local memory accesses after breaking apart aggregates into
360 // scalars.
361 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
362
363 // Catch trivial redundancies
364 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
365
366 // Hoisting of scalars and load expressions.
367 FPM.addPass(
368 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
369 FPM.addPass(InstCombinePass());
370
371 FPM.addPass(LibCallsShrinkWrapPass());
372
373 invokePeepholeEPCallbacks(FPM, Level);
374
375 FPM.addPass(
376 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
377
378 // Form canonically associated expression trees, and simplify the trees using
379 // basic mathematical properties. For example, this will form (nearly)
380 // minimal multiplication trees.
381 FPM.addPass(ReassociatePass());
382
383 // Add the primary loop simplification pipeline.
384 // FIXME: Currently this is split into two loop pass pipelines because we run
385 // some function passes in between them. These can and should be removed
386 // and/or replaced by scheduling the loop pass equivalents in the correct
387 // positions. But those equivalent passes aren't powerful enough yet.
388 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
389 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
390 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
391 // `LoopInstSimplify`.
392 LoopPassManager LPM1, LPM2;
393
394 // Simplify the loop body. We do this initially to clean up after other loop
395 // passes run, either when iterating on a loop or on inner loops with
396 // implications on the outer loop.
397 LPM1.addPass(LoopInstSimplifyPass());
398 LPM1.addPass(LoopSimplifyCFGPass());
399
400 // Try to remove as much code from the loop header as possible,
401 // to reduce amount of IR that will have to be duplicated. However,
402 // do not perform speculative hoisting the first time as LICM
403 // will destroy metadata that may not need to be destroyed if run
404 // after loop rotation.
405 // TODO: Investigate promotion cap for O1.
406 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
407 /*AllowSpeculation=*/false));
408
409 LPM1.addPass(
410 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
411 // TODO: Investigate promotion cap for O1.
412 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
413 /*AllowSpeculation=*/true));
414 LPM1.addPass(SimpleLoopUnswitchPass());
415 if (Opts.enable_loop_flatten)
416 LPM1.addPass(LoopFlattenPass());
417
418 LPM2.addPass(LoopIdiomRecognizePass());
419 LPM2.addPass(IndVarSimplifyPass());
420
422
423 LPM2.addPass(LoopDeletionPass());
424
425 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
426 // because it changes IR to makes profile annotation in back compile
427 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
428 // attributes so we need to make sure and allow the full unroll pass to pay
429 // attention to it.
430 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
431 PGOOpt->Action != PGOOptions::SampleUse)
432 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
433 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
434 PTO.ForgetAllSCEVInLoopUnroll));
435
437
438 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
439 /*UseMemorySSA=*/true));
440 FPM.addPass(
441 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
442 FPM.addPass(InstCombinePass());
443 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
444 // *All* loop passes must preserve it, in order to be able to use it.
445 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
446 /*UseMemorySSA=*/false));
447
448 // Delete small array after loop unroll.
449 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
450
451 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
452 FPM.addPass(MemCpyOptPass());
453
454 // Sparse conditional constant propagation.
455 // FIXME: It isn't clear why we do this *after* loop passes rather than
456 // before...
457 FPM.addPass(SCCPPass());
458
459 // Delete dead bit computations (instcombine runs after to fold away the dead
460 // computations, and then ADCE will run later to exploit any new DCE
461 // opportunities that creates).
462 FPM.addPass(BDCEPass());
463
464 // Run instcombine after redundancy and dead bit elimination to exploit
465 // opportunities opened up by them.
466 FPM.addPass(InstCombinePass());
467 invokePeepholeEPCallbacks(FPM, Level);
468
469 FPM.addPass(CoroElidePass());
470
472
473 // Finally, do an expensive DCE pass to catch all the dead code exposed by
474 // the simplifications and basic cleanup after all the simplifications.
475 // TODO: Investigate if this is too expensive.
476 FPM.addPass(ADCEPass());
477 FPM.addPass(
478 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
479 FPM.addPass(InstCombinePass());
480 invokePeepholeEPCallbacks(FPM, Level);
481
482 return FPM;
483}
484
488 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
489
490 // The O1 pipeline has a separate pipeline creation function to simplify
491 // construction readability.
492 if (Level == OptimizationLevel::O1)
493 return buildO1FunctionSimplificationPipeline(Level, Phase);
494
496
499
500 // Form SSA out of local memory accesses after breaking apart aggregates into
501 // scalars.
503
504 // Catch trivial redundancies
505 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
508
509 // Hoisting of scalars and load expressions.
510 if (Opts.enable_gvn_hoist)
511 FPM.addPass(GVNHoistPass());
512
513 // Global value numbering based sinking.
514 if (Opts.enable_gvn_sink) {
515 FPM.addPass(GVNSinkPass());
516 FPM.addPass(
517 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
518 }
519
520 // Speculative execution if the target has divergent branches; otherwise nop.
521 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
522
523 // Optimize based on known information about branches, and cleanup afterward.
526
527 // Jump table to switch conversion.
528 if (Opts.enable_jump_table_to_switch)
530
531 FPM.addPass(
532 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
536
537 invokePeepholeEPCallbacks(FPM, Level);
538
539 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
540 // using the size value profile. Don't perform this when optimizing for size.
541 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
543
544 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
545 isInstrumentedPGOUse()));
546 FPM.addPass(
547 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
548
549 // Form canonically associated expression trees, and simplify the trees using
550 // basic mathematical properties. For example, this will form (nearly)
551 // minimal multiplication trees.
553
554 if (Opts.enable_constraint_elimination)
556
557 // Add the primary loop simplification pipeline.
558 // FIXME: Currently this is split into two loop pass pipelines because we run
559 // some function passes in between them. These can and should be removed
560 // and/or replaced by scheduling the loop pass equivalents in the correct
561 // positions. But those equivalent passes aren't powerful enough yet.
562 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
563 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
564 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
565 // `LoopInstSimplify`.
566 LoopPassManager LPM1, LPM2;
567
568 // Simplify the loop body. We do this initially to clean up after other loop
569 // passes run, either when iterating on a loop or on inner loops with
570 // implications on the outer loop.
571 LPM1.addPass(LoopInstSimplifyPass());
572 LPM1.addPass(LoopSimplifyCFGPass());
573
574 // Try to remove as much code from the loop header as possible,
575 // to reduce amount of IR that will have to be duplicated. However,
576 // do not perform speculative hoisting the first time as LICM
577 // will destroy metadata that may not need to be destroyed if run
578 // after loop rotation.
579 // TODO: Investigate promotion cap for O1.
580 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
581 /*AllowSpeculation=*/false));
582
583 LPM1.addPass(
584 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
585 // TODO: Investigate promotion cap for O1.
586 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
587 /*AllowSpeculation=*/true));
588 LPM1.addPass(
589 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
590 if (Opts.enable_loop_flatten)
591 LPM1.addPass(LoopFlattenPass());
592
593 LPM2.addPass(LoopIdiomRecognizePass());
594 LPM2.addPass(IndVarSimplifyPass());
595
596 {
598 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
600 LPM2.addPass(std::move(ExtraPasses));
601 }
602
604
605 LPM2.addPass(LoopDeletionPass());
606
607 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
608 // because it changes IR to makes profile annotation in back compile
609 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
610 // attributes so we need to make sure and allow the full unroll pass to pay
611 // attention to it.
612 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
613 PGOOpt->Action != PGOOptions::SampleUse)
614 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
615 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
616 PTO.ForgetAllSCEVInLoopUnroll));
617
619
620 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
621 /*UseMemorySSA=*/true));
622 FPM.addPass(
623 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
625 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
626 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
627 // *All* loop passes must preserve it, in order to be able to use it.
628 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
629 /*UseMemorySSA=*/false));
630
631 // Delete small array after loop unroll.
633
634 // Try vectorization/scalarization transforms that are both improvements
635 // themselves and can allow further folds with GVN and InstCombine.
636 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
637
638 // Eliminate redundancies.
640 if (Opts.enable_newgvn)
641 FPM.addPass(NewGVNPass());
642 else
643 FPM.addPass(GVNPass());
644
645 // Sparse conditional constant propagation.
646 // FIXME: It isn't clear why we do this *after* loop passes rather than
647 // before...
648 FPM.addPass(SCCPPass());
649
650 // Delete dead bit computations (instcombine runs after to fold away the dead
651 // computations, and then ADCE will run later to exploit any new DCE
652 // opportunities that creates).
653 FPM.addPass(BDCEPass());
654
655 // Run instcombine after redundancy and dead bit elimination to exploit
656 // opportunities opened up by them.
658 invokePeepholeEPCallbacks(FPM, Level);
659
660 // Re-consider control flow based optimizations after redundancy elimination,
661 // redo DCE, etc.
662 if (Opts.enable_dfa_jump_thread)
664
667
668 // Finally, do an expensive DCE pass to catch all the dead code exposed by
669 // the simplifications and basic cleanup after all the simplifications.
670 // TODO: Investigate if this is too expensive.
671 FPM.addPass(ADCEPass());
672
673 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
674 FPM.addPass(MemCpyOptPass());
675
676 FPM.addPass(DSEPass());
678
680 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
681 /*AllowSpeculation=*/true),
682 /*UseMemorySSA=*/true));
683
684 FPM.addPass(CoroElidePass());
685
687
689 .convertSwitchRangeToICmp(true)
690 .convertSwitchToArithmetic(true)
691 .hoistCommonInsts(true)
692 .sinkCommonInsts(true)));
694 invokePeepholeEPCallbacks(FPM, Level);
695
696 return FPM;
697}
698
699void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
702 MPM.addPass(AssignGUIDPass());
703}
704
705void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
706 OptimizationLevel Level,
707 ThinOrFullLTOPhase LTOPhase) {
708 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
709 if (Opts.disable_preinline)
710 return;
711 InlineParams IP;
712
713 IP.DefaultThreshold = Opts.preinline_threshold;
714
715 // FIXME: The hint threshold has the same value used by the regular inliner
716 // when not optimzing for size. This should probably be lowered after
717 // performance testing.
718 // FIXME: this comment is cargo culted from the old pass manager, revisit).
719 IP.HintThreshold = 325;
720 IP.OptSizeHintThreshold = Opts.preinline_threshold;
722 IP, /* MandatoryFirst */ true,
724 CGSCCPassManager &CGPipeline = MIWP.getPM();
725
727 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
728 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
729 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
730 true))); // Merge & remove basic blocks.
731 FPM.addPass(InstCombinePass()); // Combine silly sequences.
732 invokePeepholeEPCallbacks(FPM, Level);
733
734 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
735 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
736
737 MPM.addPass(std::move(MIWP));
738
739 // Delete anything that is now dead to make sure that we don't instrument
740 // dead code. Instrumentation can end up keeping dead code around and
741 // dramatically increase code size.
742 MPM.addPass(GlobalDCEPass());
743}
744
745void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
746 OptimizationLevel Level) {
747 if (Opts.enable_post_pgo_loop_rotation) {
748 // Disable header duplication in loop rotation at -Oz.
750 createFunctionToLoopPassAdaptor(LoopRotatePass(),
751 /*UseMemorySSA=*/false),
752 PTO.EagerlyInvalidateAnalyses));
753 }
754}
755
756void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
757 OptimizationLevel Level, bool RunProfileGen,
758 bool IsCS, bool AtomicCounterUpdate,
759 std::string ProfileFile,
760 std::string ProfileRemappingFile) {
761 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
762
763 if (!RunProfileGen) {
764 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
765 MPM.addPass(
766 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
767 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
768 // RequireAnalysisPass for PSI before subsequent non-module passes.
769 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
770 return;
771 }
772
773 // Perform PGO instrumentation.
774 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
776
777 addPostPGOLoopRotation(MPM, Level);
778 // Add the profile lowering pass.
779 InstrProfOptions Options;
780 if (!ProfileFile.empty())
781 Options.InstrProfileOutput = ProfileFile;
782 // Do counter promotion at Level greater than O0.
783 Options.DoCounterPromotion = true;
784 Options.UseBFIInPromotion = IsCS;
785 if (Opts.enable_sampled_instrumentation) {
786 Options.Sampling = true;
787 // With sampling, there is little beneifit to enable counter promotion.
788 // But note that sampling does work with counter promotion.
789 Options.DoCounterPromotion = false;
790 }
791 Options.Atomic = AtomicCounterUpdate;
792 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
793}
794
796 bool RunProfileGen, bool IsCS,
797 bool AtomicCounterUpdate,
798 std::string ProfileFile,
799 std::string ProfileRemappingFile) {
800 if (!RunProfileGen) {
801 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
802 MPM.addPass(
803 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
804 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
805 // RequireAnalysisPass for PSI before subsequent non-module passes.
807 return;
808 }
809
810 // Perform PGO instrumentation.
813 // Add the profile lowering pass.
815 if (!ProfileFile.empty())
816 Options.InstrProfileOutput = ProfileFile;
817 // Do not do counter promotion at O0.
818 Options.DoCounterPromotion = false;
819 Options.UseBFIInPromotion = IsCS;
820 Options.Atomic = AtomicCounterUpdate;
822}
823
827 InlineParams IP;
828 if (PTO.InlinerThreshold == -1)
830 else
831 IP = getInlineParams(PTO.InlinerThreshold);
832 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
833 // set hot-caller threshold to 0 to disable hot
834 // callsite inline (as much as possible [1]) because it makes
835 // profile annotation in the backend inaccurate.
836 //
837 // [1] Note the cost of a function could be below zero due to erased
838 // prologue / epilogue.
839 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
841
842 if (PGOOpt)
843 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
844
845 ModuleInlinerWrapperPass MIWP(IP, Opts.mandatory_inlining_first,
846 InlineContext{Phase, InlinePass::CGSCCInliner},
847 Opts.enable_ml_inliner, MaxDevirtIterations);
848
849 // Require the GlobalsAA analysis for the module so we can query it within
850 // the CGSCC pipeline.
851 if (Opts.enable_global_analyses) {
853 // Invalidate AAManager so it can be recreated and pick up the newly
854 // available GlobalsAA.
855 MIWP.addModulePass(
857 }
858
859 // Require the ProfileSummaryAnalysis for the module so we can query it within
860 // the inliner pass.
862
863 // Now begin the main postorder CGSCC pipeline.
864 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
865 // manager and trying to emulate its precise behavior. Much of this doesn't
866 // make a lot of sense and we should revisit the core CGSCC structure.
867 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
868
869 // Note: historically, the PruneEH pass was run first to deduce nounwind and
870 // generally clean up exception handling overhead. It isn't clear this is
871 // valuable as the inliner doesn't currently care whether it is inlining an
872 // invoke or a call.
873
874 if (Opts.attributor_enable & AttributorRunOption::CGSCC)
875 MainCGPipeline.addPass(AttributorCGSCCPass());
876
877 // Deduce function attributes. We do another run of this after the function
878 // simplification pipeline, so this only needs to run when it could affect the
879 // function simplification pipeline, which is only the case with recursive
880 // functions.
881 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
882 MainCGPipeline.addPass(AttributorLightCGSCCPass());
883 } else {
884 MainCGPipeline.addPass(
885 PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
886 }
887
888 // When at O3 add argument promotion to the pass pipeline.
889 // FIXME: It isn't at all clear why this should be limited to O3.
890 if (Level == OptimizationLevel::O3)
891 MainCGPipeline.addPass(ArgumentPromotionPass());
892
893 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
894 // there are no OpenMP runtime calls present in the module.
895 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
896 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
897
898 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
899
900 // Add the core function simplification pipeline nested inside the
901 // CGSCC walk.
904 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
905
906 // Finally, deduce any function attributes based on the fully simplified
907 // function.
908 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
909 MainCGPipeline.addPass(AttributorLightCGSCCPass());
910 else
911 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
912
913 // Mark that the function is fully simplified and that it shouldn't be
914 // simplified again if we somehow revisit it due to CGSCC mutations unless
915 // it's been modified since.
918
919 if (!isThinLTOPreLink(Phase)) {
920 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
921 MainCGPipeline.addPass(CoroAnnotationElidePass());
922 }
923
924 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
927
928 return MIWP;
929}
930
935
937 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
938 // set hot-caller threshold to 0 to disable hot
939 // callsite inline (as much as possible [1]) because it makes
940 // profile annotation in the backend inaccurate.
941 //
942 // [1] Note the cost of a function could be below zero due to erased
943 // prologue / epilogue.
944 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
946
947 if (PGOOpt)
948 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
949
950 // The inline deferral logic is used to avoid losing some
951 // inlining chance in future. It is helpful in SCC inliner, in which
952 // inlining is processed in bottom-up order.
953 // While in module inliner, the inlining order is a priority-based order
954 // by default. The inline deferral is unnecessary there. So we disable the
955 // inline deferral logic in module inliner.
956 IP.EnableDeferral = false;
957
958 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
960 MPM.addPass(GlobalOptPass());
961 MPM.addPass(GlobalDCEPass());
962 MPM.addPass(AssignGUIDPass());
963 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
964 }
965
968 PTO.EagerlyInvalidateAnalyses));
969
970 if (!isThinLTOPreLink(Phase)) {
973 MPM.addPass(
975 }
976
977 return MPM;
978}
979
983 assert(Level != OptimizationLevel::O0 &&
984 "Should not be used for O0 pipeline");
985
987 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
988
990
991 // Place pseudo probe instrumentation as the first pass of the pipeline to
992 // minimize the impact of optimization changes.
993 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
995
996 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
997
998 // In ThinLTO mode, when flattened profile is used, all the available
999 // profile information will be annotated in PreLink phase so there is
1000 // no need to load the profile again in PostLink.
1001 bool LoadSampleProfile = HasSampleProfile && !(Opts.flattened_profile_used &&
1003
1004 // During the ThinLTO backend phase we perform early indirect call promotion
1005 // here, before globalopt. Otherwise imported available_externally functions
1006 // look unreferenced and are removed. If we are going to load the sample
1007 // profile then defer until later.
1008 // TODO: See if we can move later and consolidate with the location where
1009 // we perform ICP when we are loading a sample profile.
1010 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1011 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1012 // determine whether the new direct calls are annotated with prof metadata.
1013 // Ideally this should be determined from whether the IR is annotated with
1014 // sample profile, and not whether the a sample profile was provided on the
1015 // command line. E.g. for flattened profiles where we will not be reloading
1016 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1017 // provide the sample profile file.
1018 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1019 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1020
1021 // Create an early function pass manager to cleanup the output of the
1022 // frontend. Not necessary with LTO post link pipelines since the pre link
1023 // pipeline already cleaned up the frontend output.
1024 if (!isThinLTOPostLink(Phase)) {
1025 // Do basic inference of function attributes from known properties of system
1026 // libraries and other oracles.
1028 MPM.addPass(CoroEarlyPass());
1029
1030 FunctionPassManager EarlyFPM;
1031 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1032 // Lower llvm.expect to metadata before attempting transforms.
1033 // Compare/branch metadata may alter the behavior of passes like
1034 // SimplifyCFG.
1036 EarlyFPM.addPass(SimplifyCFGPass());
1038 EarlyFPM.addPass(EarlyCSEPass());
1039 if (Level == OptimizationLevel::O3)
1040 EarlyFPM.addPass(CallSiteSplittingPass());
1042 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1043 }
1044
1045 if (LoadSampleProfile) {
1046 // Annotate sample profile right after early FPM to ensure freshness of
1047 // the debug info.
1049 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1050 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1051 // RequireAnalysisPass for PSI before subsequent non-module passes.
1053 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1054 // for the profile annotation to be accurate in the LTO backend.
1055 if (!isLTOPreLink(Phase))
1056 // We perform early indirect call promotion here, before globalopt.
1057 // This is important for the ThinLTO backend phase because otherwise
1058 // imported available_externally functions look unreferenced and are
1059 // removed.
1060 MPM.addPass(
1061 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1062 }
1063
1064 // Try to perform OpenMP specific optimizations on the module. This is a
1065 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1067
1068 if (Opts.attributor_enable & AttributorRunOption::MODULE)
1069 MPM.addPass(AttributorPass());
1070 else if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1072
1073 // Lower type metadata and the type.test intrinsic in the ThinLTO
1074 // post link pipeline after ICP. This is to enable usage of the type
1075 // tests in ICP sequences.
1078
1080
1081 // Interprocedural constant propagation now that basic cleanup has occurred
1082 // and prior to optimizing globals.
1083 // FIXME: This position in the pipeline hasn't been carefully considered in
1084 // years, it should be re-analyzed.
1085 MPM.addPass(
1086 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1087
1088 // Attach metadata to indirect call sites indicating the set of functions
1089 // they may target at run-time. This should follow IPSCCP.
1091
1092 // Optimize globals to try and fold them into constants.
1093 MPM.addPass(GlobalOptPass());
1094
1095 // Create a small function pass pipeline to cleanup after all the global
1096 // optimizations.
1097 FunctionPassManager GlobalCleanupPM;
1098 // FIXME: Should this instead by a run of SROA?
1099 GlobalCleanupPM.addPass(PromotePass());
1100 GlobalCleanupPM.addPass(InstCombinePass());
1101 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1102 GlobalCleanupPM.addPass(
1103 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1104 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1105 PTO.EagerlyInvalidateAnalyses));
1106
1107 // We already asserted this happens in non-FullLTOPostLink earlier.
1108 const bool IsPreLink = !isThinLTOPostLink(Phase);
1109 // Enable contextual profiling instrumentation.
1110 const bool IsCtxProfGen =
1112 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1113 const bool IsPGOInstrGen =
1114 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1115 const bool IsPGOInstrUse =
1116 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1117 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1118 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1119 // enable ctx profiling from the frontend.
1121 "Enabling both instrumented PGO and contextual instrumentation is not "
1122 "supported.");
1123 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1124
1125 assert((Opts.instrument_cold_function_only_path.empty() ||
1127 "--instrument-cold-function-only-path is provided but "
1128 "--pgo-instrument-cold-function-only is not enabled");
1129 const bool IsColdFuncOnlyInstrGen =
1130 isPGOInstrumentColdFunctionOnly() && IsPGOPreLink &&
1131 !Opts.instrument_cold_function_only_path.empty();
1132
1133 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1134 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1135 addPreInlinerPasses(MPM, Level, Phase);
1136
1137 // Add all the requested passes for instrumentation PGO, if requested.
1138 if (IsPGOInstrGen || IsPGOInstrUse) {
1139 addPGOInstrPasses(MPM, Level,
1140 /*RunProfileGen=*/IsPGOInstrGen,
1141 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1142 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1143 } else if (IsCtxProfGen || IsCtxProfUse) {
1145 // In pre-link, we just want the instrumented IR. We use the contextual
1146 // profile in the post-thinlink phase.
1147 // The instrumentation will be removed in post-thinlink after IPO.
1148 if (IsCtxProfUse) {
1149 MPM.addPass(AssignGUIDPass());
1150 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1151 return MPM;
1152 }
1153 // Block further inlining in the instrumented ctxprof case. This avoids
1154 // confusingly collecting profiles for the same GUID corresponding to
1155 // different variants of the function. We could do like PGO and identify
1156 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1157 // thinlto to happen before performing any further optimizations, it's
1158 // unnecessary to collect profiles for non-prevailing copies.
1160 addPostPGOLoopRotation(MPM, Level);
1161 MPM.addPass(AssignGUIDPass());
1163 } else if (IsColdFuncOnlyInstrGen) {
1164 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1165 /* AtomicCounterUpdate */ false,
1166 Opts.instrument_cold_function_only_path.str(),
1167 /* ProfileRemappingFile */ "");
1168 }
1169
1170 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1171 MPM.addPass(PGOIndirectCallPromotion(false, false));
1172
1173 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1175 PGOOpt->CSProfileGenFile, Opts.enable_sampled_instrumentation));
1176
1177 if (IsMemprofUse)
1178 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1179
1180 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1181 PGOOpt->Action == PGOOptions::SampleUse))
1182 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1183
1184 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1185
1186 if (Opts.enable_module_inliner)
1188 else
1189 MPM.addPass(buildInlinerPipeline(Level, Phase));
1190
1191 // Remove any dead arguments exposed by cleanups, constant folding globals,
1192 // and argument promotion.
1194
1197
1198 if (!isThinLTOPreLink(Phase))
1199 MPM.addPass(CoroCleanupPass());
1200
1201 // Optimize globals now that functions are fully simplified.
1202 MPM.addPass(GlobalOptPass());
1203 MPM.addPass(GlobalDCEPass());
1204
1205 return MPM;
1206}
1207
1208/// TODO: Should LTO cause any differences to this set of passes?
1209void PassBuilder::addVectorPasses(OptimizationLevel Level,
1211 ThinOrFullLTOPhase LTOPhase) {
1214
1215 // Drop dereferenceable assumes after vectorization, as they are no longer
1216 // needed and can inhibit further optimization.
1217 if (!isLTOPreLink(LTOPhase))
1218 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1219
1221 if (isFullLTOPostLink(LTOPhase)) {
1222 // The vectorizer may have significantly shortened a loop body; unroll
1223 // again. Unroll small loops to hide loop backedge latency and saturate any
1224 // parallel execution resources of an out-of-order processor. We also then
1225 // need to clean up redundancies and loop invariant code.
1226 // FIXME: It would be really good to use a loop-integrated instruction
1227 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1228 // across the loop nests.
1229 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1230 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling)
1232 LoopUnrollAndJamPass(static_cast<int>(Level))));
1234 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1237 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1238 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1239 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1240 // NOTE: we are very late in the pipeline, and we don't have any LICM
1241 // or SimplifyCFG passes scheduled after us, that would cleanup
1242 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1243
1244 // We also turn on struct to vector canonicalization here, which allows
1245 // converting allocas of homogeneous structs into vector allocas when the
1246 // allocas' users are all memory intrinsics. This allows promotion in some
1247 // cases because structs cannot promote to SSA values, but vectors can. We
1248 // only turn this on after memcpyopt runs because this might hinder
1249 // memcpyopt's optimizations if done before. Look at the documentation for
1250 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1252 /*AggregateToVector=*/true)));
1253 }
1254
1255 if (!isFullLTOPostLink(LTOPhase)) {
1256 // Eliminate loads by forwarding stores from the previous iteration to loads
1257 // of the current iteration.
1259 }
1260 // Cleanup after the loop optimization passes.
1261 FPM.addPass(InstCombinePass());
1262
1263 if (Level > OptimizationLevel::O1 && Opts.extra_vectorizer_passes) {
1264 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1265 // At higher optimization levels, try to clean up any runtime overlap and
1266 // alignment checks inserted by the vectorizer. We want to track correlated
1267 // runtime checks for two inner loops in the same outer loop, fold any
1268 // common computations, hoist loop-invariant aspects out of any outer loop,
1269 // and unswitch the runtime checks if possible. Once hoisted, we may have
1270 // dead (or speculatable) control flows or more combining opportunities.
1271 ExtraPasses.addPass(EarlyCSEPass());
1272 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1273 ExtraPasses.addPass(InstCombinePass());
1274 LoopPassManager LPM;
1275 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1276 /*AllowSpeculation=*/true));
1277 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1279 ExtraPasses.addPass(
1280 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1281 ExtraPasses.addPass(
1282 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1283 ExtraPasses.addPass(InstCombinePass());
1284 FPM.addPass(std::move(ExtraPasses));
1285 }
1286
1287 // Now that we've formed fast to execute loop structures, we do further
1288 // optimizations. These are run afterward as they might block doing complex
1289 // analyses and transforms such as what are needed for loop vectorization.
1290
1291 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1292 // GVN, loop transforms, and others have already run, so it's now better to
1293 // convert to more optimized IR using more aggressive simplify CFG options.
1294 // The extra sinking transform can create larger basic blocks, so do this
1295 // before SLP vectorization.
1296 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1297 .forwardSwitchCondToPhi(true)
1298 .convertSwitchRangeToICmp(true)
1299 .convertSwitchToArithmetic(true)
1300 .convertSwitchToLookupTable(true)
1301 .needCanonicalLoops(false)
1302 .hoistCommonInsts(true)
1303 .sinkCommonInsts(true)));
1304
1305 if (isFullLTOPostLink(LTOPhase)) {
1306 FPM.addPass(SCCPPass());
1307 FPM.addPass(InstCombinePass());
1308 FPM.addPass(BDCEPass());
1309 }
1310
1311 // Optimize parallel scalar instruction chains into SIMD instructions.
1312 if (PTO.SLPVectorization) {
1313 FPM.addPass(SLPVectorizerPass());
1314 if (Level >= OptimizationLevel::O2 && Opts.extra_vectorizer_passes) {
1315 FPM.addPass(EarlyCSEPass());
1316 }
1317 }
1318 // Enhance/cleanup vector code.
1319 FPM.addPass(VectorCombinePass());
1320
1321 if (!isFullLTOPostLink(LTOPhase)) {
1322 FPM.addPass(InstCombinePass());
1323 // Unroll small loops to hide loop backedge latency and saturate any
1324 // parallel execution resources of an out-of-order processor. We also then
1325 // need to clean up redundancies and loop invariant code.
1326 // FIXME: It would be really good to use a loop-integrated instruction
1327 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1328 // across the loop nests.
1329 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1330 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling) {
1332 LoopUnrollAndJamPass(static_cast<int>(Level))));
1333 }
1334 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1335 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1336 PTO.ForgetAllSCEVInLoopUnroll)));
1337 FPM.addPass(WarnMissedTransformationsPass());
1338 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1339 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1340 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1341 // NOTE: we are very late in the pipeline, and we don't have any LICM
1342 // or SimplifyCFG passes scheduled after us, that would cleanup
1343 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1344
1345 // We also turn on struct to vector canonicalization here, which allows
1346 // converting allocas of homogeneous structs into vector allocas when the
1347 // allocas' users are all memory intrinsics. This allows promotion in some
1348 // cases because structs cannot promote to SSA values, but vectors can. We
1349 // only turn this on after memcpyopt runs because this might hinder
1350 // memcpyopt's optimizations if done before. Look at the documentation for
1351 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1352 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1353 /*AggregateToVector=*/true)));
1354 }
1355
1356 FPM.addPass(InferAlignmentPass());
1357 FPM.addPass(InstCombinePass());
1358
1359 // This is needed for two reasons:
1360 // 1. It works around problems that instcombine introduces, such as sinking
1361 // expensive FP divides into loops containing multiplications using the
1362 // divide result.
1363 // 2. It helps to clean up some loop-invariant code created by the loop
1364 // unroll pass when IsFullLTO=false.
1366 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1367 /*AllowSpeculation=*/true),
1368 /*UseMemorySSA=*/true));
1369
1370 // Now that we've vectorized and unrolled loops, we may have more refined
1371 // alignment information, try to re-derive it here.
1372 FPM.addPass(AlignmentFromAssumptionsPass());
1373}
1374
1377 ThinOrFullLTOPhase LTOPhase) {
1379
1380 // Run partial inlining pass to partially inline functions that have
1381 // large bodies.
1382 if (Opts.enable_partial_inlining)
1384
1385 // Remove avail extern fns and globals definitions since we aren't compiling
1386 // an object file for later LTO. For LTO we want to preserve these so they
1387 // are eligible for inlining at link-time. Note if they are unreferenced they
1388 // will be removed by GlobalDCE later, so this only impacts referenced
1389 // available externally globals. Eventually they will be suppressed during
1390 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1391 // may make globals referenced by available external functions dead and saves
1392 // running remaining passes on the eliminated functions. These should be
1393 // preserved during prelinking for link-time inlining decisions.
1394 if (!isLTOPreLink(LTOPhase))
1396
1397 // Do RPO function attribute inference across the module to forward-propagate
1398 // attributes where applicable.
1399 // FIXME: Is this really an optimization rather than a canonicalization?
1400 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1402 else
1404
1405 // Do a post inline PGO instrumentation and use pass. This is a context
1406 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1407 // cross-module inline has not been done yet. The context sensitive
1408 // instrumentation is after all the inlines are done.
1409 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1410 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1411 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1412 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1413 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1414 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1415 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1416 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1417 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1418 }
1419
1420 // Re-compute GlobalsAA here prior to function passes. This is particularly
1421 // useful as the above will have inlined, DCE'ed, and function-attr
1422 // propagated everything. We should at this point have a reasonably minimal
1423 // and richly annotated call graph. By computing aliasing and mod/ref
1424 // information for all local globals here, the late loop passes and notably
1425 // the vectorizer will be able to use them to help recognize vectorizable
1426 // memory operations.
1427 if (Opts.enable_global_analyses)
1429
1430 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1431
1432 FunctionPassManager OptimizePM;
1433
1434 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1435 // additional uses of the affected value may be introduced through inlining
1436 // and CSE.
1437 if (!isLTOPreLink(LTOPhase))
1438 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1439
1440 // Scheduling LoopVersioningLICM when inlining is over, because after that
1441 // we may see more accurate aliasing. Reason to run this late is that too
1442 // early versioning may prevent further inlining due to increase of code
1443 // size. Other optimizations which runs later might get benefit of no-alias
1444 // assumption in clone loop.
1445 if (Opts.enable_loop_versioning_licm) {
1446 OptimizePM.addPass(
1448 // LoopVersioningLICM pass might increase new LICM opportunities.
1450 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1451 /*AllowSpeculation=*/true),
1452 /*USeMemorySSA=*/true));
1453 }
1454
1455 OptimizePM.addPass(Float2IntPass());
1456 // Defer until LTO post-link where some constants may become known.
1457 if (!isLTOPreLink(LTOPhase))
1459
1460 if (Opts.enable_matrix) {
1461 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1462 OptimizePM.addPass(EarlyCSEPass());
1463 }
1464
1465 // CHR pass should only be applied with the profile information.
1466 // The check is to check the profile summary information in CHR.
1467 if (Opts.enable_chr && Level == OptimizationLevel::O3)
1468 OptimizePM.addPass(ControlHeightReductionPass());
1469
1470 // FIXME: We need to run some loop optimizations to re-rotate loops after
1471 // simplifycfg and others undo their rotation.
1472
1473 // Optimize the loop execution. These passes operate on entire loop nests
1474 // rather than on each loop in an inside-out manner, and so they are actually
1475 // function passes.
1476
1477 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1478
1479 LoopPassManager LPM;
1480 // First rotate loops that may have been un-rotated by prior passes.
1481 // Disable header duplication at -Oz.
1482 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1483 isLTOPreLink(LTOPhase),
1484 /*CheckExitCount=*/true));
1485 // Some loops may have become dead by now. Try to delete them.
1486 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1487 // this may need to be revisited once we run GVN before loop deletion
1488 // in the simplification pipeline.
1489 LPM.addPass(LoopDeletionPass());
1490
1491 if (PTO.LoopInterchange)
1492 LPM.addPass(LoopInterchangePass());
1493
1494 OptimizePM.addPass(
1495 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1496
1497 // FIXME: This may not be the right place in the pipeline.
1498 // We need to have the data to support the right place.
1499 if (PTO.LoopFusion)
1500 OptimizePM.addPass(LoopFusePass());
1501
1502 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1503 // into separate loop that would otherwise inhibit vectorization. This is
1504 // currently only performed for loops marked with the metadata
1505 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1506 OptimizePM.addPass(LoopDistributePass());
1507
1508 // Populates the VFABI attribute with the scalar-to-vector mappings
1509 // from the TargetLibraryInfo.
1510 OptimizePM.addPass(InjectTLIMappings());
1511
1512 addVectorPasses(Level, OptimizePM, LTOPhase);
1513
1514 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1515
1516 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1517 // canonicalization pass that enables other optimizations. As a result,
1518 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1519 // result too early.
1520 OptimizePM.addPass(LoopSinkPass());
1521
1522 // And finally clean up LCSSA form before generating code.
1523 OptimizePM.addPass(InstSimplifyPass());
1524
1525 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1526 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1527 // flattening of blocks.
1528 OptimizePM.addPass(DivRemPairsPass());
1529
1530 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1531 // TODO: move this further up so that it can be optimized by GVN, etc.
1532 if (Opts.enable_mergeicmps)
1533 OptimizePM.addPass(MergeICmpsPass());
1534 OptimizePM.addPass(ExpandMemCmpPass());
1535
1536 // Try to annotate calls that were created during optimization.
1537 OptimizePM.addPass(
1538 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1539
1540 // LoopSink (and other loop passes since the last simplifyCFG) might have
1541 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1542 OptimizePM.addPass(
1544 .convertSwitchRangeToICmp(true)
1545 .convertSwitchToArithmetic(true)
1546 .speculateUnpredictables(true)
1547 .hoistLoadsStoresWithCondFaulting(true)));
1548
1549 // Add the core optimizing pipeline.
1550 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1551 PTO.EagerlyInvalidateAnalyses));
1552
1553 // AllocToken transforms heap allocation calls; this needs to run late after
1554 // other allocation call transformations (such as those in InstCombine).
1555 if (!isLTOPreLink(LTOPhase))
1556 MPM.addPass(AllocTokenPass());
1557
1558 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1559
1560 // Run the Instrumentor pass late.
1561 if (Opts.enable_instrumentor)
1562 MPM.addPass(InstrumentorPass(FS));
1563
1564 // Split out cold code. Splitting is done late to avoid hiding context from
1565 // other optimizations and inadvertently regressing performance. The tradeoff
1566 // is that this has a higher code size cost than splitting early.
1567 if (Opts.hot_cold_split && !isLTOPreLink(LTOPhase))
1569
1570 // Now we need to do some global optimization transforms.
1571 // FIXME: It would seem like these should come first in the optimization
1572 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1573 // ordering here.
1574 MPM.addPass(GlobalDCEPass());
1576
1577 // Merge functions if requested. It has a better chance to merge functions
1578 // after ConstantMerge folded jump tables.
1579 if (PTO.MergeFunctions)
1581
1582 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1583 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1584
1585 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1586 if (!isLTOPreLink(LTOPhase))
1588
1589 // Add devirtualization pass only when LTO is not enabled, as otherwise
1590 // the pass is already enabled in the LTO pipeline.
1591 if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1592 // TODO: explore a better pipeline configuration that can improve
1593 // compilation time overhead.
1594 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1595 MPM.addPass(AssignGUIDPass());
1597 /*ExportSummary*/ nullptr,
1598 /*ImportSummary*/ nullptr,
1599 /*DevirtSpeculatively*/ PTO.DevirtualizeSpeculatively));
1601 // Given that the devirtualization creates more opportunities for inlining,
1602 // we run the Inliner again here to maximize the optimization gain we
1603 // get from devirtualization.
1604 // Also, we can't run devirtualization before inlining because the
1605 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1606 // and those passes are only effective after inlining.
1608 }
1609
1610 // Attach !implicit.ref metadata from all functions to copyright strings.
1612
1613 return MPM;
1614}
1615
1619 if (Level == OptimizationLevel::O0)
1620 return buildO0DefaultPipeline(Level, Phase);
1621
1623 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1624 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1625 // are not running LTO. If that changes the below checks may need updating.
1627
1628 // If we are invoking this in non-LTO mode, remove any MemProf related
1629 // attributes and metadata, as we don't know whether we are linking with
1630 // a library containing the necessary interfaces.
1633
1634 // Convert @llvm.global.annotations to !annotation metadata.
1636
1637 // Force any function attributes we want the rest of the pipeline to observe.
1639
1640 if (Opts.opt_pipeline_trigger_crash)
1642
1643 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1645
1646 // Apply module pipeline start EP callback.
1648
1649 // Add the core simplification pipeline.
1651
1652 // Now add the optimization pipeline.
1654
1655 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1656 PGOOpt->Action == PGOOptions::SampleUse)
1658
1659 // Emit annotation remarks.
1661
1662 if (isLTOPreLink(Phase))
1663 addRequiredLTOPreLinkPasses(MPM);
1664
1665 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1666 return MPM;
1667}
1668
1671 bool EmitSummary, bool Verify) {
1673
1674 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1675
1676 if (ThinLTO)
1678 else
1680 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1681 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1682 // bitcode emission runs VerifierPass by default, which registers metadata
1683 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1684 // to get the same behavior.
1685 if (Verify)
1686 MPM.addPass(VerifierPass());
1687 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1688
1689 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1690 // like removing CFI/WPD related instructions. Note, we reuse
1691 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1692 // in FatLtoCleanup.
1693 MPM.addPass(FatLtoCleanup());
1694
1695 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1696 // object code, only in the bitcode section, so drop it before we run
1697 // module optimization and generate machine code. If llvm.type.test() isn't in
1698 // the IR, this won't do anything.
1700
1701 // Use the ThinLTO post-link pipeline with sample profiling
1702 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1703 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1704 else {
1705 // ModuleSimplification does not run the coroutine passes for
1706 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1707 // builds, otherwise they will miscompile.
1708 if (ThinLTO) {
1709 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1710 // consideration.
1711 CGSCCPassManager CGPM;
1715 MPM.addPass(CoroCleanupPass());
1716 }
1717
1718 // otherwise, just use module optimization
1719 MPM.addPass(
1721 // Emit annotation remarks.
1723 }
1724
1725 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1726
1727 return MPM;
1728}
1729
1732 if (Level == OptimizationLevel::O0)
1734
1736
1737 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1738
1739 // Convert @llvm.global.annotations to !annotation metadata.
1741
1742 // Force any function attributes we want the rest of the pipeline to observe.
1744
1745 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1747
1748 // Apply module pipeline start EP callback.
1750
1751 // If we are planning to perform ThinLTO later, we don't bloat the code with
1752 // unrolling/vectorization/... now. Just simplify the module as much as we
1753 // can.
1756 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1757 // thinlto use the contextual info to perform imports; then use the contextual
1758 // profile in the post-thinlink phase.
1759 if (!UseCtxProfile.empty()) {
1760 addRequiredLTOPreLinkPasses(MPM);
1761 return MPM;
1762 }
1763
1764 // Run partial inlining pass to partially inline functions that have
1765 // large bodies.
1766 // FIXME: It isn't clear whether this is really the right place to run this
1767 // in ThinLTO. Because there is another canonicalization and simplification
1768 // phase that will run after the thin link, running this here ends up with
1769 // less information than will be available later and it may grow functions in
1770 // ways that aren't beneficial.
1771 if (Opts.enable_partial_inlining)
1773
1774 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1775 PGOOpt->Action == PGOOptions::SampleUse)
1777
1778 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1779 // optimization is going to be done in PostLink stage, but clang can't add
1780 // callbacks there in case of in-process ThinLTO called by linker.
1785
1786 // Emit annotation remarks.
1788
1789 // Attach !implicit.ref metadata from all functions to copyright strings.
1791
1792 addRequiredLTOPreLinkPasses(MPM);
1793
1794 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1795
1796 return MPM;
1797}
1798
1800 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1802
1803 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1804
1806
1807 // If we are invoking this without a summary index noting that we are linking
1808 // with a library containing the necessary APIs, remove any MemProf related
1809 // attributes and metadata.
1810 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1812
1813 if (ImportSummary) {
1814 // For ThinLTO we must apply the context disambiguation decisions early, to
1815 // ensure we can correctly match the callsites to summary data.
1818 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1819
1820 // These passes import type identifier resolutions for whole-program
1821 // devirtualization and CFI. They must run early because other passes may
1822 // disturb the specific instruction patterns that these passes look for,
1823 // creating dependencies on resolutions that may not appear in the summary.
1824 //
1825 // For example, GVN may transform the pattern assume(type.test) appearing in
1826 // two basic blocks into assume(phi(type.test, type.test)), which would
1827 // transform a dependency on a WPD resolution into a dependency on a type
1828 // identifier resolution for CFI.
1829 //
1830 // Also, WPD has access to more precise information than ICP and can
1831 // devirtualize more effectively, so it should operate on the IR first.
1832 //
1833 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1834 // metadata and intrinsics.
1835 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1836 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1837 }
1838
1839 if (Level == OptimizationLevel::O0) {
1840 // Run a second time to clean up any type tests left behind by WPD for use
1841 // in ICP.
1844
1845 // AllocToken transforms heap allocation calls; this needs to run late after
1846 // other allocation call transformations (such as those in InstCombine).
1847 MPM.addPass(AllocTokenPass());
1848
1849 // Drop available_externally and unreferenced globals. This is necessary
1850 // with ThinLTO in order to avoid leaving undefined references to dead
1851 // globals in the object file.
1853 MPM.addPass(GlobalDCEPass());
1854
1856
1857 return MPM;
1858 }
1859 if (!UseCtxProfile.empty()) {
1860 MPM.addPass(
1862 } else {
1863 // Add the core simplification pipeline.
1866 }
1867 // Now add the optimization pipeline.
1870
1872
1873 // Emit annotation remarks.
1875
1876 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1877
1878 return MPM;
1879}
1880
1883 // FIXME: We should use a customized pre-link pipeline!
1884 return buildPerModuleDefaultPipeline(Level,
1886}
1887
1890 ModuleSummaryIndex *ExportSummary) {
1892
1893 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1894
1896
1897 // If we are invoking this without a summary index noting that we are linking
1898 // with a library containing the necessary APIs, remove any MemProf related
1899 // attributes and metadata.
1900 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
1902
1903 // Create a function that performs CFI checks for cross-DSO calls with targets
1904 // in the current module.
1905 MPM.addPass(CrossDSOCFIPass());
1906
1907 if (Level == OptimizationLevel::O0) {
1908 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1909 // metadata and intrinsics.
1910 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1911 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1912 // Run a second time to clean up any type tests left behind by WPD for use
1913 // in ICP.
1915
1917
1918 // AllocToken transforms heap allocation calls; this needs to run late after
1919 // other allocation call transformations (such as those in InstCombine).
1920 MPM.addPass(AllocTokenPass());
1921
1923
1924 // Emit annotation remarks.
1926
1927 return MPM;
1928 }
1929
1930 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1931 // Load sample profile before running the LTO optimization pipeline.
1932 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1933 PGOOpt->ProfileRemappingFile,
1935 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1936 // RequireAnalysisPass for PSI before subsequent non-module passes.
1938 }
1939
1940 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1942
1943 // Remove unused virtual tables to improve the quality of code generated by
1944 // whole-program devirtualization and bitset lowering.
1945 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1946
1947 // Do basic inference of function attributes from known properties of system
1948 // libraries and other oracles.
1950
1951 if (Level >= OptimizationLevel::O2) {
1953 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
1954
1955 // Indirect call promotion. This should promote all the targets that are
1956 // left by the earlier promotion pass that promotes intra-module targets.
1957 // This two-step promotion is to save the compile time. For LTO, it should
1958 // produce the same result as if we only do promotion here.
1960 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1961
1962 // Promoting by-reference arguments to by-value exposes more constants to
1963 // IPSCCP.
1964 CGSCCPassManager CGPM;
1965 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
1967 else
1970 CGPM.addPass(
1973
1974 // Propagate constants at call sites into the functions they call. This
1975 // opens opportunities for globalopt (and inlining) by substituting function
1976 // pointers passed as arguments to direct uses of functions.
1977 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
1978
1979 // Attach metadata to indirect call sites indicating the set of functions
1980 // they may target at run-time. This should follow IPSCCP.
1982 }
1983
1984 // Do RPO function attribute inference across the module to forward-propagate
1985 // attributes where applicable.
1986 // FIXME: Is this really an optimization rather than a canonicalization?
1987 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1989 else
1991
1992 // Use in-range annotations on GEP indices to split globals where beneficial.
1993 MPM.addPass(GlobalSplitPass());
1994
1995 // Run whole program optimization of virtual call when the list of callees
1996 // is fixed.
1997 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1998
2000 // Stop here at -O1.
2001 if (Level == OptimizationLevel::O1) {
2003 LowerConstantIntrinsicsPass(), PTO.EagerlyInvalidateAnalyses));
2004
2005 // The LowerTypeTestsPass needs to run to lower type metadata and the
2006 // type.test intrinsics. The pass does nothing if CFI is disabled.
2007 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2008 // Run a second time to clean up any type tests left behind by WPD for use
2009 // in ICP (which is performed earlier than this in the regular LTO
2010 // pipeline).
2012
2014
2015 // AllocToken transforms heap allocation calls; this needs to run late after
2016 // other allocation call transformations (such as those in InstCombine).
2017 MPM.addPass(AllocTokenPass());
2018
2020
2021 // Emit annotation remarks.
2023
2024 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2025
2026 return MPM;
2027 }
2028
2029 // TODO: Skip to match buildCoroWrapper.
2030 MPM.addPass(CoroEarlyPass());
2031
2032 // Optimize globals to try and fold them into constants.
2033 MPM.addPass(GlobalOptPass());
2034
2035 // Promote any localized globals to SSA registers.
2037
2038 // Linking modules together can lead to duplicate global constant, only
2039 // keep one copy of each constant.
2041
2042 // Remove unused arguments from functions.
2044
2045 // Reduce the code after globalopt and ipsccp. Both can open up significant
2046 // simplification opportunities, and both can propagate functions through
2047 // function pointers. When this happens, we often have to resolve varargs
2048 // calls, etc, so let instcombine do this.
2049 FunctionPassManager PeepholeFPM;
2050 PeepholeFPM.addPass(InstCombinePass());
2051 if (Level >= OptimizationLevel::O2)
2052 PeepholeFPM.addPass(AggressiveInstCombinePass());
2053 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2054
2055 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
2056 PTO.EagerlyInvalidateAnalyses));
2057
2058 // Lower variadic functions for supported targets prior to inlining.
2060
2061 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2062 // generally clean up exception handling overhead. It isn't clear this is
2063 // valuable as the inliner doesn't currently care whether it is inlining an
2064 // invoke or a call.
2065 // Run the inliner now.
2067
2068 // Perform context disambiguation after inlining, since that would reduce the
2069 // amount of additional cloning required to distinguish the allocation
2070 // contexts.
2073 /*Summary=*/nullptr,
2074 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2075
2076 // Optimize globals again after we ran the inliner.
2077 MPM.addPass(GlobalOptPass());
2078
2079 // Run the OpenMPOpt pass again after global optimizations.
2081
2082 // Garbage collect dead functions.
2083 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2084
2085 // If we didn't decide to inline a function, check to see if we can
2086 // transform it to pass arguments by value instead of by reference.
2087 CGSCCPassManager CGPM;
2093
2095 // The IPO Passes may leave cruft around. Clean up after them.
2096 FPM.addPass(InstCombinePass());
2097 invokePeepholeEPCallbacks(FPM, Level);
2098
2099 if (Opts.enable_constraint_elimination)
2101
2103
2104 // Do a post inline PGO instrumentation and use pass. This is a context
2105 // sensitive PGO pass.
2106 if (PGOOpt) {
2107 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2108 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2109 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2110 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2111 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2112 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2113 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2114 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2115 }
2116
2117 // Break up allocas
2119
2120 // LTO provides additional opportunities for tailcall elimination due to
2121 // link-time inlining, and visibility of nocapture attribute.
2122 FPM.addPass(
2123 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2124
2125 // Run a few AA driver optimizations here and now to cleanup the code.
2126 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
2127 PTO.EagerlyInvalidateAnalyses));
2128
2129 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
2130 MPM.addPass(
2132 } else {
2133 MPM.addPass(
2135 }
2136
2137 // Require the GlobalsAA analysis for the module so we can query it within
2138 // MainFPM.
2139 if (Opts.enable_global_analyses) {
2141 // Invalidate AAManager so it can be recreated and pick up the newly
2142 // available GlobalsAA.
2143 MPM.addPass(
2145 }
2146
2147 FunctionPassManager MainFPM;
2149 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
2150 /*AllowSpeculation=*/true),
2151 /*USeMemorySSA=*/true));
2152
2153 if (Opts.enable_newgvn)
2154 MainFPM.addPass(NewGVNPass());
2155 else
2156 MainFPM.addPass(GVNPass());
2157
2158 // Remove dead memcpy()'s.
2159 MainFPM.addPass(MemCpyOptPass());
2160
2161 // Nuke dead stores.
2162 MainFPM.addPass(DSEPass());
2163 MainFPM.addPass(MoveAutoInitPass());
2165
2167
2168 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2169
2170 LoopPassManager LPM;
2171 if (Opts.enable_loop_flatten && Level >= OptimizationLevel::O2)
2172 LPM.addPass(LoopFlattenPass());
2173 LPM.addPass(IndVarSimplifyPass());
2174 LPM.addPass(LoopDeletionPass());
2175 // FIXME: Add loop interchange.
2176
2177 // Unroll small loops and perform peeling.
2178 LPM.addPass(LoopFullUnrollPass(static_cast<int>(Level),
2179 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2180 PTO.ForgetAllSCEVInLoopUnroll));
2181 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2182 // *All* loop passes must preserve it, in order to be able to use it.
2183 MainFPM.addPass(
2184 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2185
2186 MainFPM.addPass(LoopDistributePass());
2187
2188 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2189
2190 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2191
2192 // Run the OpenMPOpt CGSCC pass again late.
2195
2196 invokePeepholeEPCallbacks(MainFPM, Level);
2197 MainFPM.addPass(JumpThreadingPass());
2198 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
2199 PTO.EagerlyInvalidateAnalyses));
2200
2201 // Lower type metadata and the type.test intrinsic. This pass supports
2202 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2203 // to be run at link time if CFI is enabled. This pass does nothing if
2204 // CFI is disabled.
2205 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2206 // Run a second time to clean up any type tests left behind by WPD for use
2207 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2209
2210 // Enable splitting late in the FullLTO post-link pipeline.
2211 if (Opts.hot_cold_split)
2213
2214 // Add late LTO optimization passes.
2215 FunctionPassManager LateFPM;
2216
2217 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2218 // canonicalization pass that enables other optimizations. As a result,
2219 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2220 // result too early.
2221 LateFPM.addPass(LoopSinkPass());
2222
2223 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2224 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2225 // flattening of blocks.
2226 LateFPM.addPass(DivRemPairsPass());
2227
2228 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
2229 // TODO: move this further up so that it can be optimized by GVN, etc.
2230 if (Opts.enable_mergeicmps)
2231 LateFPM.addPass(MergeICmpsPass());
2232 LateFPM.addPass(ExpandMemCmpPass());
2233
2234 // Delete basic blocks, which optimization passes may have killed.
2236 .convertSwitchRangeToICmp(true)
2237 .convertSwitchToArithmetic(true)
2238 .hoistCommonInsts(true)
2239 .speculateUnpredictables(true)));
2240 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2241
2242 // Drop bodies of available eternally objects to improve GlobalDCE.
2244
2245 // Now that we have optimized the program, discard unreachable functions.
2246 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2247
2248 if (PTO.MergeFunctions)
2250
2252
2253 if (PTO.CallGraphProfile)
2254 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2255
2256 MPM.addPass(CoroCleanupPass());
2257
2258 // AllocToken transforms heap allocation calls; this needs to run late after
2259 // other allocation call transformations (such as those in InstCombine).
2260 MPM.addPass(AllocTokenPass());
2261
2263
2264 // Emit annotation remarks.
2266
2267 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2268
2269 return MPM;
2270}
2271
2275 assert(Level == OptimizationLevel::O0 &&
2276 "buildO0DefaultPipeline should only be used with O0");
2277
2279
2280 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2281
2282 // Perform pseudo probe instrumentation in O0 mode. This is for the
2283 // consistency between different build modes. For example, a LTO build can be
2284 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2285 // the postlink will require pseudo probe instrumentation in the prelink.
2286 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2288
2289 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2290 PGOOpt->Action == PGOOptions::IRUse))
2292 MPM,
2293 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2294 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2295 PGOOpt->ProfileRemappingFile);
2296
2297 // Instrument function entry and exit before all inlining.
2299 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2300
2302
2303 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2305
2306 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2307 // Explicitly disable sample loader inlining and use flattened profile in O0
2308 // pipeline.
2309 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2310 PGOOpt->ProfileRemappingFile,
2312 /*DisableSampleProfileInlining=*/true,
2313 /*UseFlattenedProfile=*/true));
2314 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2315 // RequireAnalysisPass for PSI before subsequent non-module passes.
2317 }
2318
2320
2321 // Build a minimal pipeline based on the semantics required by LLVM,
2322 // which is just that always inlining occurs. Further, disable generating
2323 // lifetime intrinsics to avoid enabling further optimizations during
2324 // code generation.
2326 /*InsertLifetimeIntrinsics=*/false));
2327
2328 if (PTO.MergeFunctions)
2330
2331 if (Opts.enable_matrix)
2332 MPM.addPass(
2334
2335 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2336 CGSCCPassManager CGPM;
2338 if (!CGPM.isEmpty())
2340 }
2341 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2342 LoopPassManager LPM;
2344 if (!LPM.isEmpty()) {
2346 createFunctionToLoopPassAdaptor(std::move(LPM))));
2347 }
2348 }
2349 if (!LoopOptimizerEndEPCallbacks.empty()) {
2350 LoopPassManager LPM;
2352 if (!LPM.isEmpty()) {
2354 createFunctionToLoopPassAdaptor(std::move(LPM))));
2355 }
2356 }
2357 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2360 if (!FPM.isEmpty())
2361 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2362 }
2363
2365
2366 if (!VectorizerStartEPCallbacks.empty()) {
2369 if (!FPM.isEmpty())
2370 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2371 }
2372
2373 if (!VectorizerEndEPCallbacks.empty()) {
2376 if (!FPM.isEmpty())
2377 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2378 }
2379
2381
2382 // AllocToken transforms heap allocation calls; this needs to run late after
2383 // other allocation call transformations (such as those in InstCombine).
2384 if (!isLTOPreLink(Phase))
2385 MPM.addPass(AllocTokenPass());
2386
2388
2389 if (Opts.enable_instrumentor)
2390 MPM.addPass(InstrumentorPass(FS));
2391
2392 // Attach !implicit.ref metadata from all functions to copyright strings.
2394
2395 if (isLTOPreLink(Phase))
2396 addRequiredLTOPreLinkPasses(MPM);
2397
2398 // Emit annotation remarks.
2400
2401 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2402
2403 return MPM;
2404}
2405
2407 AAManager AA;
2408
2409 // The order in which these are registered determines their priority when
2410 // being queried.
2411
2412 // Add any target-specific alias analyses that should be run early.
2413 if (TM)
2414 TM->registerEarlyDefaultAliasAnalyses(AA);
2415
2416 // First we register the basic alias analysis that provides the majority of
2417 // per-function local AA logic. This is a stateless, on-demand local set of
2418 // AA techniques.
2419 AA.registerFunctionAnalysis<BasicAA>();
2420
2421 // Next we query fast, specialized alias analyses that wrap IR-embedded
2422 // information about aliasing.
2423 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2424 AA.registerFunctionAnalysis<TypeBasedAA>();
2425
2426 // Add support for querying global aliasing information when available.
2427 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2428 // analysis, all that the `AAManager` can do is query for any *cached*
2429 // results from `GlobalsAA` through a readonly proxy.
2430 if (Opts.enable_global_analyses)
2431 AA.registerModuleAnalysis<GlobalsAA>();
2432
2433 // Add target-specific alias analyses.
2434 if (TM)
2435 TM->registerDefaultAliasAnalyses(AA);
2436
2437 return AA;
2438}
2439
2440bool PassBuilder::isInstrumentedPGOUse() const {
2441 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2442 !UseCtxProfile.empty();
2443}
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 bool isThinLTOPostLink(ThinOrFullLTOPhase Phase)
static void addAnnotationRemarksPass(ModulePassManager &MPM)
static CoroConditionalWrapper buildCoroWrapper(ThinOrFullLTOPhase Phase)
static bool isFullLTOPostLink(ThinOrFullLTOPhase Phase)
static void addModuleInlinerPass(ModulePassManager &MPM, const PassesOptions &Opts, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
static bool isThinLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
static void instructionCountersPass(ModulePassManager &MPM, bool IsPreOptimization)
static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPostLink(ThinOrFullLTOPhase Phase)
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file provides the interface for the pseudo probe implementation for AutoFDO.
This file provides the interface for the sampled PGO loader pass.
This is the interface for a metadata-based scoped no-alias analysis.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
This is the interface for a metadata-based TBAA.
A manager for alias analyses.
A module pass that rewrites heap allocations to use token-enabled allocation functions based on vario...
Definition AllocToken.h:36
Inlines functions marked as "always_inline".
Argument promotion pass.
Analysis pass providing a never-invalidated alias analysis result.
Simple pass that canonicalizes aliases.
A pass that merges duplicate global constants into a single constant.
This class implements a trivial dead store elimination.
Eliminate dead arguments (and return values) from functions.
A pass that transforms external global definitions into declarations.
Pass embeds a copy of the module optimized with the provided pass pipeline into a global variable.
A pass manager to run a set of extra loop passes if the MarkerTy analysis is present.
Statistics pass for the FunctionPropertiesAnalysis results.
Pass to remove unused function declarations.
Definition GlobalDCE.h:38
Optimize globals that never have their address taken.
Definition GlobalOpt.h:25
Pass to perform split of global variables.
Definition GlobalSplit.h:26
Analysis pass providing a never-invalidated alias analysis result.
Pass to outline cold regions.
Pass to perform interprocedural constant propagation.
Definition SCCP.h:48
Run instruction simplification across each instruction in the function.
Instrumentation based profiling lowering pass.
The Instrumentor pass.
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
Performs Loop Invariant Code Motion Pass.
Definition LICM.h:67
Loop unroll pass that only does full loop unrolling and peeling.
Performs Loop Idiom Recognize Pass.
Performs Loop Inst Simplify Pass.
A simple loop rotation transformation.
Performs basic CFG simplifications to assist other loop passes.
A pass that does profile-guided sinking of instructions into loops.
Definition LoopSink.h:33
A simple loop rotation transformation.
Loop unroll pass that will support both full and partial unrolling.
Strips MemProf attributes and metadata.
Merge identical functions.
The module inliner pass for the new pass manager.
Module pass, wrapping the inliner pass.
Definition Inliner.h:65
void addModulePass(T Pass)
Add a module pass that runs before the CGSCC passes.
Definition Inliner.h:81
CGSCCPassManager & getPM()
Allow adding more CGSCC passes, besides inlining.
Definition Inliner.h:78
void addLateModulePass(T Pass)
Add a module pass that runs after the CGSCC passes.
Definition Inliner.h:86
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Simple pass that provides a name to every anonymous globals.
Additional 'norecurse' attribute deduction during postlink LTO phase.
OpenMP optimizations pass.
Definition OpenMPOpt.h:42
static LLVM_ABI bool isCtxIRPGOInstrEnabled()
The indirect function call promotion pass.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The profile annotation (profile-instr-use) pass for IR based PGO.
The profile size based optimization pass for memory intrinsics.
Pass to remove unused function declarations.
LLVM_ABI void invokeFullLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModuleInlinerWrapperPass buildInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining as well as the inlining-driven cleanups.
LLVM_ABI void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO, bool EmitSummary, bool Verify=true)
Build a fat object default optimization pipeline.
LLVM_ABI void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI AAManager buildDefaultAAPipeline()
Build the default AAManager with the default alias analysis pipeline registered.
LLVM_ABI void invokeCGSCCOptimizerLateEPCallbacks(CGSCCPassManager &CGPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, ThinLTO-targeting default optimization pipeline to a pass manager.
LLVM_ABI void addPGOInstrPassesForO0(ModulePassManager &MPM, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, std::string ProfileRemappingFile)
Add PGOInstrumenation passes for O0 only.
LLVM_ABI void invokeScalarOptimizerLateEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build a per-module default optimization pipeline.
LLVM_ABI void invokePipelineStartEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI void invokeVectorizerEndEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI void invokeThinLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildO0DefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build an O0 pipeline with the minimal semantically required passes.
LLVM_ABI FunctionPassManager buildFunctionSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM function canonicalization and simplification pipeline.
LLVM_ABI void invokePeepholeEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI void invokePipelineEarlySimplificationEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI void invokeLoopOptimizerEndEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
LLVM_ABI ModulePassManager buildModuleInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining with module inliner pass.
LLVM_ABI ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build a ThinLTO default optimization pipeline to a pass manager.
LLVM_ABI void invokeLateLoopOptimizationsEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
LLVM_ABI void invokeFullLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildModuleSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM module canonicalization and simplification pipeline.
LLVM_ABI ModulePassManager buildModuleOptimizationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase LTOPhase)
Construct the core LLVM module optimization pipeline.
LLVM_ABI void invokeThinLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI void invokeOptimizerLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, LTO-targeting default optimization pipeline to a pass manager.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
bool isEmpty() const
Returns if the pass manager contains any passes.
unsigned LicmMssaNoAccForPromotionCap
Tuning option to disable promotion to scalars in LICM with MemorySSA, if the number of access is too ...
Definition PassBuilder.h:79
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:57
int InlinerThreshold
Tuning option to override the default inliner threshold.
Definition PassBuilder.h:93
bool LoopFusion
Tuning option to enable/disable loop fusion. Its default value is false.
Definition PassBuilder.h:67
bool CallGraphProfile
Tuning option to enable/disable call graph profile.
Definition PassBuilder.h:83
bool MergeFunctions
Tuning option to enable/disable function merging.
Definition PassBuilder.h:90
bool ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition PassBuilder.h:71
unsigned LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition PassBuilder.h:75
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition PassBuilder.h:49
LLVM_ABI PipelineTuningOptions()
Constructor sets pipeline tuning defaults based on cl::opts.
bool LoopUnrolling
Tuning option to enable/disable loop unrolling. Its default value is true.
Definition PassBuilder.h:60
bool LoopInterchange
Tuning option to enable/disable loop interchange.
Definition PassBuilder.h:64
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:53
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
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
LLVM_ABI bool getForgetSCEVInLoopUnroll()
Returns -forget-scev-loop-unroll.
@ 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:77
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:85
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
Definition Pass.h:83
@ None
No LTO/ThinLTO behavior needed.
Definition Pass.h:79
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:87
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:81
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
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.
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
LLVM_ABI unsigned getLicmMssaNoAccForPromotionCap()
Returns -licm-mssa-max-acc-promotion.
Definition LICM.cpp:123
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
LLVM_ABI unsigned getLicmMssaOptCap()
Returns -licm-mssa-optimization-cap.
Definition LICM.cpp:119
LLVM_ABI InlineParams getInlineParamsFromOptLevel(unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
cl::opt< unsigned > MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden, cl::init(4))
LLVM_ABI bool isPGOInstrumentColdFunctionOnly()
Return the value of -pgo-instrument-cold-function-only.
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:207
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:216
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:228
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:209
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition InlineCost.h:241
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:212
Options for the frontend instrumentation based profiling pass.
A no-op pass template which simply forces a specific analysis result to be invalidated.
Pass to forward loads in a loop around the backedge to subsequent iterations.
A set of parameters used to control various transforms performed by the LoopUnroll pass.
The LoopVectorize Pass.
Computes function attributes in post-order over the call graph.
A utility pass template to force an analysis result to be available.