109467b48Spatrick //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements some loop unrolling utilities. It does not define any
1009467b48Spatrick // actual pass or policy, but provides a single function to perform loop
1109467b48Spatrick // unrolling.
1209467b48Spatrick //
1309467b48Spatrick // The process of unrolling can produce extraneous basic blocks linked with
1409467b48Spatrick // unconditional branches. This will be corrected in the future.
1509467b48Spatrick //
1609467b48Spatrick //===----------------------------------------------------------------------===//
1709467b48Spatrick
18097a140dSpatrick #include "llvm/ADT/ArrayRef.h"
19097a140dSpatrick #include "llvm/ADT/DenseMap.h"
20097a140dSpatrick #include "llvm/ADT/STLExtras.h"
21097a140dSpatrick #include "llvm/ADT/SetVector.h"
22097a140dSpatrick #include "llvm/ADT/SmallVector.h"
2309467b48Spatrick #include "llvm/ADT/Statistic.h"
24097a140dSpatrick #include "llvm/ADT/StringRef.h"
25097a140dSpatrick #include "llvm/ADT/Twine.h"
26097a140dSpatrick #include "llvm/ADT/ilist_iterator.h"
27097a140dSpatrick #include "llvm/ADT/iterator_range.h"
2809467b48Spatrick #include "llvm/Analysis/AssumptionCache.h"
29097a140dSpatrick #include "llvm/Analysis/DomTreeUpdater.h"
3009467b48Spatrick #include "llvm/Analysis/InstructionSimplify.h"
31097a140dSpatrick #include "llvm/Analysis/LoopInfo.h"
3209467b48Spatrick #include "llvm/Analysis/LoopIterator.h"
3309467b48Spatrick #include "llvm/Analysis/OptimizationRemarkEmitter.h"
3409467b48Spatrick #include "llvm/Analysis/ScalarEvolution.h"
3509467b48Spatrick #include "llvm/IR/BasicBlock.h"
36097a140dSpatrick #include "llvm/IR/CFG.h"
37097a140dSpatrick #include "llvm/IR/Constants.h"
3809467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h"
39097a140dSpatrick #include "llvm/IR/DebugLoc.h"
40097a140dSpatrick #include "llvm/IR/DiagnosticInfo.h"
4109467b48Spatrick #include "llvm/IR/Dominators.h"
42097a140dSpatrick #include "llvm/IR/Function.h"
43097a140dSpatrick #include "llvm/IR/Instruction.h"
44097a140dSpatrick #include "llvm/IR/Instructions.h"
4509467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
46097a140dSpatrick #include "llvm/IR/Metadata.h"
47097a140dSpatrick #include "llvm/IR/Module.h"
48097a140dSpatrick #include "llvm/IR/Use.h"
49097a140dSpatrick #include "llvm/IR/User.h"
50097a140dSpatrick #include "llvm/IR/ValueHandle.h"
51097a140dSpatrick #include "llvm/IR/ValueMap.h"
52097a140dSpatrick #include "llvm/Support/Casting.h"
5309467b48Spatrick #include "llvm/Support/CommandLine.h"
5409467b48Spatrick #include "llvm/Support/Debug.h"
55097a140dSpatrick #include "llvm/Support/GenericDomTree.h"
56097a140dSpatrick #include "llvm/Support/MathExtras.h"
5709467b48Spatrick #include "llvm/Support/raw_ostream.h"
5809467b48Spatrick #include "llvm/Transforms/Utils/BasicBlockUtils.h"
5909467b48Spatrick #include "llvm/Transforms/Utils/Cloning.h"
6009467b48Spatrick #include "llvm/Transforms/Utils/Local.h"
6109467b48Spatrick #include "llvm/Transforms/Utils/LoopSimplify.h"
6209467b48Spatrick #include "llvm/Transforms/Utils/LoopUtils.h"
6309467b48Spatrick #include "llvm/Transforms/Utils/SimplifyIndVar.h"
6409467b48Spatrick #include "llvm/Transforms/Utils/UnrollLoop.h"
65097a140dSpatrick #include "llvm/Transforms/Utils/ValueMapper.h"
66097a140dSpatrick #include <algorithm>
67097a140dSpatrick #include <assert.h>
68*d415bd75Srobert #include <numeric>
69097a140dSpatrick #include <type_traits>
70097a140dSpatrick #include <vector>
71097a140dSpatrick
72097a140dSpatrick namespace llvm {
73097a140dSpatrick class DataLayout;
74097a140dSpatrick class Value;
75097a140dSpatrick } // namespace llvm
76097a140dSpatrick
7709467b48Spatrick using namespace llvm;
7809467b48Spatrick
7909467b48Spatrick #define DEBUG_TYPE "loop-unroll"
8009467b48Spatrick
8109467b48Spatrick // TODO: Should these be here or in LoopUnroll?
8209467b48Spatrick STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
8309467b48Spatrick STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
84097a140dSpatrick STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
85097a140dSpatrick "latch (completely or otherwise)");
8609467b48Spatrick
8709467b48Spatrick static cl::opt<bool>
8809467b48Spatrick UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
8909467b48Spatrick cl::desc("Allow runtime unrolled loops to be unrolled "
9009467b48Spatrick "with epilog instead of prolog."));
9109467b48Spatrick
9209467b48Spatrick static cl::opt<bool>
9309467b48Spatrick UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
9409467b48Spatrick cl::desc("Verify domtree after unrolling"),
9509467b48Spatrick #ifdef EXPENSIVE_CHECKS
9609467b48Spatrick cl::init(true)
9709467b48Spatrick #else
9809467b48Spatrick cl::init(false)
9909467b48Spatrick #endif
10009467b48Spatrick );
10109467b48Spatrick
102*d415bd75Srobert static cl::opt<bool>
103*d415bd75Srobert UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
104*d415bd75Srobert cl::desc("Verify loopinfo after unrolling"),
105*d415bd75Srobert #ifdef EXPENSIVE_CHECKS
106*d415bd75Srobert cl::init(true)
107*d415bd75Srobert #else
108*d415bd75Srobert cl::init(false)
109*d415bd75Srobert #endif
110*d415bd75Srobert );
111*d415bd75Srobert
112*d415bd75Srobert
11309467b48Spatrick /// Check if unrolling created a situation where we need to insert phi nodes to
11409467b48Spatrick /// preserve LCSSA form.
11509467b48Spatrick /// \param Blocks is a vector of basic blocks representing unrolled loop.
11609467b48Spatrick /// \param L is the outer loop.
11709467b48Spatrick /// It's possible that some of the blocks are in L, and some are not. In this
11809467b48Spatrick /// case, if there is a use is outside L, and definition is inside L, we need to
11909467b48Spatrick /// insert a phi-node, otherwise LCSSA will be broken.
12009467b48Spatrick /// The function is just a helper function for llvm::UnrollLoop that returns
12109467b48Spatrick /// true if this situation occurs, indicating that LCSSA needs to be fixed.
needToInsertPhisForLCSSA(Loop * L,const std::vector<BasicBlock * > & Blocks,LoopInfo * LI)12273471bf0Spatrick static bool needToInsertPhisForLCSSA(Loop *L,
12373471bf0Spatrick const std::vector<BasicBlock *> &Blocks,
12409467b48Spatrick LoopInfo *LI) {
12509467b48Spatrick for (BasicBlock *BB : Blocks) {
12609467b48Spatrick if (LI->getLoopFor(BB) == L)
12709467b48Spatrick continue;
12809467b48Spatrick for (Instruction &I : *BB) {
12909467b48Spatrick for (Use &U : I.operands()) {
13073471bf0Spatrick if (const auto *Def = dyn_cast<Instruction>(U)) {
13109467b48Spatrick Loop *DefLoop = LI->getLoopFor(Def->getParent());
13209467b48Spatrick if (!DefLoop)
13309467b48Spatrick continue;
13409467b48Spatrick if (DefLoop->contains(L))
13509467b48Spatrick return true;
13609467b48Spatrick }
13709467b48Spatrick }
13809467b48Spatrick }
13909467b48Spatrick }
14009467b48Spatrick return false;
14109467b48Spatrick }
14209467b48Spatrick
14309467b48Spatrick /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
14409467b48Spatrick /// and adds a mapping from the original loop to the new loop to NewLoops.
14509467b48Spatrick /// Returns nullptr if no new loop was created and a pointer to the
14609467b48Spatrick /// original loop OriginalBB was part of otherwise.
addClonedBlockToLoopInfo(BasicBlock * OriginalBB,BasicBlock * ClonedBB,LoopInfo * LI,NewLoopsMap & NewLoops)14709467b48Spatrick const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
14809467b48Spatrick BasicBlock *ClonedBB, LoopInfo *LI,
14909467b48Spatrick NewLoopsMap &NewLoops) {
15009467b48Spatrick // Figure out which loop New is in.
15109467b48Spatrick const Loop *OldLoop = LI->getLoopFor(OriginalBB);
15209467b48Spatrick assert(OldLoop && "Should (at least) be in the loop being unrolled!");
15309467b48Spatrick
15409467b48Spatrick Loop *&NewLoop = NewLoops[OldLoop];
15509467b48Spatrick if (!NewLoop) {
15609467b48Spatrick // Found a new sub-loop.
15709467b48Spatrick assert(OriginalBB == OldLoop->getHeader() &&
15809467b48Spatrick "Header should be first in RPO");
15909467b48Spatrick
16009467b48Spatrick NewLoop = LI->AllocateLoop();
16109467b48Spatrick Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
16209467b48Spatrick
16309467b48Spatrick if (NewLoopParent)
16409467b48Spatrick NewLoopParent->addChildLoop(NewLoop);
16509467b48Spatrick else
16609467b48Spatrick LI->addTopLevelLoop(NewLoop);
16709467b48Spatrick
16809467b48Spatrick NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
16909467b48Spatrick return OldLoop;
17009467b48Spatrick } else {
17109467b48Spatrick NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
17209467b48Spatrick return nullptr;
17309467b48Spatrick }
17409467b48Spatrick }
17509467b48Spatrick
17609467b48Spatrick /// The function chooses which type of unroll (epilog or prolog) is more
17709467b48Spatrick /// profitabale.
17809467b48Spatrick /// Epilog unroll is more profitable when there is PHI that starts from
17909467b48Spatrick /// constant. In this case epilog will leave PHI start from constant,
18009467b48Spatrick /// but prolog will convert it to non-constant.
18109467b48Spatrick ///
18209467b48Spatrick /// loop:
18309467b48Spatrick /// PN = PHI [I, Latch], [CI, PreHeader]
18409467b48Spatrick /// I = foo(PN)
18509467b48Spatrick /// ...
18609467b48Spatrick ///
18709467b48Spatrick /// Epilog unroll case.
18809467b48Spatrick /// loop:
18909467b48Spatrick /// PN = PHI [I2, Latch], [CI, PreHeader]
19009467b48Spatrick /// I1 = foo(PN)
19109467b48Spatrick /// I2 = foo(I1)
19209467b48Spatrick /// ...
19309467b48Spatrick /// Prolog unroll case.
19409467b48Spatrick /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
19509467b48Spatrick /// loop:
19609467b48Spatrick /// PN = PHI [I2, Latch], [NewPN, PreHeader]
19709467b48Spatrick /// I1 = foo(PN)
19809467b48Spatrick /// I2 = foo(I1)
19909467b48Spatrick /// ...
20009467b48Spatrick ///
isEpilogProfitable(Loop * L)20109467b48Spatrick static bool isEpilogProfitable(Loop *L) {
20209467b48Spatrick BasicBlock *PreHeader = L->getLoopPreheader();
20309467b48Spatrick BasicBlock *Header = L->getHeader();
20409467b48Spatrick assert(PreHeader && Header);
20509467b48Spatrick for (const PHINode &PN : Header->phis()) {
20609467b48Spatrick if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
20709467b48Spatrick return true;
20809467b48Spatrick }
20909467b48Spatrick return false;
21009467b48Spatrick }
21109467b48Spatrick
21209467b48Spatrick /// Perform some cleanup and simplifications on loops after unrolling. It is
21309467b48Spatrick /// useful to simplify the IV's in the new loop, as well as do a quick
21409467b48Spatrick /// simplify/dce pass of the instructions.
simplifyLoopAfterUnroll(Loop * L,bool SimplifyIVs,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,const TargetTransformInfo * TTI)21509467b48Spatrick void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
21609467b48Spatrick ScalarEvolution *SE, DominatorTree *DT,
217097a140dSpatrick AssumptionCache *AC,
218097a140dSpatrick const TargetTransformInfo *TTI) {
21909467b48Spatrick // Simplify any new induction variables in the partially unrolled loop.
22009467b48Spatrick if (SE && SimplifyIVs) {
22109467b48Spatrick SmallVector<WeakTrackingVH, 16> DeadInsts;
222097a140dSpatrick simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
22309467b48Spatrick
22409467b48Spatrick // Aggressively clean up dead instructions that simplifyLoopIVs already
22509467b48Spatrick // identified. Any remaining should be cleaned up below.
226097a140dSpatrick while (!DeadInsts.empty()) {
227097a140dSpatrick Value *V = DeadInsts.pop_back_val();
228097a140dSpatrick if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
22909467b48Spatrick RecursivelyDeleteTriviallyDeadInstructions(Inst);
23009467b48Spatrick }
231097a140dSpatrick }
23209467b48Spatrick
23373471bf0Spatrick // At this point, the code is well formed. Perform constprop, instsimplify,
23473471bf0Spatrick // and dce.
23509467b48Spatrick const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
23673471bf0Spatrick SmallVector<WeakTrackingVH, 16> DeadInsts;
23709467b48Spatrick for (BasicBlock *BB : L->getBlocks()) {
238*d415bd75Srobert for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
239*d415bd75Srobert if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
240*d415bd75Srobert if (LI->replacementPreservesLCSSAForm(&Inst, V))
241*d415bd75Srobert Inst.replaceAllUsesWith(V);
242*d415bd75Srobert if (isInstructionTriviallyDead(&Inst))
243*d415bd75Srobert DeadInsts.emplace_back(&Inst);
24409467b48Spatrick }
24573471bf0Spatrick // We can't do recursive deletion until we're done iterating, as we might
24673471bf0Spatrick // have a phi which (potentially indirectly) uses instructions later in
24773471bf0Spatrick // the block we're iterating through.
24873471bf0Spatrick RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
24909467b48Spatrick }
25009467b48Spatrick }
25109467b48Spatrick
25209467b48Spatrick /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
25309467b48Spatrick /// can only fail when the loop's latch block is not terminated by a conditional
25409467b48Spatrick /// branch instruction. However, if the trip count (and multiple) are not known,
25509467b48Spatrick /// loop unrolling will mostly produce more code that is no faster.
25609467b48Spatrick ///
25773471bf0Spatrick /// If Runtime is true then UnrollLoop will try to insert a prologue or
25873471bf0Spatrick /// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
25973471bf0Spatrick /// will not runtime-unroll the loop if computing the run-time trip count will
26073471bf0Spatrick /// be expensive and AllowExpensiveTripCount is false.
26109467b48Spatrick ///
26209467b48Spatrick /// The LoopInfo Analysis that is passed will be kept consistent.
26309467b48Spatrick ///
26409467b48Spatrick /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
26509467b48Spatrick /// DominatorTree if they are non-null.
26609467b48Spatrick ///
26709467b48Spatrick /// If RemainderLoop is non-null, it will receive the remainder loop (if
26809467b48Spatrick /// required and not fully unrolled).
UnrollLoop(Loop * L,UnrollLoopOptions ULO,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,const TargetTransformInfo * TTI,OptimizationRemarkEmitter * ORE,bool PreserveLCSSA,Loop ** RemainderLoop)26909467b48Spatrick LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
27009467b48Spatrick ScalarEvolution *SE, DominatorTree *DT,
27109467b48Spatrick AssumptionCache *AC,
272097a140dSpatrick const TargetTransformInfo *TTI,
27309467b48Spatrick OptimizationRemarkEmitter *ORE,
27409467b48Spatrick bool PreserveLCSSA, Loop **RemainderLoop) {
27573471bf0Spatrick assert(DT && "DomTree is required");
27609467b48Spatrick
27773471bf0Spatrick if (!L->getLoopPreheader()) {
27809467b48Spatrick LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
27909467b48Spatrick return LoopUnrollResult::Unmodified;
28009467b48Spatrick }
28109467b48Spatrick
28273471bf0Spatrick if (!L->getLoopLatch()) {
28309467b48Spatrick LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
28409467b48Spatrick return LoopUnrollResult::Unmodified;
28509467b48Spatrick }
28609467b48Spatrick
28709467b48Spatrick // Loops with indirectbr cannot be cloned.
28809467b48Spatrick if (!L->isSafeToClone()) {
28909467b48Spatrick LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
29009467b48Spatrick return LoopUnrollResult::Unmodified;
29109467b48Spatrick }
29209467b48Spatrick
29373471bf0Spatrick if (L->getHeader()->hasAddressTaken()) {
29409467b48Spatrick // The loop-rotate pass can be helpful to avoid this in many cases.
29509467b48Spatrick LLVM_DEBUG(
29609467b48Spatrick dbgs() << " Won't unroll loop: address of header block is taken.\n");
29709467b48Spatrick return LoopUnrollResult::Unmodified;
29809467b48Spatrick }
29909467b48Spatrick
30009467b48Spatrick assert(ULO.Count > 0);
30109467b48Spatrick
30273471bf0Spatrick // All these values should be taken only after peeling because they might have
30373471bf0Spatrick // changed.
30473471bf0Spatrick BasicBlock *Preheader = L->getLoopPreheader();
30573471bf0Spatrick BasicBlock *Header = L->getHeader();
30673471bf0Spatrick BasicBlock *LatchBlock = L->getLoopLatch();
30709467b48Spatrick SmallVector<BasicBlock *, 4> ExitBlocks;
30809467b48Spatrick L->getExitBlocks(ExitBlocks);
30909467b48Spatrick std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
31009467b48Spatrick
31173471bf0Spatrick const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
31273471bf0Spatrick const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
31373471bf0Spatrick
31473471bf0Spatrick // Effectively "DCE" unrolled iterations that are beyond the max tripcount
31573471bf0Spatrick // and will never be executed.
31673471bf0Spatrick if (MaxTripCount && ULO.Count > MaxTripCount)
31773471bf0Spatrick ULO.Count = MaxTripCount;
31873471bf0Spatrick
31973471bf0Spatrick struct ExitInfo {
32073471bf0Spatrick unsigned TripCount;
32173471bf0Spatrick unsigned TripMultiple;
32273471bf0Spatrick unsigned BreakoutTrip;
32373471bf0Spatrick bool ExitOnTrue;
324*d415bd75Srobert BasicBlock *FirstExitingBlock = nullptr;
32573471bf0Spatrick SmallVector<BasicBlock *> ExitingBlocks;
32673471bf0Spatrick };
32773471bf0Spatrick DenseMap<BasicBlock *, ExitInfo> ExitInfos;
32873471bf0Spatrick SmallVector<BasicBlock *, 4> ExitingBlocks;
32973471bf0Spatrick L->getExitingBlocks(ExitingBlocks);
33073471bf0Spatrick for (auto *ExitingBlock : ExitingBlocks) {
33173471bf0Spatrick // The folding code is not prepared to deal with non-branch instructions
33273471bf0Spatrick // right now.
33373471bf0Spatrick auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
33473471bf0Spatrick if (!BI)
33573471bf0Spatrick continue;
33673471bf0Spatrick
33773471bf0Spatrick ExitInfo &Info = ExitInfos.try_emplace(ExitingBlock).first->second;
33873471bf0Spatrick Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
33973471bf0Spatrick Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
34073471bf0Spatrick if (Info.TripCount != 0) {
34173471bf0Spatrick Info.BreakoutTrip = Info.TripCount % ULO.Count;
34273471bf0Spatrick Info.TripMultiple = 0;
34373471bf0Spatrick } else {
34473471bf0Spatrick Info.BreakoutTrip = Info.TripMultiple =
345*d415bd75Srobert (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
34673471bf0Spatrick }
34773471bf0Spatrick Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
34873471bf0Spatrick Info.ExitingBlocks.push_back(ExitingBlock);
34973471bf0Spatrick LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
35073471bf0Spatrick << ": TripCount=" << Info.TripCount
35173471bf0Spatrick << ", TripMultiple=" << Info.TripMultiple
35273471bf0Spatrick << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
35373471bf0Spatrick }
35473471bf0Spatrick
35573471bf0Spatrick // Are we eliminating the loop control altogether? Note that we can know
35673471bf0Spatrick // we're eliminating the backedge without knowing exactly which iteration
35773471bf0Spatrick // of the unrolled body exits.
35873471bf0Spatrick const bool CompletelyUnroll = ULO.Count == MaxTripCount;
35973471bf0Spatrick
36073471bf0Spatrick const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
36173471bf0Spatrick
36273471bf0Spatrick // There's no point in performing runtime unrolling if this unroll count
36373471bf0Spatrick // results in a full unroll.
36473471bf0Spatrick if (CompletelyUnroll)
36573471bf0Spatrick ULO.Runtime = false;
36673471bf0Spatrick
36709467b48Spatrick // Go through all exits of L and see if there are any phi-nodes there. We just
36809467b48Spatrick // conservatively assume that they're inserted to preserve LCSSA form, which
36909467b48Spatrick // means that complete unrolling might break this form. We need to either fix
37009467b48Spatrick // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
37109467b48Spatrick // now we just recompute LCSSA for the outer loop, but it should be possible
37209467b48Spatrick // to fix it in-place.
37373471bf0Spatrick bool NeedToFixLCSSA =
37473471bf0Spatrick PreserveLCSSA && CompletelyUnroll &&
37573471bf0Spatrick any_of(ExitBlocks,
37673471bf0Spatrick [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
37709467b48Spatrick
37873471bf0Spatrick // The current loop unroll pass can unroll loops that have
37973471bf0Spatrick // (1) single latch; and
38073471bf0Spatrick // (2a) latch is unconditional; or
38173471bf0Spatrick // (2b) latch is conditional and is an exiting block
38273471bf0Spatrick // FIXME: The implementation can be extended to work with more complicated
38373471bf0Spatrick // cases, e.g. loops with multiple latches.
38473471bf0Spatrick BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
38509467b48Spatrick
38673471bf0Spatrick // A conditional branch which exits the loop, which can be optimized to an
38773471bf0Spatrick // unconditional branch in the unrolled loop in some cases.
38873471bf0Spatrick bool LatchIsExiting = L->isLoopExiting(LatchBlock);
38973471bf0Spatrick if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
39073471bf0Spatrick LLVM_DEBUG(
39173471bf0Spatrick dbgs() << "Can't unroll; a conditional latch must exit the loop");
39273471bf0Spatrick return LoopUnrollResult::Unmodified;
39309467b48Spatrick }
39409467b48Spatrick
39573471bf0Spatrick // Loops containing convergent instructions cannot use runtime unrolling,
39673471bf0Spatrick // as the prologue/epilogue may add additional control-dependencies to
39773471bf0Spatrick // convergent operations.
39809467b48Spatrick LLVM_DEBUG(
39909467b48Spatrick {
40009467b48Spatrick bool HasConvergent = false;
40109467b48Spatrick for (auto &BB : L->blocks())
40209467b48Spatrick for (auto &I : *BB)
403097a140dSpatrick if (auto *CB = dyn_cast<CallBase>(&I))
404097a140dSpatrick HasConvergent |= CB->isConvergent();
40573471bf0Spatrick assert((!HasConvergent || !ULO.Runtime) &&
40673471bf0Spatrick "Can't runtime unroll if loop contains a convergent operation.");
40709467b48Spatrick });
40809467b48Spatrick
40909467b48Spatrick bool EpilogProfitability =
41009467b48Spatrick UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
41109467b48Spatrick : isEpilogProfitable(L);
41209467b48Spatrick
41373471bf0Spatrick if (ULO.Runtime &&
41409467b48Spatrick !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
41509467b48Spatrick EpilogProfitability, ULO.UnrollRemainder,
416097a140dSpatrick ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
41709467b48Spatrick PreserveLCSSA, RemainderLoop)) {
41809467b48Spatrick if (ULO.Force)
41973471bf0Spatrick ULO.Runtime = false;
42009467b48Spatrick else {
42109467b48Spatrick LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
42209467b48Spatrick "generated when assuming runtime trip count\n");
42309467b48Spatrick return LoopUnrollResult::Unmodified;
42409467b48Spatrick }
42509467b48Spatrick }
42609467b48Spatrick
42709467b48Spatrick using namespace ore;
42809467b48Spatrick // Report the unrolling decision.
42909467b48Spatrick if (CompletelyUnroll) {
43009467b48Spatrick LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
43173471bf0Spatrick << " with trip count " << ULO.Count << "!\n");
43209467b48Spatrick if (ORE)
43309467b48Spatrick ORE->emit([&]() {
43409467b48Spatrick return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
43509467b48Spatrick L->getHeader())
43609467b48Spatrick << "completely unrolled loop with "
43773471bf0Spatrick << NV("UnrollCount", ULO.Count) << " iterations";
43809467b48Spatrick });
43909467b48Spatrick } else {
44009467b48Spatrick LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
44109467b48Spatrick << ULO.Count);
44273471bf0Spatrick if (ULO.Runtime)
44309467b48Spatrick LLVM_DEBUG(dbgs() << " with run-time trip count");
44409467b48Spatrick LLVM_DEBUG(dbgs() << "!\n");
44573471bf0Spatrick
44673471bf0Spatrick if (ORE)
44773471bf0Spatrick ORE->emit([&]() {
44873471bf0Spatrick OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
44973471bf0Spatrick L->getHeader());
45073471bf0Spatrick Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
45173471bf0Spatrick if (ULO.Runtime)
45273471bf0Spatrick Diag << " with run-time trip count";
45373471bf0Spatrick return Diag;
45473471bf0Spatrick });
45509467b48Spatrick }
45609467b48Spatrick
45709467b48Spatrick // We are going to make changes to this loop. SCEV may be keeping cached info
45809467b48Spatrick // about it, in particular about backedge taken count. The changes we make
45909467b48Spatrick // are guaranteed to invalidate this information for our loop. It is tempting
46009467b48Spatrick // to only invalidate the loop being unrolled, but it is incorrect as long as
46109467b48Spatrick // all exiting branches from all inner loops have impact on the outer loops,
46209467b48Spatrick // and if something changes inside them then any of outer loops may also
46309467b48Spatrick // change. When we forget outermost loop, we also forget all contained loops
46409467b48Spatrick // and this is what we need here.
46509467b48Spatrick if (SE) {
46609467b48Spatrick if (ULO.ForgetAllSCEV)
46709467b48Spatrick SE->forgetAllLoops();
468*d415bd75Srobert else {
46909467b48Spatrick SE->forgetTopmostLoop(L);
470*d415bd75Srobert SE->forgetBlockAndLoopDispositions();
471*d415bd75Srobert }
47209467b48Spatrick }
47309467b48Spatrick
474097a140dSpatrick if (!LatchIsExiting)
475097a140dSpatrick ++NumUnrolledNotLatch;
47609467b48Spatrick
47709467b48Spatrick // For the first iteration of the loop, we should use the precloned values for
47809467b48Spatrick // PHI nodes. Insert associations now.
47909467b48Spatrick ValueToValueMapTy LastValueMap;
48009467b48Spatrick std::vector<PHINode*> OrigPHINode;
48109467b48Spatrick for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
48209467b48Spatrick OrigPHINode.push_back(cast<PHINode>(I));
48309467b48Spatrick }
48409467b48Spatrick
48509467b48Spatrick std::vector<BasicBlock *> Headers;
48609467b48Spatrick std::vector<BasicBlock *> Latches;
48709467b48Spatrick Headers.push_back(Header);
48809467b48Spatrick Latches.push_back(LatchBlock);
48909467b48Spatrick
49009467b48Spatrick // The current on-the-fly SSA update requires blocks to be processed in
49109467b48Spatrick // reverse postorder so that LastValueMap contains the correct value at each
49209467b48Spatrick // exit.
49309467b48Spatrick LoopBlocksDFS DFS(L);
49409467b48Spatrick DFS.perform(LI);
49509467b48Spatrick
49609467b48Spatrick // Stash the DFS iterators before adding blocks to the loop.
49709467b48Spatrick LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
49809467b48Spatrick LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
49909467b48Spatrick
50009467b48Spatrick std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
50109467b48Spatrick
50209467b48Spatrick // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
50309467b48Spatrick // might break loop-simplified form for these loops (as they, e.g., would
50409467b48Spatrick // share the same exit blocks). We'll keep track of loops for which we can
50509467b48Spatrick // break this so that later we can re-simplify them.
50609467b48Spatrick SmallSetVector<Loop *, 4> LoopsToSimplify;
50709467b48Spatrick for (Loop *SubLoop : *L)
50809467b48Spatrick LoopsToSimplify.insert(SubLoop);
50909467b48Spatrick
51073471bf0Spatrick // When a FSDiscriminator is enabled, we don't need to add the multiply
51173471bf0Spatrick // factors to the discriminators.
512*d415bd75Srobert if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
513*d415bd75Srobert !EnableFSDiscriminator)
51409467b48Spatrick for (BasicBlock *BB : L->getBlocks())
51509467b48Spatrick for (Instruction &I : *BB)
51609467b48Spatrick if (!isa<DbgInfoIntrinsic>(&I))
51709467b48Spatrick if (const DILocation *DIL = I.getDebugLoc()) {
51809467b48Spatrick auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
51909467b48Spatrick if (NewDIL)
520*d415bd75Srobert I.setDebugLoc(*NewDIL);
52109467b48Spatrick else
52209467b48Spatrick LLVM_DEBUG(dbgs()
52309467b48Spatrick << "Failed to create new discriminator: "
52409467b48Spatrick << DIL->getFilename() << " Line: " << DIL->getLine());
52509467b48Spatrick }
52609467b48Spatrick
52773471bf0Spatrick // Identify what noalias metadata is inside the loop: if it is inside the
52873471bf0Spatrick // loop, the associated metadata must be cloned for each iteration.
52973471bf0Spatrick SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
53073471bf0Spatrick identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
53173471bf0Spatrick
532*d415bd75Srobert // We place the unrolled iterations immediately after the original loop
533*d415bd75Srobert // latch. This is a reasonable default placement if we don't have block
534*d415bd75Srobert // frequencies, and if we do, well the layout will be adjusted later.
535*d415bd75Srobert auto BlockInsertPt = std::next(LatchBlock->getIterator());
53609467b48Spatrick for (unsigned It = 1; It != ULO.Count; ++It) {
537097a140dSpatrick SmallVector<BasicBlock *, 8> NewBlocks;
53809467b48Spatrick SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
53909467b48Spatrick NewLoops[L] = L;
54009467b48Spatrick
54109467b48Spatrick for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
54209467b48Spatrick ValueToValueMapTy VMap;
54309467b48Spatrick BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
544*d415bd75Srobert Header->getParent()->insert(BlockInsertPt, New);
54509467b48Spatrick
54609467b48Spatrick assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
54709467b48Spatrick "Header should not be in a sub-loop");
54809467b48Spatrick // Tell LI about New.
54909467b48Spatrick const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
55009467b48Spatrick if (OldLoop)
55109467b48Spatrick LoopsToSimplify.insert(NewLoops[OldLoop]);
55209467b48Spatrick
55309467b48Spatrick if (*BB == Header)
55409467b48Spatrick // Loop over all of the PHI nodes in the block, changing them to use
55509467b48Spatrick // the incoming values from the previous block.
55609467b48Spatrick for (PHINode *OrigPHI : OrigPHINode) {
55709467b48Spatrick PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
55809467b48Spatrick Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
55909467b48Spatrick if (Instruction *InValI = dyn_cast<Instruction>(InVal))
56009467b48Spatrick if (It > 1 && L->contains(InValI))
56109467b48Spatrick InVal = LastValueMap[InValI];
56209467b48Spatrick VMap[OrigPHI] = InVal;
563*d415bd75Srobert NewPHI->eraseFromParent();
56409467b48Spatrick }
56509467b48Spatrick
56609467b48Spatrick // Update our running map of newest clones
56709467b48Spatrick LastValueMap[*BB] = New;
56809467b48Spatrick for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
56909467b48Spatrick VI != VE; ++VI)
57009467b48Spatrick LastValueMap[VI->first] = VI->second;
57109467b48Spatrick
57209467b48Spatrick // Add phi entries for newly created values to all exit blocks.
57309467b48Spatrick for (BasicBlock *Succ : successors(*BB)) {
57409467b48Spatrick if (L->contains(Succ))
57509467b48Spatrick continue;
57609467b48Spatrick for (PHINode &PHI : Succ->phis()) {
57709467b48Spatrick Value *Incoming = PHI.getIncomingValueForBlock(*BB);
57809467b48Spatrick ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
57909467b48Spatrick if (It != LastValueMap.end())
58009467b48Spatrick Incoming = It->second;
58109467b48Spatrick PHI.addIncoming(Incoming, New);
582*d415bd75Srobert SE->forgetValue(&PHI);
58309467b48Spatrick }
58409467b48Spatrick }
58509467b48Spatrick // Keep track of new headers and latches as we create them, so that
58609467b48Spatrick // we can insert the proper branches later.
58709467b48Spatrick if (*BB == Header)
58809467b48Spatrick Headers.push_back(New);
58909467b48Spatrick if (*BB == LatchBlock)
59009467b48Spatrick Latches.push_back(New);
59109467b48Spatrick
592097a140dSpatrick // Keep track of the exiting block and its successor block contained in
593097a140dSpatrick // the loop for the current iteration.
59473471bf0Spatrick auto ExitInfoIt = ExitInfos.find(*BB);
59573471bf0Spatrick if (ExitInfoIt != ExitInfos.end())
59673471bf0Spatrick ExitInfoIt->second.ExitingBlocks.push_back(New);
59709467b48Spatrick
59809467b48Spatrick NewBlocks.push_back(New);
59909467b48Spatrick UnrolledLoopBlocks.push_back(New);
60009467b48Spatrick
60109467b48Spatrick // Update DomTree: since we just copy the loop body, and each copy has a
60209467b48Spatrick // dedicated entry block (copy of the header block), this header's copy
60309467b48Spatrick // dominates all copied blocks. That means, dominance relations in the
60409467b48Spatrick // copied body are the same as in the original body.
60509467b48Spatrick if (*BB == Header)
60609467b48Spatrick DT->addNewBlock(New, Latches[It - 1]);
60709467b48Spatrick else {
60809467b48Spatrick auto BBDomNode = DT->getNode(*BB);
60909467b48Spatrick auto BBIDom = BBDomNode->getIDom();
61009467b48Spatrick BasicBlock *OriginalBBIDom = BBIDom->getBlock();
61109467b48Spatrick DT->addNewBlock(
61209467b48Spatrick New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
61309467b48Spatrick }
61409467b48Spatrick }
61509467b48Spatrick
61609467b48Spatrick // Remap all instructions in the most recent iteration
617097a140dSpatrick remapInstructionsInBlocks(NewBlocks, LastValueMap);
61873471bf0Spatrick for (BasicBlock *NewBlock : NewBlocks)
61973471bf0Spatrick for (Instruction &I : *NewBlock)
62073471bf0Spatrick if (auto *II = dyn_cast<AssumeInst>(&I))
62109467b48Spatrick AC->registerAssumption(II);
62273471bf0Spatrick
62373471bf0Spatrick {
62473471bf0Spatrick // Identify what other metadata depends on the cloned version. After
62573471bf0Spatrick // cloning, replace the metadata with the corrected version for both
62673471bf0Spatrick // memory instructions and noalias intrinsics.
62773471bf0Spatrick std::string ext = (Twine("It") + Twine(It)).str();
62873471bf0Spatrick cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
62973471bf0Spatrick Header->getContext(), ext);
63009467b48Spatrick }
63109467b48Spatrick }
63209467b48Spatrick
63309467b48Spatrick // Loop over the PHI nodes in the original block, setting incoming values.
63409467b48Spatrick for (PHINode *PN : OrigPHINode) {
63509467b48Spatrick if (CompletelyUnroll) {
63609467b48Spatrick PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
637*d415bd75Srobert PN->eraseFromParent();
63809467b48Spatrick } else if (ULO.Count > 1) {
63909467b48Spatrick Value *InVal = PN->removeIncomingValue(LatchBlock, false);
64009467b48Spatrick // If this value was defined in the loop, take the value defined by the
64109467b48Spatrick // last iteration of the loop.
64209467b48Spatrick if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
64309467b48Spatrick if (L->contains(InValI))
64409467b48Spatrick InVal = LastValueMap[InVal];
64509467b48Spatrick }
64609467b48Spatrick assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
64709467b48Spatrick PN->addIncoming(InVal, Latches.back());
64809467b48Spatrick }
64909467b48Spatrick }
65009467b48Spatrick
651097a140dSpatrick // Connect latches of the unrolled iterations to the headers of the next
65273471bf0Spatrick // iteration. Currently they point to the header of the same iteration.
65309467b48Spatrick for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
65409467b48Spatrick unsigned j = (i + 1) % e;
65573471bf0Spatrick Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
65609467b48Spatrick }
65709467b48Spatrick
65809467b48Spatrick // Update dominators of blocks we might reach through exits.
65909467b48Spatrick // Immediate dominator of such block might change, because we add more
66009467b48Spatrick // routes which can lead to the exit: we can now reach it from the copied
66109467b48Spatrick // iterations too.
66273471bf0Spatrick if (ULO.Count > 1) {
66309467b48Spatrick for (auto *BB : OriginalLoopBlocks) {
66409467b48Spatrick auto *BBDomNode = DT->getNode(BB);
66509467b48Spatrick SmallVector<BasicBlock *, 16> ChildrenToUpdate;
666097a140dSpatrick for (auto *ChildDomNode : BBDomNode->children()) {
66709467b48Spatrick auto *ChildBB = ChildDomNode->getBlock();
66809467b48Spatrick if (!L->contains(ChildBB))
66909467b48Spatrick ChildrenToUpdate.push_back(ChildBB);
67009467b48Spatrick }
67109467b48Spatrick // The new idom of the block will be the nearest common dominator
67209467b48Spatrick // of all copies of the previous idom. This is equivalent to the
67309467b48Spatrick // nearest common dominator of the previous idom and the first latch,
67409467b48Spatrick // which dominates all copies of the previous idom.
67573471bf0Spatrick BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
67609467b48Spatrick for (auto *ChildBB : ChildrenToUpdate)
67709467b48Spatrick DT->changeImmediateDominator(ChildBB, NewIDom);
67809467b48Spatrick }
67909467b48Spatrick }
68009467b48Spatrick
68173471bf0Spatrick assert(!UnrollVerifyDomtree ||
68209467b48Spatrick DT->verify(DominatorTree::VerificationLevel::Fast));
68309467b48Spatrick
684*d415bd75Srobert SmallVector<DominatorTree::UpdateType> DTUpdates;
68573471bf0Spatrick auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
68673471bf0Spatrick auto *Term = cast<BranchInst>(Src->getTerminator());
68773471bf0Spatrick const unsigned Idx = ExitOnTrue ^ WillExit;
68873471bf0Spatrick BasicBlock *Dest = Term->getSuccessor(Idx);
68973471bf0Spatrick BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
69073471bf0Spatrick
69173471bf0Spatrick // Remove predecessors from all non-Dest successors.
69273471bf0Spatrick DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
69373471bf0Spatrick
69473471bf0Spatrick // Replace the conditional branch with an unconditional one.
69573471bf0Spatrick BranchInst::Create(Dest, Term);
69673471bf0Spatrick Term->eraseFromParent();
69773471bf0Spatrick
698*d415bd75Srobert DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
69973471bf0Spatrick };
70073471bf0Spatrick
70173471bf0Spatrick auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
702*d415bd75Srobert bool IsLatch) -> std::optional<bool> {
70373471bf0Spatrick if (CompletelyUnroll) {
70473471bf0Spatrick if (PreserveOnlyFirst) {
70573471bf0Spatrick if (i == 0)
706*d415bd75Srobert return std::nullopt;
70773471bf0Spatrick return j == 0;
70873471bf0Spatrick }
70973471bf0Spatrick // Complete (but possibly inexact) unrolling
71073471bf0Spatrick if (j == 0)
71173471bf0Spatrick return true;
71273471bf0Spatrick if (Info.TripCount && j != Info.TripCount)
71373471bf0Spatrick return false;
714*d415bd75Srobert return std::nullopt;
71573471bf0Spatrick }
71673471bf0Spatrick
71773471bf0Spatrick if (ULO.Runtime) {
71873471bf0Spatrick // If runtime unrolling inserts a prologue, information about non-latch
71973471bf0Spatrick // exits may be stale.
72073471bf0Spatrick if (IsLatch && j != 0)
72173471bf0Spatrick return false;
722*d415bd75Srobert return std::nullopt;
72373471bf0Spatrick }
72473471bf0Spatrick
72573471bf0Spatrick if (j != Info.BreakoutTrip &&
72673471bf0Spatrick (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
72773471bf0Spatrick // If we know the trip count or a multiple of it, we can safely use an
72873471bf0Spatrick // unconditional branch for some iterations.
72973471bf0Spatrick return false;
73073471bf0Spatrick }
731*d415bd75Srobert return std::nullopt;
73273471bf0Spatrick };
73373471bf0Spatrick
73473471bf0Spatrick // Fold branches for iterations where we know that they will exit or not
73573471bf0Spatrick // exit.
736*d415bd75Srobert for (auto &Pair : ExitInfos) {
737*d415bd75Srobert ExitInfo &Info = Pair.second;
73873471bf0Spatrick for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
73973471bf0Spatrick // The branch destination.
74073471bf0Spatrick unsigned j = (i + 1) % e;
74173471bf0Spatrick bool IsLatch = Pair.first == LatchBlock;
742*d415bd75Srobert std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
743*d415bd75Srobert if (!KnownWillExit) {
744*d415bd75Srobert if (!Info.FirstExitingBlock)
745*d415bd75Srobert Info.FirstExitingBlock = Info.ExitingBlocks[i];
74673471bf0Spatrick continue;
747*d415bd75Srobert }
74873471bf0Spatrick
74973471bf0Spatrick // We don't fold known-exiting branches for non-latch exits here,
75073471bf0Spatrick // because this ensures that both all loop blocks and all exit blocks
75173471bf0Spatrick // remain reachable in the CFG.
75273471bf0Spatrick // TODO: We could fold these branches, but it would require much more
75373471bf0Spatrick // sophisticated updates to LoopInfo.
754*d415bd75Srobert if (*KnownWillExit && !IsLatch) {
755*d415bd75Srobert if (!Info.FirstExitingBlock)
756*d415bd75Srobert Info.FirstExitingBlock = Info.ExitingBlocks[i];
75773471bf0Spatrick continue;
758*d415bd75Srobert }
75973471bf0Spatrick
76073471bf0Spatrick SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
76173471bf0Spatrick }
76273471bf0Spatrick }
76373471bf0Spatrick
764*d415bd75Srobert DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
765*d415bd75Srobert DomTreeUpdater *DTUToUse = &DTU;
766*d415bd75Srobert if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
767*d415bd75Srobert // Manually update the DT if there's a single exiting node. In that case
768*d415bd75Srobert // there's a single exit node and it is sufficient to update the nodes
769*d415bd75Srobert // immediately dominated by the original exiting block. They will become
770*d415bd75Srobert // dominated by the first exiting block that leaves the loop after
771*d415bd75Srobert // unrolling. Note that the CFG inside the loop does not change, so there's
772*d415bd75Srobert // no need to update the DT inside the unrolled loop.
773*d415bd75Srobert DTUToUse = nullptr;
774*d415bd75Srobert auto &[OriginalExit, Info] = *ExitInfos.begin();
775*d415bd75Srobert if (!Info.FirstExitingBlock)
776*d415bd75Srobert Info.FirstExitingBlock = Info.ExitingBlocks.back();
777*d415bd75Srobert for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
778*d415bd75Srobert if (L->contains(C->getBlock()))
779*d415bd75Srobert continue;
780*d415bd75Srobert C->setIDom(DT->getNode(Info.FirstExitingBlock));
781*d415bd75Srobert }
782*d415bd75Srobert } else {
783*d415bd75Srobert DTU.applyUpdates(DTUpdates);
784*d415bd75Srobert }
785*d415bd75Srobert
78673471bf0Spatrick // When completely unrolling, the last latch becomes unreachable.
787*d415bd75Srobert if (!LatchIsExiting && CompletelyUnroll) {
788*d415bd75Srobert // There is no need to update the DT here, because there must be a unique
789*d415bd75Srobert // latch. Hence if the latch is not exiting it must directly branch back to
790*d415bd75Srobert // the original loop header and does not dominate any nodes.
791*d415bd75Srobert assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
792*d415bd75Srobert changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
793*d415bd75Srobert }
79473471bf0Spatrick
79509467b48Spatrick // Merge adjacent basic blocks, if possible.
79609467b48Spatrick for (BasicBlock *Latch : Latches) {
79709467b48Spatrick BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
79809467b48Spatrick assert((Term ||
79909467b48Spatrick (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
80009467b48Spatrick "Need a branch as terminator, except when fully unrolling with "
80109467b48Spatrick "unconditional latch");
80209467b48Spatrick if (Term && Term->isUnconditional()) {
80309467b48Spatrick BasicBlock *Dest = Term->getSuccessor(0);
80409467b48Spatrick BasicBlock *Fold = Dest->getUniquePredecessor();
805*d415bd75Srobert if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
806*d415bd75Srobert /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
807*d415bd75Srobert /*PredecessorWithTwoSuccessors=*/false,
808*d415bd75Srobert DTUToUse ? nullptr : DT)) {
80909467b48Spatrick // Dest has been folded into Fold. Update our worklists accordingly.
81009467b48Spatrick std::replace(Latches.begin(), Latches.end(), Dest, Fold);
81173471bf0Spatrick llvm::erase_value(UnrolledLoopBlocks, Dest);
81209467b48Spatrick }
81309467b48Spatrick }
81409467b48Spatrick }
815*d415bd75Srobert
816*d415bd75Srobert if (DTUToUse) {
81709467b48Spatrick // Apply updates to the DomTree.
81809467b48Spatrick DT = &DTU.getDomTree();
819*d415bd75Srobert }
820*d415bd75Srobert assert(!UnrollVerifyDomtree ||
821*d415bd75Srobert DT->verify(DominatorTree::VerificationLevel::Fast));
82209467b48Spatrick
82309467b48Spatrick // At this point, the code is well formed. We now simplify the unrolled loop,
82409467b48Spatrick // doing constant propagation and dead code elimination as we go.
82573471bf0Spatrick simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
82673471bf0Spatrick TTI);
82709467b48Spatrick
82809467b48Spatrick NumCompletelyUnrolled += CompletelyUnroll;
82909467b48Spatrick ++NumUnrolled;
83009467b48Spatrick
83109467b48Spatrick Loop *OuterL = L->getParentLoop();
83209467b48Spatrick // Update LoopInfo if the loop is completely removed.
83309467b48Spatrick if (CompletelyUnroll)
83409467b48Spatrick LI->erase(L);
83509467b48Spatrick
836*d415bd75Srobert // LoopInfo should not be valid, confirm that.
837*d415bd75Srobert if (UnrollVerifyLoopInfo)
838*d415bd75Srobert LI->verify(*DT);
839*d415bd75Srobert
84009467b48Spatrick // After complete unrolling most of the blocks should be contained in OuterL.
84109467b48Spatrick // However, some of them might happen to be out of OuterL (e.g. if they
84209467b48Spatrick // precede a loop exit). In this case we might need to insert PHI nodes in
84309467b48Spatrick // order to preserve LCSSA form.
84409467b48Spatrick // We don't need to check this if we already know that we need to fix LCSSA
84509467b48Spatrick // form.
84609467b48Spatrick // TODO: For now we just recompute LCSSA for the outer loop in this case, but
84709467b48Spatrick // it should be possible to fix it in-place.
84809467b48Spatrick if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
84909467b48Spatrick NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
85009467b48Spatrick
85173471bf0Spatrick // Make sure that loop-simplify form is preserved. We want to simplify
85209467b48Spatrick // at least one layer outside of the loop that was unrolled so that any
85309467b48Spatrick // changes to the parent loop exposed by the unrolling are considered.
85409467b48Spatrick if (OuterL) {
85509467b48Spatrick // OuterL includes all loops for which we can break loop-simplify, so
85609467b48Spatrick // it's sufficient to simplify only it (it'll recursively simplify inner
85709467b48Spatrick // loops too).
85809467b48Spatrick if (NeedToFixLCSSA) {
85909467b48Spatrick // LCSSA must be performed on the outermost affected loop. The unrolled
86009467b48Spatrick // loop's last loop latch is guaranteed to be in the outermost loop
86109467b48Spatrick // after LoopInfo's been updated by LoopInfo::erase.
86209467b48Spatrick Loop *LatchLoop = LI->getLoopFor(Latches.back());
86309467b48Spatrick Loop *FixLCSSALoop = OuterL;
86409467b48Spatrick if (!FixLCSSALoop->contains(LatchLoop))
86509467b48Spatrick while (FixLCSSALoop->getParentLoop() != LatchLoop)
86609467b48Spatrick FixLCSSALoop = FixLCSSALoop->getParentLoop();
86709467b48Spatrick
86809467b48Spatrick formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
86909467b48Spatrick } else if (PreserveLCSSA) {
87009467b48Spatrick assert(OuterL->isLCSSAForm(*DT) &&
87109467b48Spatrick "Loops should be in LCSSA form after loop-unroll.");
87209467b48Spatrick }
87309467b48Spatrick
87409467b48Spatrick // TODO: That potentially might be compile-time expensive. We should try
87509467b48Spatrick // to fix the loop-simplified form incrementally.
87609467b48Spatrick simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
87709467b48Spatrick } else {
87809467b48Spatrick // Simplify loops for which we might've broken loop-simplify form.
87909467b48Spatrick for (Loop *SubLoop : LoopsToSimplify)
88009467b48Spatrick simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
88109467b48Spatrick }
88209467b48Spatrick
88309467b48Spatrick return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
88409467b48Spatrick : LoopUnrollResult::PartiallyUnrolled;
88509467b48Spatrick }
88609467b48Spatrick
88709467b48Spatrick /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
88809467b48Spatrick /// node with the given name (for example, "llvm.loop.unroll.count"). If no
88909467b48Spatrick /// such metadata node exists, then nullptr is returned.
GetUnrollMetadata(MDNode * LoopID,StringRef Name)89009467b48Spatrick MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
89109467b48Spatrick // First operand should refer to the loop id itself.
89209467b48Spatrick assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
89309467b48Spatrick assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
89409467b48Spatrick
89509467b48Spatrick for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
89609467b48Spatrick MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
89709467b48Spatrick if (!MD)
89809467b48Spatrick continue;
89909467b48Spatrick
90009467b48Spatrick MDString *S = dyn_cast<MDString>(MD->getOperand(0));
90109467b48Spatrick if (!S)
90209467b48Spatrick continue;
90309467b48Spatrick
90409467b48Spatrick if (Name.equals(S->getString()))
90509467b48Spatrick return MD;
90609467b48Spatrick }
90709467b48Spatrick return nullptr;
90809467b48Spatrick }
909