1dff0c46cSDimitry Andric //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2dff0c46cSDimitry Andric //
3dff0c46cSDimitry Andric //                     The LLVM Compiler Infrastructure
4dff0c46cSDimitry Andric //
5dff0c46cSDimitry Andric // This file is distributed under the University of Illinois Open Source
6dff0c46cSDimitry Andric // License. See LICENSE.TXT for details.
7dff0c46cSDimitry Andric //
8dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
9dff0c46cSDimitry Andric //
10dff0c46cSDimitry Andric // This file implements some loop unrolling utilities for loops with run-time
11dff0c46cSDimitry Andric // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
12dff0c46cSDimitry Andric // trip counts.
13dff0c46cSDimitry Andric //
14dff0c46cSDimitry Andric // The functions in this file are used to generate extra code when the
15dff0c46cSDimitry Andric // run-time trip count modulo the unroll factor is not 0.  When this is the
16dff0c46cSDimitry Andric // case, we need to generate code to execute these 'left over' iterations.
17dff0c46cSDimitry Andric //
18dff0c46cSDimitry Andric // The current strategy generates an if-then-else sequence prior to the
193ca95b02SDimitry Andric // unrolled loop to execute the 'left over' iterations before or after the
203ca95b02SDimitry Andric // unrolled loop.
21dff0c46cSDimitry Andric //
22dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
23dff0c46cSDimitry Andric 
244ba319b5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
25dff0c46cSDimitry Andric #include "llvm/ADT/Statistic.h"
26ff0cc061SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
27dff0c46cSDimitry Andric #include "llvm/Analysis/LoopIterator.h"
28dff0c46cSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
29dff0c46cSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpander.h"
30139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
31ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
3239d628a0SDimitry Andric #include "llvm/IR/Metadata.h"
33ff0cc061SDimitry Andric #include "llvm/IR/Module.h"
34dff0c46cSDimitry Andric #include "llvm/Support/Debug.h"
35dff0c46cSDimitry Andric #include "llvm/Support/raw_ostream.h"
364ba319b5SDimitry Andric #include "llvm/Transforms/Utils.h"
37dff0c46cSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38dff0c46cSDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
39a580b014SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
40db17bf38SDimitry Andric #include "llvm/Transforms/Utils/UnrollLoop.h"
41dff0c46cSDimitry Andric #include <algorithm>
42dff0c46cSDimitry Andric 
43dff0c46cSDimitry Andric using namespace llvm;
44dff0c46cSDimitry Andric 
4591bc56edSDimitry Andric #define DEBUG_TYPE "loop-unroll"
4691bc56edSDimitry Andric 
47dff0c46cSDimitry Andric STATISTIC(NumRuntimeUnrolled,
48dff0c46cSDimitry Andric           "Number of loops unrolled with run-time trip counts");
49a580b014SDimitry Andric static cl::opt<bool> UnrollRuntimeMultiExit(
50a580b014SDimitry Andric     "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
51a580b014SDimitry Andric     cl::desc("Allow runtime unrolling for loops with multiple exits, when "
52a580b014SDimitry Andric              "epilog is generated"));
53dff0c46cSDimitry Andric 
54dff0c46cSDimitry Andric /// Connect the unrolling prolog code to the original loop.
55dff0c46cSDimitry Andric /// The unrolling prolog code contains code to execute the
56dff0c46cSDimitry Andric /// 'extra' iterations if the run-time trip count modulo the
57dff0c46cSDimitry Andric /// unroll count is non-zero.
58dff0c46cSDimitry Andric ///
59dff0c46cSDimitry Andric /// This function performs the following:
60dff0c46cSDimitry Andric /// - Create PHI nodes at prolog end block to combine values
61dff0c46cSDimitry Andric ///   that exit the prolog code and jump around the prolog.
62dff0c46cSDimitry Andric /// - Add a PHI operand to a PHI node at the loop exit block
63dff0c46cSDimitry Andric ///   for values that exit the prolog and go around the loop.
64dff0c46cSDimitry Andric /// - Branch around the original loop if the trip count is less
65dff0c46cSDimitry Andric ///   than the unroll factor.
66dff0c46cSDimitry Andric ///
ConnectProlog(Loop * L,Value * BECount,unsigned Count,BasicBlock * PrologExit,BasicBlock * OriginalLoopLatchExit,BasicBlock * PreHeader,BasicBlock * NewPreHeader,ValueToValueMapTy & VMap,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA)67b09980d1SDimitry Andric static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
68c4394386SDimitry Andric                           BasicBlock *PrologExit,
69c4394386SDimitry Andric                           BasicBlock *OriginalLoopLatchExit,
70c4394386SDimitry Andric                           BasicBlock *PreHeader, BasicBlock *NewPreHeader,
71c4394386SDimitry Andric                           ValueToValueMapTy &VMap, DominatorTree *DT,
72c4394386SDimitry Andric                           LoopInfo *LI, bool PreserveLCSSA) {
73*b5893f02SDimitry Andric   // Loop structure should be the following:
74*b5893f02SDimitry Andric   // Preheader
75*b5893f02SDimitry Andric   //  PrologHeader
76*b5893f02SDimitry Andric   //  ...
77*b5893f02SDimitry Andric   //  PrologLatch
78*b5893f02SDimitry Andric   //  PrologExit
79*b5893f02SDimitry Andric   //   NewPreheader
80*b5893f02SDimitry Andric   //    Header
81*b5893f02SDimitry Andric   //    ...
82*b5893f02SDimitry Andric   //    Latch
83*b5893f02SDimitry Andric   //      LatchExit
84dff0c46cSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
8591bc56edSDimitry Andric   assert(Latch && "Loop must have a latch");
863ca95b02SDimitry Andric   BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
87dff0c46cSDimitry Andric 
88dff0c46cSDimitry Andric   // Create a PHI node for each outgoing value from the original loop
89dff0c46cSDimitry Andric   // (which means it is an outgoing value from the prolog code too).
90dff0c46cSDimitry Andric   // The new PHI node is inserted in the prolog end basic block.
913ca95b02SDimitry Andric   // The new PHI node value is added as an operand of a PHI node in either
92dff0c46cSDimitry Andric   // the loop header or the loop exit block.
933ca95b02SDimitry Andric   for (BasicBlock *Succ : successors(Latch)) {
9430785c0eSDimitry Andric     for (PHINode &PN : Succ->phis()) {
95dff0c46cSDimitry Andric       // Add a new PHI node to the prolog end block and add the
96dff0c46cSDimitry Andric       // appropriate incoming values.
97*b5893f02SDimitry Andric       // TODO: This code assumes that the PrologExit (or the LatchExit block for
98*b5893f02SDimitry Andric       // prolog loop) contains only one predecessor from the loop, i.e. the
99*b5893f02SDimitry Andric       // PrologLatch. When supporting multiple-exiting block loops, we can have
100*b5893f02SDimitry Andric       // two or more blocks that have the LatchExit as the target in the
101*b5893f02SDimitry Andric       // original loop.
10230785c0eSDimitry Andric       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
1033ca95b02SDimitry Andric                                        PrologExit->getFirstNonPHI());
104dff0c46cSDimitry Andric       // Adding a value to the new PHI node from the original loop preheader.
105dff0c46cSDimitry Andric       // This is the value that skips all the prolog code.
10630785c0eSDimitry Andric       if (L->contains(&PN)) {
107*b5893f02SDimitry Andric         // Succ is loop header.
10830785c0eSDimitry Andric         NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
1093ca95b02SDimitry Andric                            PreHeader);
110dff0c46cSDimitry Andric       } else {
111*b5893f02SDimitry Andric         // Succ is LatchExit.
11230785c0eSDimitry Andric         NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
113dff0c46cSDimitry Andric       }
114dff0c46cSDimitry Andric 
11530785c0eSDimitry Andric       Value *V = PN.getIncomingValueForBlock(Latch);
116dff0c46cSDimitry Andric       if (Instruction *I = dyn_cast<Instruction>(V)) {
117dff0c46cSDimitry Andric         if (L->contains(I)) {
1183ca95b02SDimitry Andric           V = VMap.lookup(I);
119dff0c46cSDimitry Andric         }
120dff0c46cSDimitry Andric       }
121dff0c46cSDimitry Andric       // Adding a value to the new PHI node from the last prolog block
122dff0c46cSDimitry Andric       // that was created.
1233ca95b02SDimitry Andric       NewPN->addIncoming(V, PrologLatch);
124dff0c46cSDimitry Andric 
125dff0c46cSDimitry Andric       // Update the existing PHI node operand with the value from the
126dff0c46cSDimitry Andric       // new PHI node.  How this is done depends on if the existing
127dff0c46cSDimitry Andric       // PHI node is in the original loop block, or the exit block.
12830785c0eSDimitry Andric       if (L->contains(&PN)) {
12930785c0eSDimitry Andric         PN.setIncomingValue(PN.getBasicBlockIndex(NewPreHeader), NewPN);
130dff0c46cSDimitry Andric       } else {
13130785c0eSDimitry Andric         PN.addIncoming(NewPN, PrologExit);
132dff0c46cSDimitry Andric       }
133dff0c46cSDimitry Andric     }
134dff0c46cSDimitry Andric   }
135dff0c46cSDimitry Andric 
136d88c1a5aSDimitry Andric   // Make sure that created prolog loop is in simplified form
137d88c1a5aSDimitry Andric   SmallVector<BasicBlock *, 4> PrologExitPreds;
138d88c1a5aSDimitry Andric   Loop *PrologLoop = LI->getLoopFor(PrologLatch);
139d88c1a5aSDimitry Andric   if (PrologLoop) {
140d88c1a5aSDimitry Andric     for (BasicBlock *PredBB : predecessors(PrologExit))
141d88c1a5aSDimitry Andric       if (PrologLoop->contains(PredBB))
142d88c1a5aSDimitry Andric         PrologExitPreds.push_back(PredBB);
143d88c1a5aSDimitry Andric 
144d88c1a5aSDimitry Andric     SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
145*b5893f02SDimitry Andric                            nullptr, PreserveLCSSA);
146d88c1a5aSDimitry Andric   }
147d88c1a5aSDimitry Andric 
1483ca95b02SDimitry Andric   // Create a branch around the original loop, which is taken if there are no
149b09980d1SDimitry Andric   // iterations remaining to be executed after running the prologue.
1503ca95b02SDimitry Andric   Instruction *InsertPt = PrologExit->getTerminator();
1518f0fd8f6SDimitry Andric   IRBuilder<> B(InsertPt);
152b09980d1SDimitry Andric 
153b09980d1SDimitry Andric   assert(Count != 0 && "nonsensical Count!");
154b09980d1SDimitry Andric 
1553ca95b02SDimitry Andric   // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
1563ca95b02SDimitry Andric   // This means %xtraiter is (BECount + 1) and all of the iterations of this
1573ca95b02SDimitry Andric   // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
1583ca95b02SDimitry Andric   // then (BECount + 1) cannot unsigned-overflow.
1598f0fd8f6SDimitry Andric   Value *BrLoopExit =
1608f0fd8f6SDimitry Andric       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
161dff0c46cSDimitry Andric   // Split the exit to maintain loop canonicalization guarantees
162c4394386SDimitry Andric   SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
163c4394386SDimitry Andric   SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
164*b5893f02SDimitry Andric                          nullptr, PreserveLCSSA);
165dff0c46cSDimitry Andric   // Add the branch to the exit block (around the unrolled loop)
166c4394386SDimitry Andric   B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
1673ca95b02SDimitry Andric   InsertPt->eraseFromParent();
1687a7e6055SDimitry Andric   if (DT)
169c4394386SDimitry Andric     DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
1703ca95b02SDimitry Andric }
1713ca95b02SDimitry Andric 
1723ca95b02SDimitry Andric /// Connect the unrolling epilog code to the original loop.
1733ca95b02SDimitry Andric /// The unrolling epilog code contains code to execute the
1743ca95b02SDimitry Andric /// 'extra' iterations if the run-time trip count modulo the
1753ca95b02SDimitry Andric /// unroll count is non-zero.
1763ca95b02SDimitry Andric ///
1773ca95b02SDimitry Andric /// This function performs the following:
1783ca95b02SDimitry Andric /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
1793ca95b02SDimitry Andric /// - Create PHI nodes at the unrolling loop exit to combine
1803ca95b02SDimitry Andric ///   values that exit the unrolling loop code and jump around it.
1813ca95b02SDimitry Andric /// - Update PHI operands in the epilog loop by the new PHI nodes
1823ca95b02SDimitry Andric /// - Branch around the epilog loop if extra iters (ModVal) is zero.
1833ca95b02SDimitry Andric ///
ConnectEpilog(Loop * L,Value * ModVal,BasicBlock * NewExit,BasicBlock * Exit,BasicBlock * PreHeader,BasicBlock * EpilogPreHeader,BasicBlock * NewPreHeader,ValueToValueMapTy & VMap,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA)1843ca95b02SDimitry Andric static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
1853ca95b02SDimitry Andric                           BasicBlock *Exit, BasicBlock *PreHeader,
1863ca95b02SDimitry Andric                           BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
1873ca95b02SDimitry Andric                           ValueToValueMapTy &VMap, DominatorTree *DT,
1883ca95b02SDimitry Andric                           LoopInfo *LI, bool PreserveLCSSA)  {
1893ca95b02SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
1903ca95b02SDimitry Andric   assert(Latch && "Loop must have a latch");
1913ca95b02SDimitry Andric   BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
1923ca95b02SDimitry Andric 
1933ca95b02SDimitry Andric   // Loop structure should be the following:
1943ca95b02SDimitry Andric   //
1953ca95b02SDimitry Andric   // PreHeader
1963ca95b02SDimitry Andric   // NewPreHeader
1973ca95b02SDimitry Andric   //   Header
1983ca95b02SDimitry Andric   //   ...
1993ca95b02SDimitry Andric   //   Latch
2003ca95b02SDimitry Andric   // NewExit (PN)
2013ca95b02SDimitry Andric   // EpilogPreHeader
2023ca95b02SDimitry Andric   //   EpilogHeader
2033ca95b02SDimitry Andric   //   ...
2043ca95b02SDimitry Andric   //   EpilogLatch
2053ca95b02SDimitry Andric   // Exit (EpilogPN)
2063ca95b02SDimitry Andric 
2073ca95b02SDimitry Andric   // Update PHI nodes at NewExit and Exit.
20830785c0eSDimitry Andric   for (PHINode &PN : NewExit->phis()) {
2093ca95b02SDimitry Andric     // PN should be used in another PHI located in Exit block as
2103ca95b02SDimitry Andric     // Exit was split by SplitBlockPredecessors into Exit and NewExit
2113ca95b02SDimitry Andric     // Basicaly it should look like:
2123ca95b02SDimitry Andric     // NewExit:
2133ca95b02SDimitry Andric     //   PN = PHI [I, Latch]
2143ca95b02SDimitry Andric     // ...
2153ca95b02SDimitry Andric     // Exit:
2163ca95b02SDimitry Andric     //   EpilogPN = PHI [PN, EpilogPreHeader]
2173ca95b02SDimitry Andric     //
2183ca95b02SDimitry Andric     // There is EpilogPreHeader incoming block instead of NewExit as
2193ca95b02SDimitry Andric     // NewExit was spilt 1 more time to get EpilogPreHeader.
22030785c0eSDimitry Andric     assert(PN.hasOneUse() && "The phi should have 1 use");
22130785c0eSDimitry Andric     PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
2223ca95b02SDimitry Andric     assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
2233ca95b02SDimitry Andric 
2243ca95b02SDimitry Andric     // Add incoming PreHeader from branch around the Loop
22530785c0eSDimitry Andric     PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
2263ca95b02SDimitry Andric 
22730785c0eSDimitry Andric     Value *V = PN.getIncomingValueForBlock(Latch);
2283ca95b02SDimitry Andric     Instruction *I = dyn_cast<Instruction>(V);
2293ca95b02SDimitry Andric     if (I && L->contains(I))
2303ca95b02SDimitry Andric       // If value comes from an instruction in the loop add VMap value.
2313ca95b02SDimitry Andric       V = VMap.lookup(I);
2323ca95b02SDimitry Andric     // For the instruction out of the loop, constant or undefined value
2333ca95b02SDimitry Andric     // insert value itself.
2343ca95b02SDimitry Andric     EpilogPN->addIncoming(V, EpilogLatch);
2353ca95b02SDimitry Andric 
2363ca95b02SDimitry Andric     assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
2373ca95b02SDimitry Andric           "EpilogPN should have EpilogPreHeader incoming block");
2383ca95b02SDimitry Andric     // Change EpilogPreHeader incoming block to NewExit.
2393ca95b02SDimitry Andric     EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
2403ca95b02SDimitry Andric                                NewExit);
2413ca95b02SDimitry Andric     // Now PHIs should look like:
2423ca95b02SDimitry Andric     // NewExit:
2433ca95b02SDimitry Andric     //   PN = PHI [I, Latch], [undef, PreHeader]
2443ca95b02SDimitry Andric     // ...
2453ca95b02SDimitry Andric     // Exit:
2463ca95b02SDimitry Andric     //   EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
2473ca95b02SDimitry Andric   }
2483ca95b02SDimitry Andric 
2493ca95b02SDimitry Andric   // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
2503ca95b02SDimitry Andric   // Update corresponding PHI nodes in epilog loop.
2513ca95b02SDimitry Andric   for (BasicBlock *Succ : successors(Latch)) {
2523ca95b02SDimitry Andric     // Skip this as we already updated phis in exit blocks.
2533ca95b02SDimitry Andric     if (!L->contains(Succ))
2543ca95b02SDimitry Andric       continue;
25530785c0eSDimitry Andric     for (PHINode &PN : Succ->phis()) {
2563ca95b02SDimitry Andric       // Add new PHI nodes to the loop exit block and update epilog
2573ca95b02SDimitry Andric       // PHIs with the new PHI values.
25830785c0eSDimitry Andric       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
2593ca95b02SDimitry Andric                                        NewExit->getFirstNonPHI());
2603ca95b02SDimitry Andric       // Adding a value to the new PHI node from the unrolling loop preheader.
26130785c0eSDimitry Andric       NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
2623ca95b02SDimitry Andric       // Adding a value to the new PHI node from the unrolling loop latch.
26330785c0eSDimitry Andric       NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
2643ca95b02SDimitry Andric 
2653ca95b02SDimitry Andric       // Update the existing PHI node operand with the value from the new PHI
2663ca95b02SDimitry Andric       // node.  Corresponding instruction in epilog loop should be PHI.
26730785c0eSDimitry Andric       PHINode *VPN = cast<PHINode>(VMap[&PN]);
2683ca95b02SDimitry Andric       VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
2693ca95b02SDimitry Andric     }
2703ca95b02SDimitry Andric   }
2713ca95b02SDimitry Andric 
2723ca95b02SDimitry Andric   Instruction *InsertPt = NewExit->getTerminator();
2733ca95b02SDimitry Andric   IRBuilder<> B(InsertPt);
2743ca95b02SDimitry Andric   Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
2753ca95b02SDimitry Andric   assert(Exit && "Loop must have a single exit block only");
2767a7e6055SDimitry Andric   // Split the epilogue exit to maintain loop canonicalization guarantees
2773ca95b02SDimitry Andric   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
278*b5893f02SDimitry Andric   SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
2793ca95b02SDimitry Andric                          PreserveLCSSA);
2803ca95b02SDimitry Andric   // Add the branch to the exit block (around the unrolling loop)
2813ca95b02SDimitry Andric   B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
282dff0c46cSDimitry Andric   InsertPt->eraseFromParent();
2837a7e6055SDimitry Andric   if (DT)
2847a7e6055SDimitry Andric     DT->changeImmediateDominator(Exit, NewExit);
2857a7e6055SDimitry Andric 
2867a7e6055SDimitry Andric   // Split the main loop exit to maintain canonicalization guarantees.
2877a7e6055SDimitry Andric   SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
288*b5893f02SDimitry Andric   SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
2897a7e6055SDimitry Andric                          PreserveLCSSA);
290dff0c46cSDimitry Andric }
291dff0c46cSDimitry Andric 
292dff0c46cSDimitry Andric /// Create a clone of the blocks in a loop and connect them together.
2933ca95b02SDimitry Andric /// If CreateRemainderLoop is false, loop structure will not be cloned,
2943ca95b02SDimitry Andric /// otherwise a new loop will be created including all cloned blocks, and the
2953ca95b02SDimitry Andric /// iterator of it switches to count NewIter down to 0.
2963ca95b02SDimitry Andric /// The cloned blocks should be inserted between InsertTop and InsertBot.
2973ca95b02SDimitry Andric /// If loop structure is cloned InsertTop should be new preheader, InsertBot
2983ca95b02SDimitry Andric /// new loop exit.
299a580b014SDimitry Andric /// Return the new cloned loop that is created when CreateRemainderLoop is true.
300a580b014SDimitry Andric static Loop *
CloneLoopBlocks(Loop * L,Value * NewIter,const bool CreateRemainderLoop,const bool UseEpilogRemainder,const bool UnrollRemainder,BasicBlock * InsertTop,BasicBlock * InsertBot,BasicBlock * Preheader,std::vector<BasicBlock * > & NewBlocks,LoopBlocksDFS & LoopBlocks,ValueToValueMapTy & VMap,DominatorTree * DT,LoopInfo * LI)301a580b014SDimitry Andric CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
3022cab237bSDimitry Andric                 const bool UseEpilogRemainder, const bool UnrollRemainder,
3032cab237bSDimitry Andric                 BasicBlock *InsertTop,
304a580b014SDimitry Andric                 BasicBlock *InsertBot, BasicBlock *Preheader,
305a580b014SDimitry Andric                 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
306a580b014SDimitry Andric                 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
3073ca95b02SDimitry Andric   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
308dff0c46cSDimitry Andric   BasicBlock *Header = L->getHeader();
309dff0c46cSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
310dff0c46cSDimitry Andric   Function *F = Header->getParent();
311dff0c46cSDimitry Andric   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
312dff0c46cSDimitry Andric   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
31339d628a0SDimitry Andric   Loop *ParentLoop = L->getParentLoop();
314f1a29dd3SDimitry Andric   NewLoopsMap NewLoops;
3157a7e6055SDimitry Andric   NewLoops[ParentLoop] = ParentLoop;
3167a7e6055SDimitry Andric   if (!CreateRemainderLoop)
3172bcad0d8SDimitry Andric     NewLoops[L] = ParentLoop;
3182bcad0d8SDimitry Andric 
319dff0c46cSDimitry Andric   // For each block in the original loop, create a new copy,
320dff0c46cSDimitry Andric   // and update the value map with the newly created values.
321dff0c46cSDimitry Andric   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
3223ca95b02SDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
323dff0c46cSDimitry Andric     NewBlocks.push_back(NewBB);
324dff0c46cSDimitry Andric 
3252bcad0d8SDimitry Andric     // If we're unrolling the outermost loop, there's no remainder loop,
3262bcad0d8SDimitry Andric     // and this block isn't in a nested loop, then the new block is not
3272bcad0d8SDimitry Andric     // in any loop. Otherwise, add it to loopinfo.
3282bcad0d8SDimitry Andric     if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
329f1a29dd3SDimitry Andric       addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
330dff0c46cSDimitry Andric 
331dff0c46cSDimitry Andric     VMap[*BB] = NewBB;
332dff0c46cSDimitry Andric     if (Header == *BB) {
333dff0c46cSDimitry Andric       // For the first block, add a CFG connection to this newly
33439d628a0SDimitry Andric       // created block.
335dff0c46cSDimitry Andric       InsertTop->getTerminator()->setSuccessor(0, NewBB);
33639d628a0SDimitry Andric     }
3373ca95b02SDimitry Andric 
3387a7e6055SDimitry Andric     if (DT) {
3397a7e6055SDimitry Andric       if (Header == *BB) {
3407a7e6055SDimitry Andric         // The header is dominated by the preheader.
3417a7e6055SDimitry Andric         DT->addNewBlock(NewBB, InsertTop);
3427a7e6055SDimitry Andric       } else {
3437a7e6055SDimitry Andric         // Copy information from original loop to unrolled loop.
3447a7e6055SDimitry Andric         BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
3457a7e6055SDimitry Andric         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
3467a7e6055SDimitry Andric       }
3477a7e6055SDimitry Andric     }
3487a7e6055SDimitry Andric 
34939d628a0SDimitry Andric     if (Latch == *BB) {
3503ca95b02SDimitry Andric       // For the last block, if CreateRemainderLoop is false, create a direct
3513ca95b02SDimitry Andric       // jump to InsertBot. If not, create a loop back to cloned head.
35239d628a0SDimitry Andric       VMap.erase((*BB)->getTerminator());
35339d628a0SDimitry Andric       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
35439d628a0SDimitry Andric       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
3558f0fd8f6SDimitry Andric       IRBuilder<> Builder(LatchBR);
3563ca95b02SDimitry Andric       if (!CreateRemainderLoop) {
3578f0fd8f6SDimitry Andric         Builder.CreateBr(InsertBot);
358dff0c46cSDimitry Andric       } else {
3593ca95b02SDimitry Andric         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
3603ca95b02SDimitry Andric                                           suffix + ".iter",
36139d628a0SDimitry Andric                                           FirstLoopBB->getFirstNonPHI());
36239d628a0SDimitry Andric         Value *IdxSub =
36339d628a0SDimitry Andric             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
36439d628a0SDimitry Andric                               NewIdx->getName() + ".sub");
36539d628a0SDimitry Andric         Value *IdxCmp =
36639d628a0SDimitry Andric             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
3678f0fd8f6SDimitry Andric         Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
36839d628a0SDimitry Andric         NewIdx->addIncoming(NewIter, InsertTop);
36939d628a0SDimitry Andric         NewIdx->addIncoming(IdxSub, NewBB);
370dff0c46cSDimitry Andric       }
3718f0fd8f6SDimitry Andric       LatchBR->eraseFromParent();
372dff0c46cSDimitry Andric     }
373dff0c46cSDimitry Andric   }
374dff0c46cSDimitry Andric 
37539d628a0SDimitry Andric   // Change the incoming values to the ones defined in the preheader or
37639d628a0SDimitry Andric   // cloned loop.
37739d628a0SDimitry Andric   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
3787d523365SDimitry Andric     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
3793ca95b02SDimitry Andric     if (!CreateRemainderLoop) {
3803ca95b02SDimitry Andric       if (UseEpilogRemainder) {
3813ca95b02SDimitry Andric         unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
3823ca95b02SDimitry Andric         NewPHI->setIncomingBlock(idx, InsertTop);
3833ca95b02SDimitry Andric         NewPHI->removeIncomingValue(Latch, false);
3843ca95b02SDimitry Andric       } else {
3857d523365SDimitry Andric         VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
38639d628a0SDimitry Andric         cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
3873ca95b02SDimitry Andric       }
38839d628a0SDimitry Andric     } else {
38939d628a0SDimitry Andric       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
39039d628a0SDimitry Andric       NewPHI->setIncomingBlock(idx, InsertTop);
39139d628a0SDimitry Andric       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
39239d628a0SDimitry Andric       idx = NewPHI->getBasicBlockIndex(Latch);
39339d628a0SDimitry Andric       Value *InVal = NewPHI->getIncomingValue(idx);
39439d628a0SDimitry Andric       NewPHI->setIncomingBlock(idx, NewLatch);
3953ca95b02SDimitry Andric       if (Value *V = VMap.lookup(InVal))
3963ca95b02SDimitry Andric         NewPHI->setIncomingValue(idx, V);
397dff0c46cSDimitry Andric     }
398dff0c46cSDimitry Andric   }
3997a7e6055SDimitry Andric   if (CreateRemainderLoop) {
4007a7e6055SDimitry Andric     Loop *NewLoop = NewLoops[L];
401*b5893f02SDimitry Andric     MDNode *LoopID = NewLoop->getLoopID();
4027a7e6055SDimitry Andric     assert(NewLoop && "L should have been cloned");
4032cab237bSDimitry Andric 
4042cab237bSDimitry Andric     // Only add loop metadata if the loop is not going to be completely
4052cab237bSDimitry Andric     // unrolled.
4062cab237bSDimitry Andric     if (UnrollRemainder)
4072cab237bSDimitry Andric       return NewLoop;
4082cab237bSDimitry Andric 
409*b5893f02SDimitry Andric     Optional<MDNode *> NewLoopID = makeFollowupLoopID(
410*b5893f02SDimitry Andric         LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
411*b5893f02SDimitry Andric     if (NewLoopID.hasValue()) {
412*b5893f02SDimitry Andric       NewLoop->setLoopID(NewLoopID.getValue());
413*b5893f02SDimitry Andric 
414*b5893f02SDimitry Andric       // Do not setLoopAlreadyUnrolled if loop attributes have been defined
415*b5893f02SDimitry Andric       // explicitly.
416*b5893f02SDimitry Andric       return NewLoop;
417*b5893f02SDimitry Andric     }
418*b5893f02SDimitry Andric 
41939d628a0SDimitry Andric     // Add unroll disable metadata to disable future unrolling for this loop.
4202cab237bSDimitry Andric     NewLoop->setLoopAlreadyUnrolled();
421a580b014SDimitry Andric     return NewLoop;
422dff0c46cSDimitry Andric   }
423a580b014SDimitry Andric   else
424a580b014SDimitry Andric     return nullptr;
425dff0c46cSDimitry Andric }
426dff0c46cSDimitry Andric 
427c4394386SDimitry Andric /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
428c4394386SDimitry Andric /// is populated with all the loop exit blocks other than the LatchExit block.
429c4394386SDimitry Andric static bool
canSafelyUnrollMultiExitLoop(Loop * L,SmallVectorImpl<BasicBlock * > & OtherExits,BasicBlock * LatchExit,bool PreserveLCSSA,bool UseEpilogRemainder)430c4394386SDimitry Andric canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits,
431c4394386SDimitry Andric                              BasicBlock *LatchExit, bool PreserveLCSSA,
432c4394386SDimitry Andric                              bool UseEpilogRemainder) {
433c4394386SDimitry Andric 
4342cab237bSDimitry Andric   // We currently have some correctness constrains in unrolling a multi-exit
4352cab237bSDimitry Andric   // loop. Check for these below.
4362cab237bSDimitry Andric 
437c4394386SDimitry Andric   // We rely on LCSSA form being preserved when the exit blocks are transformed.
438c4394386SDimitry Andric   if (!PreserveLCSSA)
439c4394386SDimitry Andric     return false;
440c4394386SDimitry Andric   SmallVector<BasicBlock *, 4> Exits;
441c4394386SDimitry Andric   L->getUniqueExitBlocks(Exits);
442c4394386SDimitry Andric   for (auto *BB : Exits)
443c4394386SDimitry Andric     if (BB != LatchExit)
444c4394386SDimitry Andric       OtherExits.push_back(BB);
445c4394386SDimitry Andric 
446c4394386SDimitry Andric   // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
447c4394386SDimitry Andric   // UnrollRuntimeMultiExit is true. This will need updating the logic in
448c4394386SDimitry Andric   // connectEpilog/connectProlog.
449c4394386SDimitry Andric   if (!LatchExit->getSinglePredecessor()) {
4504ba319b5SDimitry Andric     LLVM_DEBUG(
4514ba319b5SDimitry Andric         dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
452c4394386SDimitry Andric                   "predecessor.\n");
453c4394386SDimitry Andric     return false;
454c4394386SDimitry Andric   }
455c4394386SDimitry Andric   // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
456c4394386SDimitry Andric   // and L is an inner loop. This is because in presence of multiple exits, the
457c4394386SDimitry Andric   // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
458c4394386SDimitry Andric   // outer loop. This is automatically handled in the prolog case, so we do not
459c4394386SDimitry Andric   // have that bug in prolog generation.
460c4394386SDimitry Andric   if (UseEpilogRemainder && L->getParentLoop())
461c4394386SDimitry Andric     return false;
462c4394386SDimitry Andric 
463c4394386SDimitry Andric   // All constraints have been satisfied.
464c4394386SDimitry Andric   return true;
465c4394386SDimitry Andric }
466c4394386SDimitry Andric 
4672cab237bSDimitry Andric /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
4682cab237bSDimitry Andric /// we return true only if UnrollRuntimeMultiExit is set to true.
canProfitablyUnrollMultiExitLoop(Loop * L,SmallVectorImpl<BasicBlock * > & OtherExits,BasicBlock * LatchExit,bool PreserveLCSSA,bool UseEpilogRemainder)4692cab237bSDimitry Andric static bool canProfitablyUnrollMultiExitLoop(
4702cab237bSDimitry Andric     Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
4712cab237bSDimitry Andric     bool PreserveLCSSA, bool UseEpilogRemainder) {
472c4394386SDimitry Andric 
4732cab237bSDimitry Andric #if !defined(NDEBUG)
4742cab237bSDimitry Andric   SmallVector<BasicBlock *, 8> OtherExitsDummyCheck;
4752cab237bSDimitry Andric   assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit,
4762cab237bSDimitry Andric                                       PreserveLCSSA, UseEpilogRemainder) &&
4772cab237bSDimitry Andric          "Should be safe to unroll before checking profitability!");
4782cab237bSDimitry Andric #endif
4792cab237bSDimitry Andric 
4802cab237bSDimitry Andric   // Priority goes to UnrollRuntimeMultiExit if it's supplied.
4812cab237bSDimitry Andric   if (UnrollRuntimeMultiExit.getNumOccurrences())
4822cab237bSDimitry Andric     return UnrollRuntimeMultiExit;
4832cab237bSDimitry Andric 
4842cab237bSDimitry Andric   // The main pain point with multi-exit loop unrolling is that once unrolled,
4852cab237bSDimitry Andric   // we will not be able to merge all blocks into a straight line code.
4862cab237bSDimitry Andric   // There are branches within the unrolled loop that go to the OtherExits.
4872cab237bSDimitry Andric   // The second point is the increase in code size, but this is true
4882cab237bSDimitry Andric   // irrespective of multiple exits.
4892cab237bSDimitry Andric 
4902cab237bSDimitry Andric   // Note: Both the heuristics below are coarse grained. We are essentially
4912cab237bSDimitry Andric   // enabling unrolling of loops that have a single side exit other than the
4922cab237bSDimitry Andric   // normal LatchExit (i.e. exiting into a deoptimize block).
4932cab237bSDimitry Andric   // The heuristics considered are:
4942cab237bSDimitry Andric   // 1. low number of branches in the unrolled version.
4952cab237bSDimitry Andric   // 2. high predictability of these extra branches.
4962cab237bSDimitry Andric   // We avoid unrolling loops that have more than two exiting blocks. This
4972cab237bSDimitry Andric   // limits the total number of branches in the unrolled loop to be atmost
4982cab237bSDimitry Andric   // the unroll factor (since one of the exiting blocks is the latch block).
4992cab237bSDimitry Andric   SmallVector<BasicBlock*, 4> ExitingBlocks;
5002cab237bSDimitry Andric   L->getExitingBlocks(ExitingBlocks);
5012cab237bSDimitry Andric   if (ExitingBlocks.size() > 2)
5022cab237bSDimitry Andric     return false;
5032cab237bSDimitry Andric 
5042cab237bSDimitry Andric   // The second heuristic is that L has one exit other than the latchexit and
5052cab237bSDimitry Andric   // that exit is a deoptimize block. We know that deoptimize blocks are rarely
5062cab237bSDimitry Andric   // taken, which also implies the branch leading to the deoptimize block is
5072cab237bSDimitry Andric   // highly predictable.
5082cab237bSDimitry Andric   return (OtherExits.size() == 1 &&
5092cab237bSDimitry Andric           OtherExits[0]->getTerminatingDeoptimizeCall());
5102cab237bSDimitry Andric   // TODO: These can be fine-tuned further to consider code size or deopt states
5112cab237bSDimitry Andric   // that are captured by the deoptimize exit block.
5122cab237bSDimitry Andric   // Also, we can extend this to support more cases, if we actually
5132cab237bSDimitry Andric   // know of kinds of multiexit loops that would benefit from unrolling.
5142cab237bSDimitry Andric }
515c4394386SDimitry Andric 
5163ca95b02SDimitry Andric /// Insert code in the prolog/epilog code when unrolling a loop with a
517dff0c46cSDimitry Andric /// run-time trip-count.
518dff0c46cSDimitry Andric ///
519dff0c46cSDimitry Andric /// This method assumes that the loop unroll factor is total number
5203ca95b02SDimitry Andric /// of loop bodies in the loop after unrolling. (Some folks refer
521dff0c46cSDimitry Andric /// to the unroll factor as the number of *extra* copies added).
522dff0c46cSDimitry Andric /// We assume also that the loop unroll factor is a power-of-two. So, after
523dff0c46cSDimitry Andric /// unrolling the loop, the number of loop bodies executed is 2,
524dff0c46cSDimitry Andric /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
525dff0c46cSDimitry Andric /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
526dff0c46cSDimitry Andric /// the switch instruction is generated.
527dff0c46cSDimitry Andric ///
5283ca95b02SDimitry Andric /// ***Prolog case***
529dff0c46cSDimitry Andric ///        extraiters = tripcount % loopfactor
530dff0c46cSDimitry Andric ///        if (extraiters == 0) jump Loop:
5313ca95b02SDimitry Andric ///        else jump Prol:
53239d628a0SDimitry Andric /// Prol:  LoopBody;
53339d628a0SDimitry Andric ///        extraiters -= 1                 // Omitted if unroll factor is 2.
53439d628a0SDimitry Andric ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
5353ca95b02SDimitry Andric ///        if (tripcount < loopfactor) jump End:
536dff0c46cSDimitry Andric /// Loop:
537dff0c46cSDimitry Andric /// ...
538dff0c46cSDimitry Andric /// End:
539dff0c46cSDimitry Andric ///
5403ca95b02SDimitry Andric /// ***Epilog case***
5413ca95b02SDimitry Andric ///        extraiters = tripcount % loopfactor
5423ca95b02SDimitry Andric ///        if (tripcount < loopfactor) jump LoopExit:
5433ca95b02SDimitry Andric ///        unroll_iters = tripcount - extraiters
5443ca95b02SDimitry Andric /// Loop:  LoopBody; (executes unroll_iter times);
5453ca95b02SDimitry Andric ///        unroll_iter -= 1
5463ca95b02SDimitry Andric ///        if (unroll_iter != 0) jump Loop:
5473ca95b02SDimitry Andric /// LoopExit:
5483ca95b02SDimitry Andric ///        if (extraiters == 0) jump EpilExit:
5493ca95b02SDimitry Andric /// Epil:  LoopBody; (executes extraiters times)
5503ca95b02SDimitry Andric ///        extraiters -= 1                 // Omitted if unroll factor is 2.
5513ca95b02SDimitry Andric ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
5523ca95b02SDimitry Andric /// EpilExit:
5533ca95b02SDimitry Andric 
UnrollRuntimeLoopRemainder(Loop * L,unsigned Count,bool AllowExpensiveTripCount,bool UseEpilogRemainder,bool UnrollRemainder,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,bool PreserveLCSSA,Loop ** ResultLoop)5543ca95b02SDimitry Andric bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
5553ca95b02SDimitry Andric                                       bool AllowExpensiveTripCount,
5563ca95b02SDimitry Andric                                       bool UseEpilogRemainder,
557*b5893f02SDimitry Andric                                       bool UnrollRemainder, LoopInfo *LI,
558*b5893f02SDimitry Andric                                       ScalarEvolution *SE, DominatorTree *DT,
559*b5893f02SDimitry Andric                                       AssumptionCache *AC, bool PreserveLCSSA,
560*b5893f02SDimitry Andric                                       Loop **ResultLoop) {
5614ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
5624ba319b5SDimitry Andric   LLVM_DEBUG(L->dump());
5634ba319b5SDimitry Andric   LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
5644ba319b5SDimitry Andric                                 : dbgs() << "Using prolog remainder.\n");
565dff0c46cSDimitry Andric 
566a580b014SDimitry Andric   // Make sure the loop is in canonical form.
567c4394386SDimitry Andric   if (!L->isLoopSimplifyForm()) {
5684ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
5693ca95b02SDimitry Andric     return false;
570c4394386SDimitry Andric   }
571dff0c46cSDimitry Andric 
572edd7eaddSDimitry Andric   // Guaranteed by LoopSimplifyForm.
573edd7eaddSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
574a580b014SDimitry Andric   BasicBlock *Header = L->getHeader();
575edd7eaddSDimitry Andric 
576edd7eaddSDimitry Andric   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
577*b5893f02SDimitry Andric 
578*b5893f02SDimitry Andric   if (!LatchBR || LatchBR->isUnconditional()) {
579*b5893f02SDimitry Andric     // The loop-rotate pass can be helpful to avoid this in many cases.
580*b5893f02SDimitry Andric     LLVM_DEBUG(
581*b5893f02SDimitry Andric         dbgs()
582*b5893f02SDimitry Andric         << "Loop latch not terminated by a conditional branch.\n");
583*b5893f02SDimitry Andric     return false;
584*b5893f02SDimitry Andric   }
585*b5893f02SDimitry Andric 
586c4394386SDimitry Andric   unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
587c4394386SDimitry Andric   BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
588*b5893f02SDimitry Andric 
589*b5893f02SDimitry Andric   if (L->contains(LatchExit)) {
590a580b014SDimitry Andric     // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
591*b5893f02SDimitry Andric     // targets of the Latch be an exit block out of the loop.
592*b5893f02SDimitry Andric     LLVM_DEBUG(
593*b5893f02SDimitry Andric         dbgs()
594*b5893f02SDimitry Andric         << "One of the loop latch successors must be the exit block.\n");
595*b5893f02SDimitry Andric     return false;
596*b5893f02SDimitry Andric   }
597*b5893f02SDimitry Andric 
598c4394386SDimitry Andric   // These are exit blocks other than the target of the latch exiting block.
599c4394386SDimitry Andric   SmallVector<BasicBlock *, 4> OtherExits;
6002cab237bSDimitry Andric   bool isMultiExitUnrollingEnabled =
6012cab237bSDimitry Andric       canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
6022cab237bSDimitry Andric                                    UseEpilogRemainder) &&
6032cab237bSDimitry Andric       canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
6042cab237bSDimitry Andric                                        UseEpilogRemainder);
605c4394386SDimitry Andric   // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
606c4394386SDimitry Andric   if (!isMultiExitUnrollingEnabled &&
607c4394386SDimitry Andric       (!L->getExitingBlock() || OtherExits.size())) {
6084ba319b5SDimitry Andric     LLVM_DEBUG(
609c4394386SDimitry Andric         dbgs()
610c4394386SDimitry Andric         << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
611c4394386SDimitry Andric            "enabled!\n");
612a580b014SDimitry Andric     return false;
613a580b014SDimitry Andric   }
6143ca95b02SDimitry Andric   // Use Scalar Evolution to compute the trip count. This allows more loops to
6153ca95b02SDimitry Andric   // be unrolled than relying on induction var simplification.
61691bc56edSDimitry Andric   if (!SE)
617dff0c46cSDimitry Andric     return false;
618dff0c46cSDimitry Andric 
6193ca95b02SDimitry Andric   // Only unroll loops with a computable trip count, and the trip count needs
6203ca95b02SDimitry Andric   // to be an int value (allowing a pointer type is a TODO item).
621a580b014SDimitry Andric   // We calculate the backedge count by using getExitCount on the Latch block,
622a580b014SDimitry Andric   // which is proven to be the only exiting block in this loop. This is same as
623a580b014SDimitry Andric   // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
624a580b014SDimitry Andric   // exiting blocks).
625a580b014SDimitry Andric   const SCEV *BECountSC = SE->getExitCount(L, Latch);
626b09980d1SDimitry Andric   if (isa<SCEVCouldNotCompute>(BECountSC) ||
627c4394386SDimitry Andric       !BECountSC->getType()->isIntegerTy()) {
6284ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
629dff0c46cSDimitry Andric     return false;
630c4394386SDimitry Andric   }
631dff0c46cSDimitry Andric 
632b09980d1SDimitry Andric   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
63339d628a0SDimitry Andric 
6343ca95b02SDimitry Andric   // Add 1 since the backedge count doesn't include the first loop iteration.
635dff0c46cSDimitry Andric   const SCEV *TripCountSC =
636b09980d1SDimitry Andric       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
637c4394386SDimitry Andric   if (isa<SCEVCouldNotCompute>(TripCountSC)) {
6384ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
639dff0c46cSDimitry Andric     return false;
640c4394386SDimitry Andric   }
641dff0c46cSDimitry Andric 
6423ca95b02SDimitry Andric   BasicBlock *PreHeader = L->getLoopPreheader();
6433ca95b02SDimitry Andric   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
644ff0cc061SDimitry Andric   const DataLayout &DL = Header->getModule()->getDataLayout();
645ff0cc061SDimitry Andric   SCEVExpander Expander(*SE, DL, "loop-unroll");
6463ca95b02SDimitry Andric   if (!AllowExpensiveTripCount &&
647c4394386SDimitry Andric       Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
6484ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
649b09980d1SDimitry Andric     return false;
650c4394386SDimitry Andric   }
651b09980d1SDimitry Andric 
652b09980d1SDimitry Andric   // This constraint lets us deal with an overflowing trip count easily; see the
653ff0cc061SDimitry Andric   // comment on ModVal below.
654c4394386SDimitry Andric   if (Log2_32(Count) > BEWidth) {
6554ba319b5SDimitry Andric     LLVM_DEBUG(
6564ba319b5SDimitry Andric         dbgs()
657c4394386SDimitry Andric         << "Count failed constraint on overflow trip count calculation.\n");
658dff0c46cSDimitry Andric     return false;
659c4394386SDimitry Andric   }
660dff0c46cSDimitry Andric 
6613ca95b02SDimitry Andric   // Loop structure is the following:
6623ca95b02SDimitry Andric   //
6633ca95b02SDimitry Andric   // PreHeader
6643ca95b02SDimitry Andric   //   Header
6653ca95b02SDimitry Andric   //   ...
6663ca95b02SDimitry Andric   //   Latch
667edd7eaddSDimitry Andric   // LatchExit
6683ca95b02SDimitry Andric 
6693ca95b02SDimitry Andric   BasicBlock *NewPreHeader;
6703ca95b02SDimitry Andric   BasicBlock *NewExit = nullptr;
6713ca95b02SDimitry Andric   BasicBlock *PrologExit = nullptr;
6723ca95b02SDimitry Andric   BasicBlock *EpilogPreHeader = nullptr;
6733ca95b02SDimitry Andric   BasicBlock *PrologPreHeader = nullptr;
6743ca95b02SDimitry Andric 
6753ca95b02SDimitry Andric   if (UseEpilogRemainder) {
6763ca95b02SDimitry Andric     // If epilog remainder
6773ca95b02SDimitry Andric     // Split PreHeader to insert a branch around loop for unrolling.
6783ca95b02SDimitry Andric     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
6793ca95b02SDimitry Andric     NewPreHeader->setName(PreHeader->getName() + ".new");
680edd7eaddSDimitry Andric     // Split LatchExit to create phi nodes from branch above.
681edd7eaddSDimitry Andric     SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
682*b5893f02SDimitry Andric     NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI,
683*b5893f02SDimitry Andric                                      nullptr, PreserveLCSSA);
684fe4fed2eSDimitry Andric     // NewExit gets its DebugLoc from LatchExit, which is not part of the
685fe4fed2eSDimitry Andric     // original Loop.
686fe4fed2eSDimitry Andric     // Fix this by setting Loop's DebugLoc to NewExit.
687fe4fed2eSDimitry Andric     auto *NewExitTerminator = NewExit->getTerminator();
688fe4fed2eSDimitry Andric     NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
6893ca95b02SDimitry Andric     // Split NewExit to insert epilog remainder loop.
690fe4fed2eSDimitry Andric     EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
6913ca95b02SDimitry Andric     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
6923ca95b02SDimitry Andric   } else {
6933ca95b02SDimitry Andric     // If prolog remainder
6943ca95b02SDimitry Andric     // Split the original preheader twice to insert prolog remainder loop
6953ca95b02SDimitry Andric     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
6963ca95b02SDimitry Andric     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
6973ca95b02SDimitry Andric     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
6983ca95b02SDimitry Andric                             DT, LI);
6993ca95b02SDimitry Andric     PrologExit->setName(Header->getName() + ".prol.loopexit");
7003ca95b02SDimitry Andric     // Split PrologExit to get NewPreHeader.
7013ca95b02SDimitry Andric     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
7023ca95b02SDimitry Andric     NewPreHeader->setName(PreHeader->getName() + ".new");
7033ca95b02SDimitry Andric   }
7043ca95b02SDimitry Andric   // Loop structure should be the following:
7053ca95b02SDimitry Andric   //  Epilog             Prolog
7063ca95b02SDimitry Andric   //
7073ca95b02SDimitry Andric   // PreHeader         PreHeader
7083ca95b02SDimitry Andric   // *NewPreHeader     *PrologPreHeader
7093ca95b02SDimitry Andric   //   Header          *PrologExit
7103ca95b02SDimitry Andric   //   ...             *NewPreHeader
7113ca95b02SDimitry Andric   //   Latch             Header
7123ca95b02SDimitry Andric   // *NewExit            ...
7133ca95b02SDimitry Andric   // *EpilogPreHeader    Latch
714edd7eaddSDimitry Andric   // LatchExit              LatchExit
7153ca95b02SDimitry Andric 
7163ca95b02SDimitry Andric   // Calculate conditions for branch around loop for unrolling
7173ca95b02SDimitry Andric   // in epilog case and around prolog remainder loop in prolog case.
718dff0c46cSDimitry Andric   // Compute the number of extra iterations required, which is:
7193ca95b02SDimitry Andric   //  extra iterations = run-time trip count % loop unroll factor
7203ca95b02SDimitry Andric   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
721dff0c46cSDimitry Andric   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
722dff0c46cSDimitry Andric                                             PreHeaderBR);
723b09980d1SDimitry Andric   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
724b09980d1SDimitry Andric                                           PreHeaderBR);
72591bc56edSDimitry Andric   IRBuilder<> B(PreHeaderBR);
7263ca95b02SDimitry Andric   Value *ModVal;
7273ca95b02SDimitry Andric   // Calculate ModVal = (BECount + 1) % Count.
7283ca95b02SDimitry Andric   // Note that TripCount is BECount + 1.
7293ca95b02SDimitry Andric   if (isPowerOf2_32(Count)) {
7303ca95b02SDimitry Andric     // When Count is power of 2 we don't BECount for epilog case, however we'll
7313ca95b02SDimitry Andric     // need it for a branch around unrolling loop for prolog case.
7323ca95b02SDimitry Andric     ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
7333ca95b02SDimitry Andric     //  1. There are no iterations to be run in the prolog/epilog loop.
734b09980d1SDimitry Andric     // OR
7353ca95b02SDimitry Andric     //  2. The addition computing TripCount overflowed.
736b09980d1SDimitry Andric     //
7373ca95b02SDimitry Andric     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
7383ca95b02SDimitry Andric     // the number of iterations that remain to be run in the original loop is a
739b09980d1SDimitry Andric     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
740b09980d1SDimitry Andric     // explicitly check this above).
7413ca95b02SDimitry Andric   } else {
7423ca95b02SDimitry Andric     // As (BECount + 1) can potentially unsigned overflow we count
7433ca95b02SDimitry Andric     // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
7443ca95b02SDimitry Andric     Value *ModValTmp = B.CreateURem(BECount,
7453ca95b02SDimitry Andric                                     ConstantInt::get(BECount->getType(),
7463ca95b02SDimitry Andric                                                      Count));
7473ca95b02SDimitry Andric     Value *ModValAdd = B.CreateAdd(ModValTmp,
7483ca95b02SDimitry Andric                                    ConstantInt::get(ModValTmp->getType(), 1));
7493ca95b02SDimitry Andric     // At that point (BECount % Count) + 1 could be equal to Count.
7503ca95b02SDimitry Andric     // To handle this case we need to take mod by Count one more time.
7513ca95b02SDimitry Andric     ModVal = B.CreateURem(ModValAdd,
7523ca95b02SDimitry Andric                           ConstantInt::get(BECount->getType(), Count),
7533ca95b02SDimitry Andric                           "xtraiter");
7543ca95b02SDimitry Andric   }
7553ca95b02SDimitry Andric   Value *BranchVal =
7563ca95b02SDimitry Andric       UseEpilogRemainder ? B.CreateICmpULT(BECount,
7573ca95b02SDimitry Andric                                            ConstantInt::get(BECount->getType(),
7583ca95b02SDimitry Andric                                                             Count - 1)) :
7593ca95b02SDimitry Andric                            B.CreateIsNotNull(ModVal, "lcmp.mod");
7603ca95b02SDimitry Andric   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
7613ca95b02SDimitry Andric   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
7623ca95b02SDimitry Andric   // Branch to either remainder (extra iterations) loop or unrolling loop.
7633ca95b02SDimitry Andric   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
764dff0c46cSDimitry Andric   PreHeaderBR->eraseFromParent();
7657a7e6055SDimitry Andric   if (DT) {
7667a7e6055SDimitry Andric     if (UseEpilogRemainder)
7677a7e6055SDimitry Andric       DT->changeImmediateDominator(NewExit, PreHeader);
7687a7e6055SDimitry Andric     else
7697a7e6055SDimitry Andric       DT->changeImmediateDominator(PrologExit, PreHeader);
7707a7e6055SDimitry Andric   }
771dff0c46cSDimitry Andric   Function *F = Header->getParent();
772dff0c46cSDimitry Andric   // Get an ordered list of blocks in the loop to help with the ordering of the
7733ca95b02SDimitry Andric   // cloned blocks in the prolog/epilog code
774dff0c46cSDimitry Andric   LoopBlocksDFS LoopBlocks(L);
775dff0c46cSDimitry Andric   LoopBlocks.perform(LI);
776dff0c46cSDimitry Andric 
777dff0c46cSDimitry Andric   //
778dff0c46cSDimitry Andric   // For each extra loop iteration, create a copy of the loop's basic blocks
779dff0c46cSDimitry Andric   // and generate a condition that branches to the copy depending on the
780dff0c46cSDimitry Andric   // number of 'left over' iterations.
781dff0c46cSDimitry Andric   //
782dff0c46cSDimitry Andric   std::vector<BasicBlock *> NewBlocks;
783dff0c46cSDimitry Andric   ValueToValueMapTy VMap;
784dff0c46cSDimitry Andric 
7853ca95b02SDimitry Andric   // For unroll factor 2 remainder loop will have 1 iterations.
7863ca95b02SDimitry Andric   // Do not create 1 iteration loop.
7873ca95b02SDimitry Andric   bool CreateRemainderLoop = (Count != 2);
78839d628a0SDimitry Andric 
78939d628a0SDimitry Andric   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
79039d628a0SDimitry Andric   // the loop, otherwise we create a cloned loop to execute the extra
79139d628a0SDimitry Andric   // iterations. This function adds the appropriate CFG connections.
792edd7eaddSDimitry Andric   BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
7933ca95b02SDimitry Andric   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
794a580b014SDimitry Andric   Loop *remainderLoop = CloneLoopBlocks(
7952cab237bSDimitry Andric       L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
7962cab237bSDimitry Andric       InsertTop, InsertBot,
797a580b014SDimitry Andric       NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
798dff0c46cSDimitry Andric 
7993ca95b02SDimitry Andric   // Insert the cloned blocks into the function.
8003ca95b02SDimitry Andric   F->getBasicBlockList().splice(InsertBot->getIterator(),
8013ca95b02SDimitry Andric                                 F->getBasicBlockList(),
8023ca95b02SDimitry Andric                                 NewBlocks[0]->getIterator(),
8033ca95b02SDimitry Andric                                 F->end());
804dff0c46cSDimitry Andric 
805a580b014SDimitry Andric   // Now the loop blocks are cloned and the other exiting blocks from the
806a580b014SDimitry Andric   // remainder are connected to the original Loop's exit blocks. The remaining
807a580b014SDimitry Andric   // work is to update the phi nodes in the original loop, and take in the
808*b5893f02SDimitry Andric   // values from the cloned region.
809a580b014SDimitry Andric   for (auto *BB : OtherExits) {
810a580b014SDimitry Andric    for (auto &II : *BB) {
811a580b014SDimitry Andric 
812a580b014SDimitry Andric      // Given we preserve LCSSA form, we know that the values used outside the
813a580b014SDimitry Andric      // loop will be used through these phi nodes at the exit blocks that are
814a580b014SDimitry Andric      // transformed below.
815a580b014SDimitry Andric      if (!isa<PHINode>(II))
816a580b014SDimitry Andric        break;
817a580b014SDimitry Andric      PHINode *Phi = cast<PHINode>(&II);
818a580b014SDimitry Andric      unsigned oldNumOperands = Phi->getNumIncomingValues();
819a580b014SDimitry Andric      // Add the incoming values from the remainder code to the end of the phi
820a580b014SDimitry Andric      // node.
821a580b014SDimitry Andric      for (unsigned i =0; i < oldNumOperands; i++){
8222cab237bSDimitry Andric        Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
823c4394386SDimitry Andric        // newVal can be a constant or derived from values outside the loop, and
8242cab237bSDimitry Andric        // hence need not have a VMap value. Also, since lookup already generated
8252cab237bSDimitry Andric        // a default "null" VMap entry for this value, we need to populate that
8262cab237bSDimitry Andric        // VMap entry correctly, with the mapped entry being itself.
8272cab237bSDimitry Andric        if (!newVal) {
828a580b014SDimitry Andric          newVal = Phi->getIncomingValue(i);
8292cab237bSDimitry Andric          VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
8302cab237bSDimitry Andric        }
831a580b014SDimitry Andric        Phi->addIncoming(newVal,
832a580b014SDimitry Andric                            cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
833a580b014SDimitry Andric      }
834a580b014SDimitry Andric    }
835b40b48b8SDimitry Andric #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
836b40b48b8SDimitry Andric     for (BasicBlock *SuccBB : successors(BB)) {
837b40b48b8SDimitry Andric       assert(!(any_of(OtherExits,
838b40b48b8SDimitry Andric                       [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
839b40b48b8SDimitry Andric                SuccBB == LatchExit) &&
840b40b48b8SDimitry Andric              "Breaks the definition of dedicated exits!");
841b40b48b8SDimitry Andric     }
842b40b48b8SDimitry Andric #endif
843*b5893f02SDimitry Andric   }
844*b5893f02SDimitry Andric 
845*b5893f02SDimitry Andric   // Update the immediate dominator of the exit blocks and blocks that are
846*b5893f02SDimitry Andric   // reachable from the exit blocks. This is needed because we now have paths
847*b5893f02SDimitry Andric   // from both the original loop and the remainder code reaching the exit
848*b5893f02SDimitry Andric   // blocks. While the IDom of these exit blocks were from the original loop,
849*b5893f02SDimitry Andric   // now the IDom is the preheader (which decides whether the original loop or
850*b5893f02SDimitry Andric   // remainder code should run).
851*b5893f02SDimitry Andric   if (DT && !L->getExitingBlock()) {
852*b5893f02SDimitry Andric     SmallVector<BasicBlock *, 16> ChildrenToUpdate;
853*b5893f02SDimitry Andric     // NB! We have to examine the dom children of all loop blocks, not just
854*b5893f02SDimitry Andric     // those which are the IDom of the exit blocks. This is because blocks
855*b5893f02SDimitry Andric     // reachable from the exit blocks can have their IDom as the nearest common
856*b5893f02SDimitry Andric     // dominator of the exit blocks.
857*b5893f02SDimitry Andric     for (auto *BB : L->blocks()) {
858*b5893f02SDimitry Andric       auto *DomNodeBB = DT->getNode(BB);
859*b5893f02SDimitry Andric       for (auto *DomChild : DomNodeBB->getChildren()) {
860*b5893f02SDimitry Andric         auto *DomChildBB = DomChild->getBlock();
861*b5893f02SDimitry Andric         if (!L->contains(LI->getLoopFor(DomChildBB)))
862*b5893f02SDimitry Andric           ChildrenToUpdate.push_back(DomChildBB);
863*b5893f02SDimitry Andric       }
864*b5893f02SDimitry Andric     }
865*b5893f02SDimitry Andric     for (auto *BB : ChildrenToUpdate)
866a580b014SDimitry Andric       DT->changeImmediateDominator(BB, PreHeader);
867a580b014SDimitry Andric   }
868a580b014SDimitry Andric 
8693ca95b02SDimitry Andric   // Loop structure should be the following:
8703ca95b02SDimitry Andric   //  Epilog             Prolog
8713ca95b02SDimitry Andric   //
8723ca95b02SDimitry Andric   // PreHeader         PreHeader
8733ca95b02SDimitry Andric   // NewPreHeader      PrologPreHeader
8743ca95b02SDimitry Andric   //   Header            PrologHeader
8753ca95b02SDimitry Andric   //   ...               ...
8763ca95b02SDimitry Andric   //   Latch             PrologLatch
8773ca95b02SDimitry Andric   // NewExit           PrologExit
8783ca95b02SDimitry Andric   // EpilogPreHeader   NewPreHeader
8793ca95b02SDimitry Andric   //   EpilogHeader      Header
8803ca95b02SDimitry Andric   //   ...               ...
8813ca95b02SDimitry Andric   //   EpilogLatch       Latch
882edd7eaddSDimitry Andric   // LatchExit              LatchExit
8833ca95b02SDimitry Andric 
8843ca95b02SDimitry Andric   // Rewrite the cloned instruction operands to use the values created when the
8853ca95b02SDimitry Andric   // clone is created.
8863ca95b02SDimitry Andric   for (BasicBlock *BB : NewBlocks) {
8873ca95b02SDimitry Andric     for (Instruction &I : *BB) {
8883ca95b02SDimitry Andric       RemapInstruction(&I, VMap,
8893ca95b02SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
890dff0c46cSDimitry Andric     }
891dff0c46cSDimitry Andric   }
892dff0c46cSDimitry Andric 
8933ca95b02SDimitry Andric   if (UseEpilogRemainder) {
8943ca95b02SDimitry Andric     // Connect the epilog code to the original loop and update the
8953ca95b02SDimitry Andric     // PHI functions.
896edd7eaddSDimitry Andric     ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
8973ca95b02SDimitry Andric                   EpilogPreHeader, NewPreHeader, VMap, DT, LI,
8983ca95b02SDimitry Andric                   PreserveLCSSA);
8993ca95b02SDimitry Andric 
9003ca95b02SDimitry Andric     // Update counter in loop for unrolling.
9013ca95b02SDimitry Andric     // I should be multiply of Count.
9023ca95b02SDimitry Andric     IRBuilder<> B2(NewPreHeader->getTerminator());
9033ca95b02SDimitry Andric     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
9043ca95b02SDimitry Andric     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
9053ca95b02SDimitry Andric     B2.SetInsertPoint(LatchBR);
9063ca95b02SDimitry Andric     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
9073ca95b02SDimitry Andric                                       Header->getFirstNonPHI());
9083ca95b02SDimitry Andric     Value *IdxSub =
9093ca95b02SDimitry Andric         B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
9103ca95b02SDimitry Andric                      NewIdx->getName() + ".nsub");
9113ca95b02SDimitry Andric     Value *IdxCmp;
9123ca95b02SDimitry Andric     if (LatchBR->getSuccessor(0) == Header)
9133ca95b02SDimitry Andric       IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
9143ca95b02SDimitry Andric     else
9153ca95b02SDimitry Andric       IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
9163ca95b02SDimitry Andric     NewIdx->addIncoming(TestVal, NewPreHeader);
9173ca95b02SDimitry Andric     NewIdx->addIncoming(IdxSub, Latch);
9183ca95b02SDimitry Andric     LatchBR->setCondition(IdxCmp);
9193ca95b02SDimitry Andric   } else {
920dff0c46cSDimitry Andric     // Connect the prolog code to the original loop and update the
921dff0c46cSDimitry Andric     // PHI functions.
922c4394386SDimitry Andric     ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
923c4394386SDimitry Andric                   NewPreHeader, VMap, DT, LI, PreserveLCSSA);
9243ca95b02SDimitry Andric   }
925d88c1a5aSDimitry Andric 
9264ba319b5SDimitry Andric   // If this loop is nested, then the loop unroller changes the code in the any
9274ba319b5SDimitry Andric   // of its parent loops, so the Scalar Evolution pass needs to be run again.
9284ba319b5SDimitry Andric   SE->forgetTopmostLoop(L);
929d88c1a5aSDimitry Andric 
930*b5893f02SDimitry Andric   // Verify that the Dom Tree is correct.
931*b5893f02SDimitry Andric #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
932*b5893f02SDimitry Andric   if (DT)
933*b5893f02SDimitry Andric     assert(DT->verify(DominatorTree::VerificationLevel::Full));
934*b5893f02SDimitry Andric #endif
935*b5893f02SDimitry Andric 
936a580b014SDimitry Andric   // Canonicalize to LoopSimplifyForm both original and remainder loops. We
937a580b014SDimitry Andric   // cannot rely on the LoopUnrollPass to do this because it only does
938a580b014SDimitry Andric   // canonicalization for parent/subloops and not the sibling loops.
939a580b014SDimitry Andric   if (OtherExits.size() > 0) {
940a580b014SDimitry Andric     // Generate dedicated exit blocks for the original loop, to preserve
941a580b014SDimitry Andric     // LoopSimplifyForm.
942a580b014SDimitry Andric     formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
943a580b014SDimitry Andric     // Generate dedicated exit blocks for the remainder loop if one exists, to
944a580b014SDimitry Andric     // preserve LoopSimplifyForm.
945a580b014SDimitry Andric     if (remainderLoop)
946a580b014SDimitry Andric       formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
947a580b014SDimitry Andric   }
948a580b014SDimitry Andric 
949*b5893f02SDimitry Andric   auto UnrollResult = LoopUnrollResult::Unmodified;
9502cab237bSDimitry Andric   if (remainderLoop && UnrollRemainder) {
9514ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
952*b5893f02SDimitry Andric     UnrollResult =
9532cab237bSDimitry Andric         UnrollLoop(remainderLoop, /*Count*/ Count - 1, /*TripCount*/ Count - 1,
9542cab237bSDimitry Andric                    /*Force*/ false, /*AllowRuntime*/ false,
9552cab237bSDimitry Andric                    /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true,
9562cab237bSDimitry Andric                    /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1,
9572cab237bSDimitry Andric                    /*PeelCount*/ 0, /*UnrollRemainder*/ false, LI, SE, DT, AC,
9582cab237bSDimitry Andric                    /*ORE*/ nullptr, PreserveLCSSA);
9592cab237bSDimitry Andric   }
9602cab237bSDimitry Andric 
961*b5893f02SDimitry Andric   if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
962*b5893f02SDimitry Andric     *ResultLoop = remainderLoop;
963dff0c46cSDimitry Andric   NumRuntimeUnrolled++;
964dff0c46cSDimitry Andric   return true;
965dff0c46cSDimitry Andric }
966