blob: f96c0bd149a0e9f99d502c08d6fada37ec7b5fc6 [file] [log] [blame]
Andrew Trickd04d15292011-12-09 06:19:40 +00001//===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements some loop unrolling utilities for loops with run-time
11// trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
12// trip counts.
13//
Jakub Staszak1b1d5232011-12-18 21:52:30 +000014// The functions in this file are used to generate extra code when the
Andrew Trickd04d15292011-12-09 06:19:40 +000015// run-time trip count modulo the unroll factor is not 0. When this is the
16// case, we need to generate code to execute these 'left over' iterations.
17//
Jakub Staszak1b1d5232011-12-18 21:52:30 +000018// The current strategy generates an if-then-else sequence prior to the
David L Kreitzer188de5a2016-04-05 12:19:35 +000019// unrolled loop to execute the 'left over' iterations before or after the
20// unrolled loop.
Andrew Trickd04d15292011-12-09 06:19:40 +000021//
22//===----------------------------------------------------------------------===//
23
Andrew Trickd04d15292011-12-09 06:19:40 +000024#include "llvm/ADT/Statistic.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000025#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000026#include "llvm/Analysis/LoopIterator.h"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Analysis/ScalarEvolution.h"
29#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/BasicBlock.h"
Chandler Carruth32c52c72015-01-18 02:39:37 +000031#include "llvm/IR/Dominators.h"
Kevin Qinfc02e3c2014-09-29 11:15:00 +000032#include "llvm/IR/Metadata.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000033#include "llvm/IR/Module.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000036#include "llvm/Transforms/Scalar.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Cloning.h"
Anna Thomase5e5e592017-06-30 17:57:07 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000040#include "llvm/Transforms/Utils/UnrollLoop.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000041#include <algorithm>
42
43using namespace llvm;
44
Chandler Carruth964daaa2014-04-22 02:55:47 +000045#define DEBUG_TYPE "loop-unroll"
46
Jakub Staszak1b1d5232011-12-18 21:52:30 +000047STATISTIC(NumRuntimeUnrolled,
Andrew Trickd04d15292011-12-09 06:19:40 +000048 "Number of loops unrolled with run-time trip counts");
Anna Thomase5e5e592017-06-30 17:57:07 +000049static cl::opt<bool> UnrollRuntimeMultiExit(
50 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
51 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
52 "epilog is generated"));
Andrew Trickd04d15292011-12-09 06:19:40 +000053
54/// Connect the unrolling prolog code to the original loop.
55/// The unrolling prolog code contains code to execute the
56/// 'extra' iterations if the run-time trip count modulo the
57/// unroll count is non-zero.
58///
59/// This function performs the following:
60/// - Create PHI nodes at prolog end block to combine values
61/// that exit the prolog code and jump around the prolog.
62/// - Add a PHI operand to a PHI node at the loop exit block
63/// for values that exit the prolog and go around the loop.
64/// - Branch around the original loop if the trip count is less
65/// than the unroll factor.
66///
Sanjoy Das11b279a2015-02-18 19:32:25 +000067static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
David L Kreitzer188de5a2016-04-05 12:19:35 +000068 BasicBlock *PrologExit, BasicBlock *PreHeader,
69 BasicBlock *NewPreHeader, ValueToValueMapTy &VMap,
70 DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA) {
Andrew Trickd04d15292011-12-09 06:19:40 +000071 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000072 assert(Latch && "Loop must have a latch");
David L Kreitzer188de5a2016-04-05 12:19:35 +000073 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
Andrew Trickd04d15292011-12-09 06:19:40 +000074
75 // Create a PHI node for each outgoing value from the original loop
76 // (which means it is an outgoing value from the prolog code too).
77 // The new PHI node is inserted in the prolog end basic block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000078 // The new PHI node value is added as an operand of a PHI node in either
Andrew Trickd04d15292011-12-09 06:19:40 +000079 // the loop header or the loop exit block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000080 for (BasicBlock *Succ : successors(Latch)) {
81 for (Instruction &BBI : *Succ) {
82 PHINode *PN = dyn_cast<PHINode>(&BBI);
83 // Exit when we passed all PHI nodes.
84 if (!PN)
85 break;
Andrew Trickd04d15292011-12-09 06:19:40 +000086 // Add a new PHI node to the prolog end block and add the
87 // appropriate incoming values.
David L Kreitzer188de5a2016-04-05 12:19:35 +000088 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
89 PrologExit->getFirstNonPHI());
Andrew Trickd04d15292011-12-09 06:19:40 +000090 // Adding a value to the new PHI node from the original loop preheader.
91 // This is the value that skips all the prolog code.
92 if (L->contains(PN)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +000093 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader),
94 PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +000095 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +000096 NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +000097 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +000098
99 Value *V = PN->getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000100 if (Instruction *I = dyn_cast<Instruction>(V)) {
101 if (L->contains(I)) {
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000102 V = VMap.lookup(I);
Andrew Trickd04d15292011-12-09 06:19:40 +0000103 }
104 }
105 // Adding a value to the new PHI node from the last prolog block
106 // that was created.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000107 NewPN->addIncoming(V, PrologLatch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000108
109 // Update the existing PHI node operand with the value from the
110 // new PHI node. How this is done depends on if the existing
111 // PHI node is in the original loop block, or the exit block.
112 if (L->contains(PN)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000113 PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN);
Andrew Trickd04d15292011-12-09 06:19:40 +0000114 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000115 PN->addIncoming(NewPN, PrologExit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000116 }
117 }
118 }
119
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000120 // Make sure that created prolog loop is in simplified form
121 SmallVector<BasicBlock *, 4> PrologExitPreds;
122 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
123 if (PrologLoop) {
124 for (BasicBlock *PredBB : predecessors(PrologExit))
125 if (PrologLoop->contains(PredBB))
126 PrologExitPreds.push_back(PredBB);
127
128 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
129 PreserveLCSSA);
130 }
131
Sanjay Patele08381a2016-02-08 19:27:33 +0000132 // Create a branch around the original loop, which is taken if there are no
Sanjoy Das11b279a2015-02-18 19:32:25 +0000133 // iterations remaining to be executed after running the prologue.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000134 Instruction *InsertPt = PrologExit->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000135 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000136
137 assert(Count != 0 && "nonsensical Count!");
138
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000139 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
140 // This means %xtraiter is (BECount + 1) and all of the iterations of this
141 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
142 // then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000143 Value *BrLoopExit =
144 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000145 BasicBlock *Exit = L->getUniqueExitBlock();
Craig Toppere73658d2014-04-28 04:05:08 +0000146 assert(Exit && "Loop must have a single exit block only");
Andrew Trickd04d15292011-12-09 06:19:40 +0000147 // Split the exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000148 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
Chandler Carruth96ada252015-07-22 09:52:54 +0000149 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI,
Justin Bogner843fb202015-12-15 19:40:57 +0000150 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000151 // Add the branch to the exit block (around the unrolled loop)
David L Kreitzer188de5a2016-04-05 12:19:35 +0000152 B.CreateCondBr(BrLoopExit, Exit, NewPreHeader);
153 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000154 if (DT)
155 DT->changeImmediateDominator(Exit, PrologExit);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000156}
157
158/// Connect the unrolling epilog code to the original loop.
159/// The unrolling epilog code contains code to execute the
160/// 'extra' iterations if the run-time trip count modulo the
161/// unroll count is non-zero.
162///
163/// This function performs the following:
164/// - Update PHI nodes at the unrolling loop exit and epilog loop exit
165/// - Create PHI nodes at the unrolling loop exit to combine
166/// values that exit the unrolling loop code and jump around it.
167/// - Update PHI operands in the epilog loop by the new PHI nodes
168/// - Branch around the epilog loop if extra iters (ModVal) is zero.
169///
170static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
171 BasicBlock *Exit, BasicBlock *PreHeader,
172 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
173 ValueToValueMapTy &VMap, DominatorTree *DT,
174 LoopInfo *LI, bool PreserveLCSSA) {
175 BasicBlock *Latch = L->getLoopLatch();
176 assert(Latch && "Loop must have a latch");
177 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
178
179 // Loop structure should be the following:
180 //
181 // PreHeader
182 // NewPreHeader
183 // Header
184 // ...
185 // Latch
186 // NewExit (PN)
187 // EpilogPreHeader
188 // EpilogHeader
189 // ...
190 // EpilogLatch
191 // Exit (EpilogPN)
192
193 // Update PHI nodes at NewExit and Exit.
194 for (Instruction &BBI : *NewExit) {
195 PHINode *PN = dyn_cast<PHINode>(&BBI);
196 // Exit when we passed all PHI nodes.
197 if (!PN)
198 break;
199 // PN should be used in another PHI located in Exit block as
200 // Exit was split by SplitBlockPredecessors into Exit and NewExit
201 // Basicaly it should look like:
202 // NewExit:
203 // PN = PHI [I, Latch]
204 // ...
205 // Exit:
206 // EpilogPN = PHI [PN, EpilogPreHeader]
207 //
208 // There is EpilogPreHeader incoming block instead of NewExit as
209 // NewExit was spilt 1 more time to get EpilogPreHeader.
210 assert(PN->hasOneUse() && "The phi should have 1 use");
211 PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser());
212 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
213
214 // Add incoming PreHeader from branch around the Loop
215 PN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
216
217 Value *V = PN->getIncomingValueForBlock(Latch);
218 Instruction *I = dyn_cast<Instruction>(V);
219 if (I && L->contains(I))
220 // If value comes from an instruction in the loop add VMap value.
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000221 V = VMap.lookup(I);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000222 // For the instruction out of the loop, constant or undefined value
223 // insert value itself.
224 EpilogPN->addIncoming(V, EpilogLatch);
225
226 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
227 "EpilogPN should have EpilogPreHeader incoming block");
228 // Change EpilogPreHeader incoming block to NewExit.
229 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
230 NewExit);
231 // Now PHIs should look like:
232 // NewExit:
233 // PN = PHI [I, Latch], [undef, PreHeader]
234 // ...
235 // Exit:
236 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
237 }
238
239 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
240 // Update corresponding PHI nodes in epilog loop.
241 for (BasicBlock *Succ : successors(Latch)) {
242 // Skip this as we already updated phis in exit blocks.
243 if (!L->contains(Succ))
244 continue;
245 for (Instruction &BBI : *Succ) {
246 PHINode *PN = dyn_cast<PHINode>(&BBI);
247 // Exit when we passed all PHI nodes.
248 if (!PN)
249 break;
250 // Add new PHI nodes to the loop exit block and update epilog
251 // PHIs with the new PHI values.
252 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
253 NewExit->getFirstNonPHI());
254 // Adding a value to the new PHI node from the unrolling loop preheader.
255 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader);
256 // Adding a value to the new PHI node from the unrolling loop latch.
257 NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch);
258
259 // Update the existing PHI node operand with the value from the new PHI
260 // node. Corresponding instruction in epilog loop should be PHI.
261 PHINode *VPN = cast<PHINode>(VMap[&BBI]);
262 VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
263 }
264 }
265
266 Instruction *InsertPt = NewExit->getTerminator();
267 IRBuilder<> B(InsertPt);
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000268 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000269 assert(Exit && "Loop must have a single exit block only");
Eli Friedman0a217452017-01-18 23:26:37 +0000270 // Split the epilogue exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000271 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
272 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI,
273 PreserveLCSSA);
274 // Add the branch to the exit block (around the unrolling loop)
275 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000276 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000277 if (DT)
278 DT->changeImmediateDominator(Exit, NewExit);
279
280 // Split the main loop exit to maintain canonicalization guarantees.
281 SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
282 SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI,
283 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000284}
285
286/// Create a clone of the blocks in a loop and connect them together.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000287/// If CreateRemainderLoop is false, loop structure will not be cloned,
288/// otherwise a new loop will be created including all cloned blocks, and the
289/// iterator of it switches to count NewIter down to 0.
290/// The cloned blocks should be inserted between InsertTop and InsertBot.
291/// If loop structure is cloned InsertTop should be new preheader, InsertBot
292/// new loop exit.
Anna Thomase5e5e592017-06-30 17:57:07 +0000293/// Return the new cloned loop that is created when CreateRemainderLoop is true.
294static Loop *
295CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
296 const bool UseEpilogRemainder, BasicBlock *InsertTop,
297 BasicBlock *InsertBot, BasicBlock *Preheader,
298 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
299 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000300 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
Andrew Trickd04d15292011-12-09 06:19:40 +0000301 BasicBlock *Header = L->getHeader();
302 BasicBlock *Latch = L->getLoopLatch();
303 Function *F = Header->getParent();
304 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
305 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000306 Loop *ParentLoop = L->getParentLoop();
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000307 NewLoopsMap NewLoops;
Florian Hahn5364cf32017-01-31 11:13:44 +0000308 NewLoops[ParentLoop] = ParentLoop;
309 if (!CreateRemainderLoop)
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000310 NewLoops[L] = ParentLoop;
311
Andrew Trickd04d15292011-12-09 06:19:40 +0000312 // For each block in the original loop, create a new copy,
313 // and update the value map with the newly created values.
314 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000315 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000316 NewBlocks.push_back(NewBB);
Florian Hahn5364cf32017-01-31 11:13:44 +0000317
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000318 // If we're unrolling the outermost loop, there's no remainder loop,
319 // and this block isn't in a nested loop, then the new block is not
320 // in any loop. Otherwise, add it to loopinfo.
321 if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000322 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
Andrew Trickd04d15292011-12-09 06:19:40 +0000323
324 VMap[*BB] = NewBB;
325 if (Header == *BB) {
326 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000327 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000328 InsertTop->getTerminator()->setSuccessor(0, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000329 }
Junmo Park502ff662016-01-28 01:23:18 +0000330
Eli Friedman0a217452017-01-18 23:26:37 +0000331 if (DT) {
332 if (Header == *BB) {
333 // The header is dominated by the preheader.
334 DT->addNewBlock(NewBB, InsertTop);
335 } else {
336 // Copy information from original loop to unrolled loop.
337 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
338 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
339 }
340 }
341
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000342 if (Latch == *BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000343 // For the last block, if CreateRemainderLoop is false, create a direct
344 // jump to InsertBot. If not, create a loop back to cloned head.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000345 VMap.erase((*BB)->getTerminator());
346 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
347 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000348 IRBuilder<> Builder(LatchBR);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000349 if (!CreateRemainderLoop) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000350 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000351 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000352 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
353 suffix + ".iter",
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000354 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000355 Value *IdxSub =
356 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
357 NewIdx->getName() + ".sub");
358 Value *IdxCmp =
359 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000360 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000361 NewIdx->addIncoming(NewIter, InsertTop);
362 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000363 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000364 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000365 }
366 }
367
368 // Change the incoming values to the ones defined in the preheader or
369 // cloned loop.
370 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000371 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000372 if (!CreateRemainderLoop) {
373 if (UseEpilogRemainder) {
374 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
375 NewPHI->setIncomingBlock(idx, InsertTop);
376 NewPHI->removeIncomingValue(Latch, false);
377 } else {
378 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
379 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
380 }
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000381 } else {
382 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
383 NewPHI->setIncomingBlock(idx, InsertTop);
384 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
385 idx = NewPHI->getBasicBlockIndex(Latch);
386 Value *InVal = NewPHI->getIncomingValue(idx);
387 NewPHI->setIncomingBlock(idx, NewLatch);
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000388 if (Value *V = VMap.lookup(InVal))
389 NewPHI->setIncomingValue(idx, V);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000390 }
391 }
Florian Hahn5364cf32017-01-31 11:13:44 +0000392 if (CreateRemainderLoop) {
393 Loop *NewLoop = NewLoops[L];
394 assert(NewLoop && "L should have been cloned");
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000395 // Add unroll disable metadata to disable future unrolling for this loop.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000396 SmallVector<Metadata *, 4> MDs;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000397 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000398 MDs.push_back(nullptr);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000399 MDNode *LoopID = NewLoop->getLoopID();
400 if (LoopID) {
401 // First remove any existing loop unrolling metadata.
402 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
403 bool IsUnrollMetadata = false;
404 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
405 if (MD) {
406 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
407 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
Andrew Trickd04d15292011-12-09 06:19:40 +0000408 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000409 if (!IsUnrollMetadata)
410 MDs.push_back(LoopID->getOperand(i));
Andrew Trickd04d15292011-12-09 06:19:40 +0000411 }
412 }
413
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000414 LLVMContext &Context = NewLoop->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000415 SmallVector<Metadata *, 1> DisableOperands;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000416 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
417 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000418 MDs.push_back(DisableNode);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000419
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000420 MDNode *NewLoopID = MDNode::get(Context, MDs);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000421 // Set operand 0 to refer to the loop id itself.
422 NewLoopID->replaceOperandWith(0, NewLoopID);
423 NewLoop->setLoopID(NewLoopID);
Anna Thomase5e5e592017-06-30 17:57:07 +0000424 return NewLoop;
Andrew Trickd04d15292011-12-09 06:19:40 +0000425 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000426 else
427 return nullptr;
Andrew Trickd04d15292011-12-09 06:19:40 +0000428}
429
David L Kreitzer188de5a2016-04-05 12:19:35 +0000430/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000431/// run-time trip-count.
432///
433/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000434/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000435/// to the unroll factor as the number of *extra* copies added).
436/// We assume also that the loop unroll factor is a power-of-two. So, after
437/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000438/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000439/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
440/// the switch instruction is generated.
441///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000442/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000443/// extraiters = tripcount % loopfactor
444/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000445/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000446/// Prol: LoopBody;
447/// extraiters -= 1 // Omitted if unroll factor is 2.
448/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000449/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000450/// Loop:
451/// ...
452/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000453///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000454/// ***Epilog case***
455/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000456/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000457/// unroll_iters = tripcount - extraiters
458/// Loop: LoopBody; (executes unroll_iter times);
459/// unroll_iter -= 1
460/// if (unroll_iter != 0) jump Loop:
461/// LoopExit:
462/// if (extraiters == 0) jump EpilExit:
463/// Epil: LoopBody; (executes extraiters times)
464/// extraiters -= 1 // Omitted if unroll factor is 2.
465/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
466/// EpilExit:
467
468bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
469 bool AllowExpensiveTripCount,
470 bool UseEpilogRemainder,
471 LoopInfo *LI, ScalarEvolution *SE,
472 DominatorTree *DT, bool PreserveLCSSA) {
473 // for now, only unroll loops that contain a single exit
Anna Thomase5e5e592017-06-30 17:57:07 +0000474 if (!UnrollRuntimeMultiExit && !L->getExitingBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000475 return false;
476
Anna Thomase5e5e592017-06-30 17:57:07 +0000477 // Make sure the loop is in canonical form.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000478 if (!L->isLoopSimplifyForm())
479 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000480
Anna Thomas91eed9a2017-06-23 14:28:01 +0000481 // Guaranteed by LoopSimplifyForm.
482 BasicBlock *Latch = L->getLoopLatch();
Anna Thomase5e5e592017-06-30 17:57:07 +0000483 BasicBlock *Header = L->getHeader();
Anna Thomas91eed9a2017-06-23 14:28:01 +0000484
485 BasicBlock *LatchExit = L->getUniqueExitBlock(); // successor out of loop
Anna Thomase5e5e592017-06-30 17:57:07 +0000486 if (!LatchExit && !UnrollRuntimeMultiExit)
Anna Thomas91eed9a2017-06-23 14:28:01 +0000487 return false;
Anna Thomase5e5e592017-06-30 17:57:07 +0000488 // These are exit blocks other than the target of the latch exiting block.
489 SmallVector<BasicBlock *, 4> OtherExits;
Anna Thomas91eed9a2017-06-23 14:28:01 +0000490 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
Anna Thomase5e5e592017-06-30 17:57:07 +0000491 unsigned int ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
492 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
493 // targets of the Latch be an exit block out of the loop. This needs
494 // to be guaranteed by the callers of UnrollRuntimeLoopRemainder.
495 assert(!L->contains(LatchBR->getSuccessor(ExitIndex)) &&
496 "one of the loop latch successors should be the exit block!");
497 // Support runtime unrolling for multiple exit blocks and multiple exiting
498 // blocks.
499 if (!LatchExit) {
500 assert(UseEpilogRemainder && "Multi exit unrolling is currently supported "
501 "unrolling with epilog remainder only!");
502 LatchExit = LatchBR->getSuccessor(ExitIndex);
503 // We rely on LCSSA form being preserved when the exit blocks are
504 // transformed.
505 if (!PreserveLCSSA)
506 return false;
Anna Thomase5e5e592017-06-30 17:57:07 +0000507 SmallVector<BasicBlock *, 4> Exits;
508 L->getUniqueExitBlocks(Exits);
509 for (auto *BB : Exits)
510 if (BB != LatchExit)
511 OtherExits.push_back(BB);
512 }
513
514 assert(LatchExit && "Latch Exit should exist!");
515
Anna Thomaseb6d5d12017-07-06 18:39:26 +0000516 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
517 // UnrollRuntimeMultiExit is true. This will need updating the logic in
518 // connectEpilog.
519 if (!LatchExit->getSinglePredecessor())
520 return false;
Sanjay Patele08381a2016-02-08 19:27:33 +0000521 // Use Scalar Evolution to compute the trip count. This allows more loops to
522 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000523 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000524 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000525
Sanjay Patele08381a2016-02-08 19:27:33 +0000526 // Only unroll loops with a computable trip count, and the trip count needs
527 // to be an int value (allowing a pointer type is a TODO item).
Anna Thomasdc935a62017-06-27 14:14:35 +0000528 // We calculate the backedge count by using getExitCount on the Latch block,
529 // which is proven to be the only exiting block in this loop. This is same as
530 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
531 // exiting blocks).
532 const SCEV *BECountSC = SE->getExitCount(L, Latch);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000533 if (isa<SCEVCouldNotCompute>(BECountSC) ||
534 !BECountSC->getType()->isIntegerTy())
Andrew Trickd04d15292011-12-09 06:19:40 +0000535 return false;
536
Sanjoy Das11b279a2015-02-18 19:32:25 +0000537 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000538
Sanjay Patele08381a2016-02-08 19:27:33 +0000539 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000540 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000541 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000542 if (isa<SCEVCouldNotCompute>(TripCountSC))
543 return false;
544
David L Kreitzer188de5a2016-04-05 12:19:35 +0000545 BasicBlock *PreHeader = L->getLoopPreheader();
546 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000547 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000548 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000549 if (!AllowExpensiveTripCount &&
550 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR))
Sanjoy Dase178f462015-04-14 03:20:38 +0000551 return false;
552
Sanjoy Das11b279a2015-02-18 19:32:25 +0000553 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000554 // comment on ModVal below.
555 if (Log2_32(Count) > BEWidth)
Andrew Trickd04d15292011-12-09 06:19:40 +0000556 return false;
557
David L Kreitzer188de5a2016-04-05 12:19:35 +0000558 // Loop structure is the following:
559 //
560 // PreHeader
561 // Header
562 // ...
563 // Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000564 // LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000565
566 BasicBlock *NewPreHeader;
567 BasicBlock *NewExit = nullptr;
568 BasicBlock *PrologExit = nullptr;
569 BasicBlock *EpilogPreHeader = nullptr;
570 BasicBlock *PrologPreHeader = nullptr;
571
572 if (UseEpilogRemainder) {
573 // If epilog remainder
574 // Split PreHeader to insert a branch around loop for unrolling.
575 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
576 NewPreHeader->setName(PreHeader->getName() + ".new");
Anna Thomas91eed9a2017-06-23 14:28:01 +0000577 // Split LatchExit to create phi nodes from branch above.
578 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
579 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000580 DT, LI, PreserveLCSSA);
581 // Split NewExit to insert epilog remainder loop.
582 EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
583 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
584 } else {
585 // If prolog remainder
586 // Split the original preheader twice to insert prolog remainder loop
587 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
588 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
589 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
590 DT, LI);
591 PrologExit->setName(Header->getName() + ".prol.loopexit");
592 // Split PrologExit to get NewPreHeader.
593 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
594 NewPreHeader->setName(PreHeader->getName() + ".new");
595 }
596 // Loop structure should be the following:
597 // Epilog Prolog
598 //
599 // PreHeader PreHeader
600 // *NewPreHeader *PrologPreHeader
601 // Header *PrologExit
602 // ... *NewPreHeader
603 // Latch Header
604 // *NewExit ...
605 // *EpilogPreHeader Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000606 // LatchExit LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000607
608 // Calculate conditions for branch around loop for unrolling
609 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000610 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000611 // extra iterations = run-time trip count % loop unroll factor
612 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000613 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
614 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000615 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
616 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000617 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000618 Value *ModVal;
619 // Calculate ModVal = (BECount + 1) % Count.
620 // Note that TripCount is BECount + 1.
621 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000622 // When Count is power of 2 we don't BECount for epilog case, however we'll
623 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000624 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000625 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000626 // OR
627 // 2. The addition computing TripCount overflowed.
628 //
629 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
630 // the number of iterations that remain to be run in the original loop is a
631 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
632 // explicitly check this above).
633 } else {
634 // As (BECount + 1) can potentially unsigned overflow we count
635 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
636 Value *ModValTmp = B.CreateURem(BECount,
637 ConstantInt::get(BECount->getType(),
638 Count));
639 Value *ModValAdd = B.CreateAdd(ModValTmp,
640 ConstantInt::get(ModValTmp->getType(), 1));
641 // At that point (BECount % Count) + 1 could be equal to Count.
642 // To handle this case we need to take mod by Count one more time.
643 ModVal = B.CreateURem(ModValAdd,
644 ConstantInt::get(BECount->getType(), Count),
645 "xtraiter");
646 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000647 Value *BranchVal =
648 UseEpilogRemainder ? B.CreateICmpULT(BECount,
649 ConstantInt::get(BECount->getType(),
650 Count - 1)) :
651 B.CreateIsNotNull(ModVal, "lcmp.mod");
652 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
653 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000654 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000655 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000656 PreHeaderBR->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000657 if (DT) {
658 if (UseEpilogRemainder)
659 DT->changeImmediateDominator(NewExit, PreHeader);
660 else
661 DT->changeImmediateDominator(PrologExit, PreHeader);
662 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000663 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000664 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000665 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000666 LoopBlocksDFS LoopBlocks(L);
667 LoopBlocks.perform(LI);
668
669 //
670 // For each extra loop iteration, create a copy of the loop's basic blocks
671 // and generate a condition that branches to the copy depending on the
672 // number of 'left over' iterations.
673 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000674 std::vector<BasicBlock *> NewBlocks;
675 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000676
David L Kreitzer188de5a2016-04-05 12:19:35 +0000677 // For unroll factor 2 remainder loop will have 1 iterations.
678 // Do not create 1 iteration loop.
679 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000680
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000681 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
682 // the loop, otherwise we create a cloned loop to execute the extra
683 // iterations. This function adds the appropriate CFG connections.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000684 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000685 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
Anna Thomase5e5e592017-06-30 17:57:07 +0000686 Loop *remainderLoop = CloneLoopBlocks(
687 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop, InsertBot,
688 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000689
David L Kreitzer188de5a2016-04-05 12:19:35 +0000690 // Insert the cloned blocks into the function.
691 F->getBasicBlockList().splice(InsertBot->getIterator(),
692 F->getBasicBlockList(),
693 NewBlocks[0]->getIterator(),
694 F->end());
695
Anna Thomase5e5e592017-06-30 17:57:07 +0000696 // Now the loop blocks are cloned and the other exiting blocks from the
697 // remainder are connected to the original Loop's exit blocks. The remaining
698 // work is to update the phi nodes in the original loop, and take in the
699 // values from the cloned region. Also update the dominator info for
700 // OtherExits, since we have new edges into OtherExits.
701 for (auto *BB : OtherExits) {
702 for (auto &II : *BB) {
703
704 // Given we preserve LCSSA form, we know that the values used outside the
705 // loop will be used through these phi nodes at the exit blocks that are
706 // transformed below.
707 if (!isa<PHINode>(II))
708 break;
709 PHINode *Phi = cast<PHINode>(&II);
710 unsigned oldNumOperands = Phi->getNumIncomingValues();
711 // Add the incoming values from the remainder code to the end of the phi
712 // node.
713 for (unsigned i =0; i < oldNumOperands; i++){
714 Value *newVal = VMap[Phi->getIncomingValue(i)];
715 if (!newVal) {
716 assert(isa<Constant>(Phi->getIncomingValue(i)) &&
717 "VMap should exist for all values except constants!");
718 newVal = Phi->getIncomingValue(i);
719 }
720 Phi->addIncoming(newVal,
721 cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
722 }
723 }
724 // Update the dominator info because the immediate dominator is no longer the
725 // header of the original Loop. BB has edges both from L and remainder code.
726 // Since the preheader determines which loop is run (L or directly jump to
727 // the remainder code), we set the immediate dominator as the preheader.
728 if (DT)
729 DT->changeImmediateDominator(BB, PreHeader);
730 }
731
David L Kreitzer188de5a2016-04-05 12:19:35 +0000732 // Loop structure should be the following:
733 // Epilog Prolog
734 //
735 // PreHeader PreHeader
736 // NewPreHeader PrologPreHeader
737 // Header PrologHeader
738 // ... ...
739 // Latch PrologLatch
740 // NewExit PrologExit
741 // EpilogPreHeader NewPreHeader
742 // EpilogHeader Header
743 // ... ...
744 // EpilogLatch Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000745 // LatchExit LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +0000746
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000747 // Rewrite the cloned instruction operands to use the values created when the
748 // clone is created.
749 for (BasicBlock *BB : NewBlocks) {
750 for (Instruction &I : *BB) {
751 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000752 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000753 }
754 }
755
David L Kreitzer188de5a2016-04-05 12:19:35 +0000756 if (UseEpilogRemainder) {
757 // Connect the epilog code to the original loop and update the
758 // PHI functions.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000759 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000760 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
761 PreserveLCSSA);
762
763 // Update counter in loop for unrolling.
764 // I should be multiply of Count.
765 IRBuilder<> B2(NewPreHeader->getTerminator());
766 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
767 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
768 B2.SetInsertPoint(LatchBR);
769 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
770 Header->getFirstNonPHI());
771 Value *IdxSub =
772 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
773 NewIdx->getName() + ".nsub");
774 Value *IdxCmp;
775 if (LatchBR->getSuccessor(0) == Header)
776 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
777 else
778 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
779 NewIdx->addIncoming(TestVal, NewPreHeader);
780 NewIdx->addIncoming(IdxSub, Latch);
781 LatchBR->setCondition(IdxCmp);
782 } else {
783 // Connect the prolog code to the original loop and update the
784 // PHI functions.
785 ConnectProlog(L, BECount, Count, PrologExit, PreHeader, NewPreHeader,
786 VMap, DT, LI, PreserveLCSSA);
787 }
Wei Mi59ca9662016-08-25 16:17:18 +0000788
789 // If this loop is nested, then the loop unroller changes the code in the
790 // parent loop, so the Scalar Evolution pass needs to be run again.
791 if (Loop *ParentLoop = L->getParentLoop())
792 SE->forgetLoop(ParentLoop);
793
Anna Thomase5e5e592017-06-30 17:57:07 +0000794 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
795 // cannot rely on the LoopUnrollPass to do this because it only does
796 // canonicalization for parent/subloops and not the sibling loops.
797 if (OtherExits.size() > 0) {
798 // Generate dedicated exit blocks for the original loop, to preserve
799 // LoopSimplifyForm.
800 formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
801 // Generate dedicated exit blocks for the remainder loop if one exists, to
802 // preserve LoopSimplifyForm.
803 if (remainderLoop)
804 formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
805 }
806
Andrew Trickd04d15292011-12-09 06:19:40 +0000807 NumRuntimeUnrolled++;
808 return true;
809}