1//===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
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
7//===----------------------------------------------------------------------===//
9// This file implements some loop unrolling utilities. It does not define any
10// actual pass or policy, but provides a single function to perform loop
13// The process of unrolling can produce extraneous basic blocks linked with
14// unconditional branches. This will be corrected in the future.
16//===----------------------------------------------------------------------===//
79 #define DEBUG_TYPE "loop-unroll"
81// TODO: Should these be here or in LoopUnroll?
82 STATISTIC(NumCompletelyUnrolled,
"Number of loops completely unrolled");
83 STATISTIC(NumUnrolled,
"Number of loops unrolled (completely or otherwise)");
84 STATISTIC(NumUnrolledNotLatch,
"Number of loops unrolled without a conditional "
85 "latch (completely or otherwise)");
89 cl::desc(
"Allow runtime unrolled loops to be unrolled "
90 "with epilog instead of prolog."));
94 cl::desc(
"Verify domtree after unrolling"),
95#ifdef EXPENSIVE_CHECKS
104 cl::desc(
"Verify loopinfo after unrolling"),
105#ifdef EXPENSIVE_CHECKS
114 cl::desc(
"Allow unrolling to add parallel reduction phis."));
116/// Check if unrolling created a situation where we need to insert phi nodes to
117/// preserve LCSSA form.
118/// \param Blocks is a vector of basic blocks representing unrolled loop.
119/// \param L is the outer loop.
120/// It's possible that some of the blocks are in L, and some are not. In this
121/// case, if there is a use is outside L, and definition is inside L, we need to
122/// insert a phi-node, otherwise LCSSA will be broken.
123/// The function is just a helper function for llvm::UnrollLoop that returns
124/// true if this situation occurs, indicating that LCSSA needs to be fixed.
126 const std::vector<BasicBlock *> &Blocks,
132 for (
Use &U :
I.operands()) {
146/// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
147/// and adds a mapping from the original loop to the new loop to NewLoops.
148/// Returns nullptr if no new loop was created and a pointer to the
149/// original loop OriginalBB was part of otherwise.
153 // Figure out which loop New is in.
155 assert(OldLoop &&
"Should (at least) be in the loop being unrolled!");
157 Loop *&NewLoop = NewLoops[OldLoop];
159 // Found a new sub-loop.
161 "Header should be first in RPO");
179/// The function chooses which type of unroll (epilog or prolog) is more
181/// Epilog unroll is more profitable when there is PHI that starts from
182/// constant. In this case epilog will leave PHI start from constant,
183/// but prolog will convert it to non-constant.
186/// PN = PHI [I, Latch], [CI, PreHeader]
190/// Epilog unroll case.
192/// PN = PHI [I2, Latch], [CI, PreHeader]
196/// Prolog unroll case.
197/// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
199/// PN = PHI [I2, Latch], [NewPN, PreHeader]
205 BasicBlock *PreHeader = L->getLoopPreheader();
207 assert(PreHeader && Header);
208 for (
const PHINode &PN : Header->phis()) {
225 unsigned CurrentGeneration;
226 unsigned ChildGeneration;
230 bool Processed =
false;
236 : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
237 Node(
N), ChildIter(Child), EndIter(End) {}
270 if (!MSSA->
dominates(LaterDef, EarlierMA))
284 unsigned CurrentGeneration = 0;
285 while (!NodesToProcess.
empty()) {
293 // If this block has a single predecessor, then the predecessor is the
295 // of the domtree node and all of the live out memory values are still
296 // current in this block. If this block has multiple predecessors, then
297 // they could have invalidated the live-out memory values of our parent
298 // value. For now, just be conservative and invalidate memory if this
299 // block has multiple predecessors.
305 if (!Load || !Load->isSimple()) {
306 if (
I.mayWriteToMemory())
311 const SCEV *PtrSCEV = SE.
getSCEV(Load->getPointerOperand());
316 Load->replaceAllUsesWith(M);
317 Load->eraseFromParent();
325 }
else if (NodeToProcess->
childIter() != NodeToProcess->
end()) {
326 // Push the next child onto the stack.
328 if (!L->contains(Child->
getBlock()))
334 // It has been processed, and there are no more children to process,
335 // so delete it and pop it off the stack.
341/// Perform some cleanup and simplifications on loops after unrolling. It is
342/// useful to simplify the IV's in the new loop, as well as do a quick
343/// simplify/dce pass of the instructions.
351 // Simplify any new induction variables in the partially unrolled loop.
352 if (SE && SimplifyIVs) {
356 // Aggressively clean up dead instructions that simplifyLoopIVs already
357 // identified. Any remaining should be cleaned up below.
358 while (!DeadInsts.
empty()) {
365 std::unique_ptr<MemorySSA> MSSA =
nullptr;
375 // At this point, the code is well formed. Perform constprop, instsimplify,
380 // Remove repeated debug instructions after loop unrolling.
381 if (BB->getParent()->getSubprogram())
387 Inst.replaceAllUsesWith(V);
391 // Fold ((add X, C1), C2) to (add X, C1+C2). This is very common in
392 // unrolled loops, and handling this early allows following code to
393 // identify the IV as a "simple recurrence" without first folding away
394 // a long chain of adds.
397 const APInt *C1, *C2;
403 Inst.setOperand(0,
X);
404 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
405 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
406 InnerOBO->hasNoUnsignedWrap());
407 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
408 InnerOBO->hasNoSignedWrap() &&
415 // We can't do recursive deletion until we're done iterating, as we might
416 // have a phi which (potentially indirectly) uses instructions later in
417 // the block we're iterating through.
422// Loops containing convergent instructions that are uncontrolled or controlled
423// from outside the loop must have a count that divides their TripMultiple.
429 // Check for uncontrolled convergent operations.
430 for (
auto &BB : L->blocks()) {
431 for (
auto &
I : *BB) {
435 if (CB->isConvergent())
436 return CB->getConvergenceControlToken();
442/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
443/// can only fail when the loop's latch block is not terminated by a conditional
444/// branch instruction. However, if the trip count (and multiple) are not known,
445/// loop unrolling will mostly produce more code that is no faster.
447/// If Runtime is true then UnrollLoop will try to insert a prologue or
448/// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
449/// will not runtime-unroll the loop if computing the run-time trip count will
450/// be expensive and AllowExpensiveTripCount is false.
452/// The LoopInfo Analysis that is passed will be kept consistent.
454/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
455/// DominatorTree if they are non-null.
457/// If RemainderLoop is non-null, it will receive the remainder loop (if
458/// required and not fully unrolled).
464 assert(DT &&
"DomTree is required");
466 if (!L->getLoopPreheader()) {
467 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
471 if (!L->getLoopLatch()) {
472 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
476 // Loops with indirectbr cannot be cloned.
477 if (!L->isSafeToClone()) {
478 LLVM_DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
482 if (L->getHeader()->hasAddressTaken()) {
483 // The loop-rotate pass can be helpful to avoid this in many cases.
485 dbgs() <<
" Won't unroll loop: address of header block is taken.\n");
491 // All these values should be taken only after peeling because they might have
493 BasicBlock *Preheader = L->getLoopPreheader();
497 L->getExitBlocks(ExitBlocks);
498 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
502 std::optional<unsigned> OriginalTripCount =
506 // Effectively "DCE" unrolled iterations that are beyond the max tripcount
507 // and will never be executed.
508 if (MaxTripCount && ULO.
Count > MaxTripCount)
509 ULO.
Count = MaxTripCount;
513 unsigned TripMultiple;
514 unsigned BreakoutTrip;
521 L->getExitingBlocks(ExitingBlocks);
522 for (
auto *ExitingBlock : ExitingBlocks) {
523 // The folding code is not prepared to deal with non-branch instructions
529 ExitInfo &Info = ExitInfos[ExitingBlock];
532 if (Info.TripCount != 0) {
533 Info.BreakoutTrip = Info.TripCount % ULO.
Count;
534 Info.TripMultiple = 0;
536 Info.BreakoutTrip = Info.TripMultiple =
539 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
540 Info.ExitingBlocks.push_back(ExitingBlock);
541 LLVM_DEBUG(
dbgs() <<
" Exiting block %" << ExitingBlock->getName()
542 <<
": TripCount=" << Info.TripCount
543 <<
", TripMultiple=" << Info.TripMultiple
544 <<
", BreakoutTrip=" << Info.BreakoutTrip <<
"\n");
547 // Are we eliminating the loop control altogether? Note that we can know
548 // we're eliminating the backedge without knowing exactly which iteration
549 // of the unrolled body exits.
550 const bool CompletelyUnroll = ULO.
Count == MaxTripCount;
552 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
554 // There's no point in performing runtime unrolling if this unroll count
555 // results in a full unroll.
556 if (CompletelyUnroll)
559 // Go through all exits of L and see if there are any phi-nodes there. We just
560 // conservatively assume that they're inserted to preserve LCSSA form, which
561 // means that complete unrolling might break this form. We need to either fix
562 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
563 // now we just recompute LCSSA for the outer loop, but it should be possible
564 // to fix it in-place.
565 bool NeedToFixLCSSA =
566 PreserveLCSSA && CompletelyUnroll &&
570 // The current loop unroll pass can unroll loops that have
571 // (1) single latch; and
572 // (2a) latch is unconditional; or
573 // (2b) latch is conditional and is an exiting block
574 // FIXME: The implementation can be extended to work with more complicated
575 // cases, e.g. loops with multiple latches.
578 // A conditional branch which exits the loop, which can be optimized to an
579 // unconditional branch in the unrolled loop in some cases.
580 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
581 if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
583 dbgs() <<
"Can't unroll; a conditional latch must exit the loop");
588 "Can't runtime unroll if loop contains a convergent operation.");
590 bool EpilogProfitability =
599 RemainderLoop, OriginalTripCount, OriginalLoopProb)) {
604 "generated when assuming runtime trip count\n");
610 // Report the unrolling decision.
611 if (CompletelyUnroll) {
612 LLVM_DEBUG(
dbgs() <<
"COMPLETELY UNROLLING loop %" << Header->getName()
613 <<
" with trip count " << ULO.
Count <<
"!\n");
618 <<
"completely unrolled loop with "
619 << NV(
"UnrollCount", ULO.
Count) <<
" iterations";
622 LLVM_DEBUG(
dbgs() <<
"UNROLLING loop %" << Header->getName() <<
" by "
632 Diag <<
"unrolled loop by a factor of " << NV(
"UnrollCount", ULO.
Count);
634 Diag <<
" with run-time trip count";
639 // We are going to make changes to this loop. SCEV may be keeping cached info
640 // about it, in particular about backedge taken count. The changes we make
641 // are guaranteed to invalidate this information for our loop. It is tempting
642 // to only invalidate the loop being unrolled, but it is incorrect as long as
643 // all exiting branches from all inner loops have impact on the outer loops,
644 // and if something changes inside them then any of outer loops may also
645 // change. When we forget outermost loop, we also forget all contained loops
646 // and this is what we need here.
657 ++NumUnrolledNotLatch;
659 // For the first iteration of the loop, we should use the precloned values for
660 // PHI nodes. Insert associations now.
662 std::vector<PHINode*> OrigPHINode;
667 // Collect phi nodes for reductions for which we can introduce multiple
668 // parallel reduction phis and compute the final reduction result after the
669 // loop. This requires a single exit block after unrolling. This is ensured by
670 // restricting to single-block loops where the unrolled iterations are known
673 bool CanAddAdditionalAccumulators =
677 !CompletelyUnroll && L->getNumBlocks() == 1 &&
679 (ExitInfos.
contains(Header) && ((ExitInfos[Header].TripCount != 0 &&
680 ExitInfos[Header].BreakoutTrip == 0))));
682 // Limit parallelizing reductions to unroll counts of 4 or less for now.
683 // TODO: The number of parallel reductions should depend on the number of
684 // execution units. We also don't have to add a parallel reduction phi per
685 // unrolled iteration, but could for example add a parallel phi for every 2
686 // unrolled iterations.
687 if (CanAddAdditionalAccumulators && ULO.
Count <= 4) {
688 for (
PHINode &Phi : Header->phis()) {
693 // Only handle duplicate phis for a single reduction for now.
694 // TODO: Handle any number of reductions
702 std::vector<BasicBlock *> Headers;
703 std::vector<BasicBlock *> Latches;
704 Headers.push_back(Header);
705 Latches.push_back(LatchBlock);
707 // The current on-the-fly SSA update requires blocks to be processed in
708 // reverse postorder so that LastValueMap contains the correct value at each
713 // Stash the DFS iterators before adding blocks to the loop.
717 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
719 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
720 // might break loop-simplified form for these loops (as they, e.g., would
721 // share the same exit blocks). We'll keep track of loops for which we can
722 // break this so that later we can re-simplify them.
726 // When a FSDiscriminator is enabled, we don't need to add the multiply
727 // factors to the discriminators.
728 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
732 if (!
I.isDebugOrPseudoInst())
734 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.
Count);
736 I.setDebugLoc(*NewDIL);
739 <<
"Failed to create new discriminator: "
740 << DIL->getFilename() <<
" Line: " << DIL->getLine());
743 // Identify what noalias metadata is inside the loop: if it is inside the
744 // loop, the associated metadata must be cloned for each iteration.
748 // We place the unrolled iterations immediately after the original loop
749 // latch. This is a reasonable default placement if we don't have block
750 // frequencies, and if we do, well the layout will be adjusted later.
751 auto BlockInsertPt = std::next(LatchBlock->
getIterator());
753 for (
unsigned It = 1; It != ULO.
Count; ++It) {
761 Header->getParent()->insert(BlockInsertPt, New);
764 "Header should not be in a sub-loop");
765 // Tell LI about New.
768 LoopsToSimplify.
insert(NewLoops[OldLoop]);
771 // Loop over all of the PHI nodes in the block, changing them to use
772 // the incoming values from the previous block.
773 for (
PHINode *OrigPHI : OrigPHINode) {
777 // Use cloned phis as parallel phis for partial reductions, which will
778 // get combined to the final reduction result after the loop.
780 // Collect partial reduction results.
781 if (PartialReductions.
empty())
785 // Update the start value for the cloned phis to use the identity
786 // value for the reduction.
789 L->getLoopPreheader(),
794 // Update NewPHI to use the cloned value for the iteration and move
802 if (It > 1 && L->contains(InValI))
803 InVal = LastValueMap[InValI];
804 VMap[OrigPHI] = InVal;
808 // Eliminate copies of the loop heart intrinsic, if any.
818 // Remap source location atom instance. Do this now, rather than
819 // when we remap instructions, because remap is called once we've
820 // cloned all blocks (all the clones would get the same atom
826 // Update our running map of newest clones
827 LastValueMap[*BB] = New;
830 LastValueMap[VI->first] = VI->second;
832 // Add phi entries for newly created values to all exit blocks.
834 if (L->contains(Succ))
839 if (It != LastValueMap.
end())
845 // Keep track of new headers and latches as we create them, so that
846 // we can insert the proper branches later.
848 Headers.push_back(New);
849 if (*BB == LatchBlock)
850 Latches.push_back(New);
852 // Keep track of the exiting block and its successor block contained in
853 // the loop for the current iteration.
854 auto ExitInfoIt = ExitInfos.
find(*BB);
855 if (ExitInfoIt != ExitInfos.
end())
856 ExitInfoIt->second.ExitingBlocks.push_back(New);
859 UnrolledLoopBlocks.push_back(New);
861 // Update DomTree: since we just copy the loop body, and each copy has a
862 // dedicated entry block (copy of the header block), this header's copy
863 // dominates all copied blocks. That means, dominance relations in the
864 // copied body are the same as in the original body.
868 auto BBDomNode = DT->
getNode(*BB);
869 auto BBIDom = BBDomNode->
getIDom();
870 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
876 // Remap all instructions in the most recent iteration.
877 // Key Instructions: Nothing to do - we've already remapped the atoms.
885 // Identify what other metadata depends on the cloned version. After
886 // cloning, replace the metadata with the corrected version for both
887 // memory instructions and noalias intrinsics.
888 std::string ext = (
Twine(
"It") +
Twine(It)).str();
890 Header->getContext(), ext);
894 // Loop over the PHI nodes in the original block, setting incoming values.
895 for (
PHINode *PN : OrigPHINode) {
896 if (CompletelyUnroll) {
897 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
898 PN->eraseFromParent();
899 }
else if (ULO.
Count > 1) {
903 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
904 // If this value was defined in the loop, take the value defined by the
905 // last iteration of the loop.
907 if (L->contains(InValI))
908 InVal = LastValueMap[InVal];
910 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
911 PN->addIncoming(InVal, Latches.back());
915 // Connect latches of the unrolled iterations to the headers of the next
916 // iteration. Currently they point to the header of the same iteration.
917 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
918 unsigned j = (i + 1) % e;
919 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
922 // Update dominators of blocks we might reach through exits.
923 // Immediate dominator of such block might change, because we add more
924 // routes which can lead to the exit: we can now reach it from the copied
927 for (
auto *BB : OriginalLoopBlocks) {
928 auto *BBDomNode = DT->
getNode(BB);
930 for (
auto *ChildDomNode : BBDomNode->children()) {
931 auto *ChildBB = ChildDomNode->getBlock();
932 if (!L->contains(ChildBB))
935 // The new idom of the block will be the nearest common dominator
936 // of all copies of the previous idom. This is equivalent to the
937 // nearest common dominator of the previous idom and the first latch,
938 // which dominates all copies of the previous idom.
940 for (
auto *ChildBB : ChildrenToUpdate)
946 DT->
verify(DominatorTree::VerificationLevel::Fast));
949 auto SetDest = [&](
BasicBlock *Src,
bool WillExit,
bool ExitOnTrue) {
951 const unsigned Idx = ExitOnTrue ^ WillExit;
953 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
955 // Remove predecessors from all non-Dest successors.
958 // Replace the conditional branch with an unconditional one.
960 BI->setDebugLoc(Term->getDebugLoc());
961 Term->eraseFromParent();
966 auto WillExit = [&](
const ExitInfo &Info,
unsigned i,
unsigned j,
967 bool IsLatch) -> std::optional<bool> {
968 if (CompletelyUnroll) {
969 if (PreserveOnlyFirst) {
974 // Complete (but possibly inexact) unrolling
977 if (Info.TripCount && j != Info.TripCount)
983 // If runtime unrolling inserts a prologue, information about non-latch
984 // exits may be stale.
985 if (IsLatch && j != 0)
990 if (j != Info.BreakoutTrip &&
991 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
992 // If we know the trip count or a multiple of it, we can safely use an
993 // unconditional branch for some iterations.
999 // Fold branches for iterations where we know that they will exit or not
1001 for (
auto &Pair : ExitInfos) {
1002 ExitInfo &Info = Pair.second;
1003 for (
unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
1004 // The branch destination.
1005 unsigned j = (i + 1) % e;
1006 bool IsLatch = Pair.first == LatchBlock;
1007 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
1008 if (!KnownWillExit) {
1009 if (!Info.FirstExitingBlock)
1010 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1014 // We don't fold known-exiting branches for non-latch exits here,
1015 // because this ensures that both all loop blocks and all exit blocks
1016 // remain reachable in the CFG.
1017 // TODO: We could fold these branches, but it would require much more
1018 // sophisticated updates to LoopInfo.
1019 if (*KnownWillExit && !IsLatch) {
1020 if (!Info.FirstExitingBlock)
1021 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1025 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
1031 if (ExitingBlocks.
size() == 1 && ExitInfos.
size() == 1) {
1032 // Manually update the DT if there's a single exiting node. In that case
1033 // there's a single exit node and it is sufficient to update the nodes
1034 // immediately dominated by the original exiting block. They will become
1035 // dominated by the first exiting block that leaves the loop after
1036 // unrolling. Note that the CFG inside the loop does not change, so there's
1037 // no need to update the DT inside the unrolled loop.
1039 auto &[OriginalExit, Info] = *ExitInfos.
begin();
1040 if (!Info.FirstExitingBlock)
1041 Info.FirstExitingBlock = Info.ExitingBlocks.back();
1043 if (L->contains(
C->getBlock()))
1045 C->setIDom(DT->
getNode(Info.FirstExitingBlock));
1051 // When completely unrolling, the last latch becomes unreachable.
1052 if (!LatchIsExiting && CompletelyUnroll) {
1053 // There is no need to update the DT here, because there must be a unique
1054 // latch. Hence if the latch is not exiting it must directly branch back to
1055 // the original loop header and does not dominate any nodes.
1060 // Merge adjacent basic blocks, if possible.
1064 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
1065 "Need a branch as terminator, except when fully unrolling with "
1066 "unconditional latch");
1067 if (Term && Term->isUnconditional()) {
1071 /*MSSAU=*/nullptr,
/*MemDep=*/nullptr,
1072 /*PredecessorWithTwoSuccessors=*/false,
1073 DTUToUse ?
nullptr : DT)) {
1074 // Dest has been folded into Fold. Update our worklists accordingly.
1081 // If there are partial reductions, create code in the exit block to compute
1082 // the final result and update users of the final result.
1083 if (!PartialReductions.
empty()) {
1086 "Can only introduce parallel reduction phis with single exit block");
1088 "currently only a single reduction is supported");
1089 Value *FinalRdxValue = PartialReductions.
back();
1090 Value *RdxResult =
nullptr;
1092 if (Phi.getIncomingValueForBlock(L->getLoopLatch()) != FinalRdxValue)
1095 RdxResult = PartialReductions.
front();
1099 RdxResult = Builder.CreateBinOp(
1101 RdxPart, RdxResult,
"bin.rdx");
1103 NeedToFixLCSSA =
true;
1105 RdxPart->dropPoisonGeneratingFlags();
1108 Phi.replaceAllUsesWith(RdxResult);
1113 // Apply updates to the DomTree.
1117 DT->
verify(DominatorTree::VerificationLevel::Fast));
1119 // At this point, the code is well formed. We now simplify the unrolled loop,
1120 // doing constant propagation and dead code elimination as we go.
1124 NumCompletelyUnrolled += CompletelyUnroll;
1127 Loop *OuterL = L->getParentLoop();
1128 // Update LoopInfo if the loop is completely removed.
1129 if (CompletelyUnroll) {
1131 // We shouldn't try to use `L` anymore.
1134 // Update metadata for the loop's branch weights and estimated trip count:
1135 // - If ULO.Runtime, UnrollRuntimeLoopRemainder sets the guard branch
1136 // weights, latch branch weights, and estimated trip count of the
1137 // remainder loop it creates. It also sets the branch weights for the
1138 // unrolled loop guard it creates. The branch weights for the unrolled
1139 // loop latch are adjusted below. FIXME: Handle prologue loops.
1140 // - Otherwise, if unrolled loop iteration latches become unconditional,
1141 // branch weights are adjusted above. FIXME: Actually handle such
1142 // unconditional latches.
1143 // - Otherwise, the original loop's branch weights are correct for the
1144 // unrolled loop, so do not adjust them.
1145 // - In all cases, the unrolled loop's estimated trip count is set below.
1147 // As an example of the last case, consider what happens if the unroll count
1148 // is 4 for a loop with an estimated trip count of 10 when we do not create
1149 // a remainder loop and all iterations' latches remain conditional. Each
1150 // unrolled iteration's latch still has the same probability of exiting the
1151 // loop as it did when in the original loop, and thus it should still have
1152 // the same branch weights. Each unrolled iteration's non-zero probability
1153 // of exiting already appropriately reduces the probability of reaching the
1154 // remaining iterations just as it did in the original loop. Trying to also
1155 // adjust the branch weights of the final unrolled iteration's latch (i.e.,
1156 // the backedge for the unrolled loop as a whole) to reflect its new trip
1157 // count of 3 will erroneously further reduce its block frequencies.
1158 // However, in case an analysis later needs to estimate the trip count of
1159 // the unrolled loop as a whole without considering the branch weights for
1160 // each unrolled iteration's latch within it, we store the new trip count as
1161 // separate metadata.
1163 // Where p is always the probability of executing at least 1 more
1164 // iteration, the probability for at least n more iterations is p^n.
1167 if (OriginalTripCount) {
1168 unsigned NewTripCount = *OriginalTripCount / ULO.
Count;
1175 // LoopInfo should not be valid, confirm that.
1179 // After complete unrolling most of the blocks should be contained in OuterL.
1180 // However, some of them might happen to be out of OuterL (e.g. if they
1181 // precede a loop exit). In this case we might need to insert PHI nodes in
1182 // order to preserve LCSSA form.
1183 // We don't need to check this if we already know that we need to fix LCSSA
1185 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
1186 // it should be possible to fix it in-place.
1187 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1190 // Make sure that loop-simplify form is preserved. We want to simplify
1191 // at least one layer outside of the loop that was unrolled so that any
1192 // changes to the parent loop exposed by the unrolling are considered.
1194 // OuterL includes all loops for which we can break loop-simplify, so
1195 // it's sufficient to simplify only it (it'll recursively simplify inner
1197 if (NeedToFixLCSSA) {
1198 // LCSSA must be performed on the outermost affected loop. The unrolled
1199 // loop's last loop latch is guaranteed to be in the outermost loop
1200 // after LoopInfo's been updated by LoopInfo::erase.
1202 Loop *FixLCSSALoop = OuterL;
1203 if (!FixLCSSALoop->
contains(LatchLoop))
1208 }
else if (PreserveLCSSA) {
1210 "Loops should be in LCSSA form after loop-unroll.");
1213 // TODO: That potentially might be compile-time expensive. We should try
1214 // to fix the loop-simplified form incrementally.
1215 simplifyLoop(OuterL, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1217 // Simplify loops for which we might've broken loop-simplify form.
1218 for (
Loop *SubLoop : LoopsToSimplify)
1219 simplifyLoop(SubLoop, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1226/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
1227/// node with the given name (for example, "llvm.loop.unroll.count"). If no
1228/// such metadata node exists, then nullptr is returned.
1230 // First operand should refer to the loop id itself.
1249std::optional<RecurrenceDescriptor>
1254 /*DemandedBits=*/nullptr,
1255 /*AC=*/nullptr,
/*DT=*/nullptr, SE))
1256 return std::nullopt;
1258 // Skip unsupported reductions.
1259 // TODO: Handle additional reductions, including FP and min-max
1265 return std::nullopt;
1268 return std::nullopt;
1270 // Don't unroll reductions with constant ops; those can be folded to a
1271 // single induction update.
1275 return std::nullopt;
1282 return std::nullopt;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Optimize for code generation
#define LLVM_ATTRIBUTE_USED
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
static bool needToInsertPhisForLCSSA(Loop *L, const std::vector< BasicBlock * > &Blocks, LoopInfo *LI)
Check if unrolling created a situation where we need to insert phi nodes to preserve LCSSA form.
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale.
void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
static cl::opt< bool > UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolled loops to be unrolled " "with epilog instead of prolog."))
static cl::opt< bool > UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden, cl::desc("Verify loopinfo after unrolling"), cl::init(false))
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(false))
static LLVM_ATTRIBUTE_USED bool canHaveUnrollRemainder(const Loop *L)
static cl::opt< bool > UnrollAddParallelReductions("unroll-add-parallel-reductions", cl::init(false), cl::Hidden, cl::desc("Allow unrolling to add parallel reduction phis."))
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
void childGeneration(unsigned generation)
unsigned currentGeneration() const
unsigned childGeneration() const
StackNode(ScopedHashTable< const SCEV *, LoadValue > &AvailableLoads, unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child, DomTreeNode::const_iterator End)
DomTreeNode::const_iterator end() const
DomTreeNode * nextChild()
DomTreeNode::const_iterator childIter() const
Class for arbitrary precision integers.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BranchProbability pow(unsigned N) const
Compute pow(Probability, N).
A parsed version of the target data layout string in and methods for querying it.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
typename SmallVector< DomTreeNodeBase *, 4 >::const_iterator const_iterator
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
static constexpr UpdateKind Delete
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An instruction for reading from memory.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Represents a single loop in the control flow graph.
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
Tracking metadata reference owned by Metadata.
LLVM_ABI StringRef getString() const
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Encapsulates MemorySSA, including all data associated with memory accesses.
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
FastMathFlags getFastMathFlags() const
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isIntegerRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI void forgetAllLoops()
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< K, V, KInfo, AllocatorTy > ScopeTy
ScopeTy - A type alias for easy access to the name of the scope for this hash table.
void insert_range(Range &&R)
bool insert(const value_type &X)
Insert a new element into the SetVector.
A SetVector that performs no allocations if smaller than a certain size.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A Use represents the edge between a Value definition and its users.
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
iterator find(const KeyT &Val)
ValueMapIteratorImpl< MapT, const Value *, false > iterator
bool erase(const KeyT &Val)
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Abstract Attribute helper functions.
@ C
The default llvm calling convention, compatible with C.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
LLVM_ABI void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, AAResults *AA=nullptr)
Perform some cleanup and simplifications on loops after unrolling.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
LLVM_ABI std::optional< RecurrenceDescriptor > canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L, ScalarEvolution *SE)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
auto dyn_cast_or_null(const Y &Val)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
LLVM_ABI cl::opt< bool > EnableFSDiscriminator
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
BranchProbability getLoopProbability(Loop *L)
Based on branch weight metadata, return either:
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
@ PartiallyUnrolled
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
@ Unmodified
The loop was not modified.
@ FullyUnrolled
The loop was fully unrolled into straight-line code.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
bool setLoopProbability(Loop *L, BranchProbability P)
Set branch weight metadata for the latch of L to indicate that, at the end of any iteration,...
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
RecurKind
These are the kinds of recurrences that we support.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
LLVM_ABI const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, bool PreserveLCSSA, unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit, Loop **ResultLoop=nullptr, std::optional< unsigned > OriginalTripCount=std::nullopt, BranchProbability OriginalLoopProb=BranchProbability::getUnknown())
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
LLVM_ABI MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
LLVM_ABI LoopUnrollResult UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const llvm::TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr, AAResults *AA=nullptr)
Unroll the given loop by Count.
LoadValue(Instruction *Inst, unsigned Generation)
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
const Instruction * Heart
bool RuntimeUnrollMultiExit
bool AllowExpensiveTripCount
bool AddAdditionalAccumulators
unsigned SCEVExpansionBudget
std::conditional_t< IsConst, const ValueT &, ValueT & > second