blob: 16197a9206e47731b2bd183aea8c51672fc5174b [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/Transforms/Utils/UnrollLoop.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000025#include "llvm/ADT/Statistic.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000026#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000027#include "llvm/Analysis/LoopIterator.h"
28#include "llvm/Analysis/LoopPass.h"
29#include "llvm/Analysis/ScalarEvolution.h"
30#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/BasicBlock.h"
Chandler Carruth32c52c72015-01-18 02:39:37 +000032#include "llvm/IR/Dominators.h"
Kevin Qinfc02e3c2014-09-29 11:15:00 +000033#include "llvm/IR/Metadata.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000034#include "llvm/IR/Module.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000037#include "llvm/Transforms/Scalar.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/Cloning.h"
40#include <algorithm>
41
42using namespace llvm;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "loop-unroll"
45
Jakub Staszak1b1d5232011-12-18 21:52:30 +000046STATISTIC(NumRuntimeUnrolled,
Andrew Trickd04d15292011-12-09 06:19:40 +000047 "Number of loops unrolled with run-time trip counts");
48
49/// Connect the unrolling prolog code to the original loop.
50/// The unrolling prolog code contains code to execute the
51/// 'extra' iterations if the run-time trip count modulo the
52/// unroll count is non-zero.
53///
54/// This function performs the following:
55/// - Create PHI nodes at prolog end block to combine values
56/// that exit the prolog code and jump around the prolog.
57/// - Add a PHI operand to a PHI node at the loop exit block
58/// for values that exit the prolog and go around the loop.
59/// - Branch around the original loop if the trip count is less
60/// than the unroll factor.
61///
Sanjoy Das11b279a2015-02-18 19:32:25 +000062static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
David L Kreitzer188de5a2016-04-05 12:19:35 +000063 BasicBlock *PrologExit, BasicBlock *PreHeader,
64 BasicBlock *NewPreHeader, ValueToValueMapTy &VMap,
65 DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA) {
Andrew Trickd04d15292011-12-09 06:19:40 +000066 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000067 assert(Latch && "Loop must have a latch");
David L Kreitzer188de5a2016-04-05 12:19:35 +000068 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
Andrew Trickd04d15292011-12-09 06:19:40 +000069
70 // Create a PHI node for each outgoing value from the original loop
71 // (which means it is an outgoing value from the prolog code too).
72 // The new PHI node is inserted in the prolog end basic block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000073 // The new PHI node value is added as an operand of a PHI node in either
Andrew Trickd04d15292011-12-09 06:19:40 +000074 // the loop header or the loop exit block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000075 for (BasicBlock *Succ : successors(Latch)) {
76 for (Instruction &BBI : *Succ) {
77 PHINode *PN = dyn_cast<PHINode>(&BBI);
78 // Exit when we passed all PHI nodes.
79 if (!PN)
80 break;
Andrew Trickd04d15292011-12-09 06:19:40 +000081 // Add a new PHI node to the prolog end block and add the
82 // appropriate incoming values.
David L Kreitzer188de5a2016-04-05 12:19:35 +000083 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
84 PrologExit->getFirstNonPHI());
Andrew Trickd04d15292011-12-09 06:19:40 +000085 // Adding a value to the new PHI node from the original loop preheader.
86 // This is the value that skips all the prolog code.
87 if (L->contains(PN)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +000088 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader),
89 PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +000090 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +000091 NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +000092 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +000093
94 Value *V = PN->getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +000095 if (Instruction *I = dyn_cast<Instruction>(V)) {
96 if (L->contains(I)) {
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +000097 V = VMap.lookup(I);
Andrew Trickd04d15292011-12-09 06:19:40 +000098 }
99 }
100 // Adding a value to the new PHI node from the last prolog block
101 // that was created.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000102 NewPN->addIncoming(V, PrologLatch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000103
104 // Update the existing PHI node operand with the value from the
105 // new PHI node. How this is done depends on if the existing
106 // PHI node is in the original loop block, or the exit block.
107 if (L->contains(PN)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000108 PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN);
Andrew Trickd04d15292011-12-09 06:19:40 +0000109 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000110 PN->addIncoming(NewPN, PrologExit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000111 }
112 }
113 }
114
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000115 // Make sure that created prolog loop is in simplified form
116 SmallVector<BasicBlock *, 4> PrologExitPreds;
117 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
118 if (PrologLoop) {
119 for (BasicBlock *PredBB : predecessors(PrologExit))
120 if (PrologLoop->contains(PredBB))
121 PrologExitPreds.push_back(PredBB);
122
123 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
124 PreserveLCSSA);
125 }
126
Sanjay Patele08381a2016-02-08 19:27:33 +0000127 // Create a branch around the original loop, which is taken if there are no
Sanjoy Das11b279a2015-02-18 19:32:25 +0000128 // iterations remaining to be executed after running the prologue.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000129 Instruction *InsertPt = PrologExit->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000130 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000131
132 assert(Count != 0 && "nonsensical Count!");
133
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000134 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
135 // This means %xtraiter is (BECount + 1) and all of the iterations of this
136 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
137 // then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000138 Value *BrLoopExit =
139 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000140 BasicBlock *Exit = L->getUniqueExitBlock();
Craig Toppere73658d2014-04-28 04:05:08 +0000141 assert(Exit && "Loop must have a single exit block only");
Andrew Trickd04d15292011-12-09 06:19:40 +0000142 // Split the exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000143 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
Chandler Carruth96ada252015-07-22 09:52:54 +0000144 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI,
Justin Bogner843fb202015-12-15 19:40:57 +0000145 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000146 // Add the branch to the exit block (around the unrolled loop)
David L Kreitzer188de5a2016-04-05 12:19:35 +0000147 B.CreateCondBr(BrLoopExit, Exit, NewPreHeader);
148 InsertPt->eraseFromParent();
149}
150
151/// Connect the unrolling epilog code to the original loop.
152/// The unrolling epilog code contains code to execute the
153/// 'extra' iterations if the run-time trip count modulo the
154/// unroll count is non-zero.
155///
156/// This function performs the following:
157/// - Update PHI nodes at the unrolling loop exit and epilog loop exit
158/// - Create PHI nodes at the unrolling loop exit to combine
159/// values that exit the unrolling loop code and jump around it.
160/// - Update PHI operands in the epilog loop by the new PHI nodes
161/// - Branch around the epilog loop if extra iters (ModVal) is zero.
162///
163static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
164 BasicBlock *Exit, BasicBlock *PreHeader,
165 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
166 ValueToValueMapTy &VMap, DominatorTree *DT,
167 LoopInfo *LI, bool PreserveLCSSA) {
168 BasicBlock *Latch = L->getLoopLatch();
169 assert(Latch && "Loop must have a latch");
170 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
171
172 // Loop structure should be the following:
173 //
174 // PreHeader
175 // NewPreHeader
176 // Header
177 // ...
178 // Latch
179 // NewExit (PN)
180 // EpilogPreHeader
181 // EpilogHeader
182 // ...
183 // EpilogLatch
184 // Exit (EpilogPN)
185
186 // Update PHI nodes at NewExit and Exit.
187 for (Instruction &BBI : *NewExit) {
188 PHINode *PN = dyn_cast<PHINode>(&BBI);
189 // Exit when we passed all PHI nodes.
190 if (!PN)
191 break;
192 // PN should be used in another PHI located in Exit block as
193 // Exit was split by SplitBlockPredecessors into Exit and NewExit
194 // Basicaly it should look like:
195 // NewExit:
196 // PN = PHI [I, Latch]
197 // ...
198 // Exit:
199 // EpilogPN = PHI [PN, EpilogPreHeader]
200 //
201 // There is EpilogPreHeader incoming block instead of NewExit as
202 // NewExit was spilt 1 more time to get EpilogPreHeader.
203 assert(PN->hasOneUse() && "The phi should have 1 use");
204 PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser());
205 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
206
207 // Add incoming PreHeader from branch around the Loop
208 PN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
209
210 Value *V = PN->getIncomingValueForBlock(Latch);
211 Instruction *I = dyn_cast<Instruction>(V);
212 if (I && L->contains(I))
213 // If value comes from an instruction in the loop add VMap value.
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000214 V = VMap.lookup(I);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000215 // For the instruction out of the loop, constant or undefined value
216 // insert value itself.
217 EpilogPN->addIncoming(V, EpilogLatch);
218
219 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
220 "EpilogPN should have EpilogPreHeader incoming block");
221 // Change EpilogPreHeader incoming block to NewExit.
222 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
223 NewExit);
224 // Now PHIs should look like:
225 // NewExit:
226 // PN = PHI [I, Latch], [undef, PreHeader]
227 // ...
228 // Exit:
229 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
230 }
231
232 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
233 // Update corresponding PHI nodes in epilog loop.
234 for (BasicBlock *Succ : successors(Latch)) {
235 // Skip this as we already updated phis in exit blocks.
236 if (!L->contains(Succ))
237 continue;
238 for (Instruction &BBI : *Succ) {
239 PHINode *PN = dyn_cast<PHINode>(&BBI);
240 // Exit when we passed all PHI nodes.
241 if (!PN)
242 break;
243 // Add new PHI nodes to the loop exit block and update epilog
244 // PHIs with the new PHI values.
245 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
246 NewExit->getFirstNonPHI());
247 // Adding a value to the new PHI node from the unrolling loop preheader.
248 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader);
249 // Adding a value to the new PHI node from the unrolling loop latch.
250 NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch);
251
252 // Update the existing PHI node operand with the value from the new PHI
253 // node. Corresponding instruction in epilog loop should be PHI.
254 PHINode *VPN = cast<PHINode>(VMap[&BBI]);
255 VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
256 }
257 }
258
259 Instruction *InsertPt = NewExit->getTerminator();
260 IRBuilder<> B(InsertPt);
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000261 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000262 assert(Exit && "Loop must have a single exit block only");
263 // Split the exit to maintain loop canonicalization guarantees
264 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
265 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI,
266 PreserveLCSSA);
267 // Add the branch to the exit block (around the unrolling loop)
268 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000269 InsertPt->eraseFromParent();
270}
271
272/// Create a clone of the blocks in a loop and connect them together.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000273/// If CreateRemainderLoop is false, loop structure will not be cloned,
274/// otherwise a new loop will be created including all cloned blocks, and the
275/// iterator of it switches to count NewIter down to 0.
276/// The cloned blocks should be inserted between InsertTop and InsertBot.
277/// If loop structure is cloned InsertTop should be new preheader, InsertBot
278/// new loop exit.
Andrew Trickd04d15292011-12-09 06:19:40 +0000279///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000280static void CloneLoopBlocks(Loop *L, Value *NewIter,
281 const bool CreateRemainderLoop,
282 const bool UseEpilogRemainder,
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000283 BasicBlock *InsertTop, BasicBlock *InsertBot,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000284 BasicBlock *Preheader,
Andrew Trickd04d15292011-12-09 06:19:40 +0000285 std::vector<BasicBlock *> &NewBlocks,
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000286 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Kevin Qin65b07b82015-03-09 07:26:37 +0000287 LoopInfo *LI) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000288 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
Andrew Trickd04d15292011-12-09 06:19:40 +0000289 BasicBlock *Header = L->getHeader();
290 BasicBlock *Latch = L->getLoopLatch();
291 Function *F = Header->getParent();
292 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
293 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000294 Loop *NewLoop = nullptr;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000295 Loop *ParentLoop = L->getParentLoop();
David L Kreitzer188de5a2016-04-05 12:19:35 +0000296 if (CreateRemainderLoop) {
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000297 NewLoop = new Loop();
Kevin Qin65b07b82015-03-09 07:26:37 +0000298 if (ParentLoop)
299 ParentLoop->addChildLoop(NewLoop);
300 else
301 LI->addTopLevelLoop(NewLoop);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000302 }
303
Andrew Trickd04d15292011-12-09 06:19:40 +0000304 // For each block in the original loop, create a new copy,
305 // and update the value map with the newly created values.
306 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000307 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000308 NewBlocks.push_back(NewBB);
309
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000310 if (NewLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000311 NewLoop->addBasicBlockToLoop(NewBB, *LI);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000312 else if (ParentLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000313 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000314
315 VMap[*BB] = NewBB;
316 if (Header == *BB) {
317 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000318 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000319 InsertTop->getTerminator()->setSuccessor(0, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000320 }
Junmo Park502ff662016-01-28 01:23:18 +0000321
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000322 if (Latch == *BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000323 // For the last block, if CreateRemainderLoop is false, create a direct
324 // jump to InsertBot. If not, create a loop back to cloned head.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000325 VMap.erase((*BB)->getTerminator());
326 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
327 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000328 IRBuilder<> Builder(LatchBR);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000329 if (!CreateRemainderLoop) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000330 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000331 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000332 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
333 suffix + ".iter",
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000334 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000335 Value *IdxSub =
336 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
337 NewIdx->getName() + ".sub");
338 Value *IdxCmp =
339 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000340 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000341 NewIdx->addIncoming(NewIter, InsertTop);
342 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000343 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000344 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000345 }
346 }
347
348 // Change the incoming values to the ones defined in the preheader or
349 // cloned loop.
350 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000351 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000352 if (!CreateRemainderLoop) {
353 if (UseEpilogRemainder) {
354 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
355 NewPHI->setIncomingBlock(idx, InsertTop);
356 NewPHI->removeIncomingValue(Latch, false);
357 } else {
358 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
359 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
360 }
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000361 } else {
362 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
363 NewPHI->setIncomingBlock(idx, InsertTop);
364 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
365 idx = NewPHI->getBasicBlockIndex(Latch);
366 Value *InVal = NewPHI->getIncomingValue(idx);
367 NewPHI->setIncomingBlock(idx, NewLatch);
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000368 if (Value *V = VMap.lookup(InVal))
369 NewPHI->setIncomingValue(idx, V);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000370 }
371 }
372 if (NewLoop) {
373 // Add unroll disable metadata to disable future unrolling for this loop.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000374 SmallVector<Metadata *, 4> MDs;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000375 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000376 MDs.push_back(nullptr);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000377 MDNode *LoopID = NewLoop->getLoopID();
378 if (LoopID) {
379 // First remove any existing loop unrolling metadata.
380 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
381 bool IsUnrollMetadata = false;
382 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
383 if (MD) {
384 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
385 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
Andrew Trickd04d15292011-12-09 06:19:40 +0000386 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000387 if (!IsUnrollMetadata)
388 MDs.push_back(LoopID->getOperand(i));
Andrew Trickd04d15292011-12-09 06:19:40 +0000389 }
390 }
391
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000392 LLVMContext &Context = NewLoop->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000393 SmallVector<Metadata *, 1> DisableOperands;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000394 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
395 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000396 MDs.push_back(DisableNode);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000397
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000398 MDNode *NewLoopID = MDNode::get(Context, MDs);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000399 // Set operand 0 to refer to the loop id itself.
400 NewLoopID->replaceOperandWith(0, NewLoopID);
401 NewLoop->setLoopID(NewLoopID);
Andrew Trickd04d15292011-12-09 06:19:40 +0000402 }
403}
404
David L Kreitzer188de5a2016-04-05 12:19:35 +0000405/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000406/// run-time trip-count.
407///
408/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000409/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000410/// to the unroll factor as the number of *extra* copies added).
411/// We assume also that the loop unroll factor is a power-of-two. So, after
412/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000413/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000414/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
415/// the switch instruction is generated.
416///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000417/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000418/// extraiters = tripcount % loopfactor
419/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000420/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000421/// Prol: LoopBody;
422/// extraiters -= 1 // Omitted if unroll factor is 2.
423/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000424/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000425/// Loop:
426/// ...
427/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000428///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000429/// ***Epilog case***
430/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000431/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000432/// unroll_iters = tripcount - extraiters
433/// Loop: LoopBody; (executes unroll_iter times);
434/// unroll_iter -= 1
435/// if (unroll_iter != 0) jump Loop:
436/// LoopExit:
437/// if (extraiters == 0) jump EpilExit:
438/// Epil: LoopBody; (executes extraiters times)
439/// extraiters -= 1 // Omitted if unroll factor is 2.
440/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
441/// EpilExit:
442
443bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
444 bool AllowExpensiveTripCount,
445 bool UseEpilogRemainder,
446 LoopInfo *LI, ScalarEvolution *SE,
447 DominatorTree *DT, bool PreserveLCSSA) {
448 // for now, only unroll loops that contain a single exit
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000449 if (!L->getExitingBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000450 return false;
451
452 // Make sure the loop is in canonical form, and there is a single
453 // exit block only.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000454 if (!L->isLoopSimplifyForm())
455 return false;
456 BasicBlock *Exit = L->getUniqueExitBlock(); // successor out of loop
457 if (!Exit)
Andrew Trickd04d15292011-12-09 06:19:40 +0000458 return false;
459
Sanjay Patele08381a2016-02-08 19:27:33 +0000460 // Use Scalar Evolution to compute the trip count. This allows more loops to
461 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000462 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000463 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000464
Sanjay Patele08381a2016-02-08 19:27:33 +0000465 // Only unroll loops with a computable trip count, and the trip count needs
466 // to be an int value (allowing a pointer type is a TODO item).
Justin Bogner843fb202015-12-15 19:40:57 +0000467 const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000468 if (isa<SCEVCouldNotCompute>(BECountSC) ||
469 !BECountSC->getType()->isIntegerTy())
Andrew Trickd04d15292011-12-09 06:19:40 +0000470 return false;
471
Sanjoy Das11b279a2015-02-18 19:32:25 +0000472 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000473
Sanjay Patele08381a2016-02-08 19:27:33 +0000474 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000475 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000476 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000477 if (isa<SCEVCouldNotCompute>(TripCountSC))
478 return false;
479
Sanjoy Dase178f462015-04-14 03:20:38 +0000480 BasicBlock *Header = L->getHeader();
David L Kreitzer188de5a2016-04-05 12:19:35 +0000481 BasicBlock *PreHeader = L->getLoopPreheader();
482 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000483 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000484 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000485 if (!AllowExpensiveTripCount &&
486 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR))
Sanjoy Dase178f462015-04-14 03:20:38 +0000487 return false;
488
Sanjoy Das11b279a2015-02-18 19:32:25 +0000489 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000490 // comment on ModVal below.
491 if (Log2_32(Count) > BEWidth)
Andrew Trickd04d15292011-12-09 06:19:40 +0000492 return false;
493
Sanjay Patele08381a2016-02-08 19:27:33 +0000494 // If this loop is nested, then the loop unroller changes the code in the
495 // parent loop, so the Scalar Evolution pass needs to be run again.
Andrew Trickd04d15292011-12-09 06:19:40 +0000496 if (Loop *ParentLoop = L->getParentLoop())
Justin Bogner843fb202015-12-15 19:40:57 +0000497 SE->forgetLoop(ParentLoop);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000498
Andrew Trickd04d15292011-12-09 06:19:40 +0000499 BasicBlock *Latch = L->getLoopLatch();
Andrew Trickd04d15292011-12-09 06:19:40 +0000500
David L Kreitzer188de5a2016-04-05 12:19:35 +0000501 // Loop structure is the following:
502 //
503 // PreHeader
504 // Header
505 // ...
506 // Latch
507 // Exit
508
509 BasicBlock *NewPreHeader;
510 BasicBlock *NewExit = nullptr;
511 BasicBlock *PrologExit = nullptr;
512 BasicBlock *EpilogPreHeader = nullptr;
513 BasicBlock *PrologPreHeader = nullptr;
514
515 if (UseEpilogRemainder) {
516 // If epilog remainder
517 // Split PreHeader to insert a branch around loop for unrolling.
518 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
519 NewPreHeader->setName(PreHeader->getName() + ".new");
520 // Split Exit to create phi nodes from branch above.
521 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
522 NewExit = SplitBlockPredecessors(Exit, Preds, ".unr-lcssa",
523 DT, LI, PreserveLCSSA);
524 // Split NewExit to insert epilog remainder loop.
525 EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
526 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
527 } else {
528 // If prolog remainder
529 // Split the original preheader twice to insert prolog remainder loop
530 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
531 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
532 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
533 DT, LI);
534 PrologExit->setName(Header->getName() + ".prol.loopexit");
535 // Split PrologExit to get NewPreHeader.
536 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
537 NewPreHeader->setName(PreHeader->getName() + ".new");
538 }
539 // Loop structure should be the following:
540 // Epilog Prolog
541 //
542 // PreHeader PreHeader
543 // *NewPreHeader *PrologPreHeader
544 // Header *PrologExit
545 // ... *NewPreHeader
546 // Latch Header
547 // *NewExit ...
548 // *EpilogPreHeader Latch
549 // Exit Exit
550
551 // Calculate conditions for branch around loop for unrolling
552 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000553 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000554 // extra iterations = run-time trip count % loop unroll factor
555 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000556 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
557 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000558 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
559 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000560 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000561 Value *ModVal;
562 // Calculate ModVal = (BECount + 1) % Count.
563 // Note that TripCount is BECount + 1.
564 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000565 // When Count is power of 2 we don't BECount for epilog case, however we'll
566 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000567 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000568 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000569 // OR
570 // 2. The addition computing TripCount overflowed.
571 //
572 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
573 // the number of iterations that remain to be run in the original loop is a
574 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
575 // explicitly check this above).
576 } else {
577 // As (BECount + 1) can potentially unsigned overflow we count
578 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
579 Value *ModValTmp = B.CreateURem(BECount,
580 ConstantInt::get(BECount->getType(),
581 Count));
582 Value *ModValAdd = B.CreateAdd(ModValTmp,
583 ConstantInt::get(ModValTmp->getType(), 1));
584 // At that point (BECount % Count) + 1 could be equal to Count.
585 // To handle this case we need to take mod by Count one more time.
586 ModVal = B.CreateURem(ModValAdd,
587 ConstantInt::get(BECount->getType(), Count),
588 "xtraiter");
589 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000590 Value *BranchVal =
591 UseEpilogRemainder ? B.CreateICmpULT(BECount,
592 ConstantInt::get(BECount->getType(),
593 Count - 1)) :
594 B.CreateIsNotNull(ModVal, "lcmp.mod");
595 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
596 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000597 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000598 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000599 PreHeaderBR->eraseFromParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000600 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000601 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000602 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000603 LoopBlocksDFS LoopBlocks(L);
604 LoopBlocks.perform(LI);
605
606 //
607 // For each extra loop iteration, create a copy of the loop's basic blocks
608 // and generate a condition that branches to the copy depending on the
609 // number of 'left over' iterations.
610 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000611 std::vector<BasicBlock *> NewBlocks;
612 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000613
David L Kreitzer188de5a2016-04-05 12:19:35 +0000614 // For unroll factor 2 remainder loop will have 1 iterations.
615 // Do not create 1 iteration loop.
616 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000617
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000618 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
619 // the loop, otherwise we create a cloned loop to execute the extra
620 // iterations. This function adds the appropriate CFG connections.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000621 BasicBlock *InsertBot = UseEpilogRemainder ? Exit : PrologExit;
622 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
623 CloneLoopBlocks(L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop,
624 InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000625
David L Kreitzer188de5a2016-04-05 12:19:35 +0000626 // Insert the cloned blocks into the function.
627 F->getBasicBlockList().splice(InsertBot->getIterator(),
628 F->getBasicBlockList(),
629 NewBlocks[0]->getIterator(),
630 F->end());
631
632 // Loop structure should be the following:
633 // Epilog Prolog
634 //
635 // PreHeader PreHeader
636 // NewPreHeader PrologPreHeader
637 // Header PrologHeader
638 // ... ...
639 // Latch PrologLatch
640 // NewExit PrologExit
641 // EpilogPreHeader NewPreHeader
642 // EpilogHeader Header
643 // ... ...
644 // EpilogLatch Latch
645 // Exit Exit
Andrew Trickd04d15292011-12-09 06:19:40 +0000646
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000647 // Rewrite the cloned instruction operands to use the values created when the
648 // clone is created.
649 for (BasicBlock *BB : NewBlocks) {
650 for (Instruction &I : *BB) {
651 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000652 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000653 }
654 }
655
David L Kreitzer188de5a2016-04-05 12:19:35 +0000656 if (UseEpilogRemainder) {
657 // Connect the epilog code to the original loop and update the
658 // PHI functions.
659 ConnectEpilog(L, ModVal, NewExit, Exit, PreHeader,
660 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
661 PreserveLCSSA);
662
663 // Update counter in loop for unrolling.
664 // I should be multiply of Count.
665 IRBuilder<> B2(NewPreHeader->getTerminator());
666 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
667 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
668 B2.SetInsertPoint(LatchBR);
669 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
670 Header->getFirstNonPHI());
671 Value *IdxSub =
672 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
673 NewIdx->getName() + ".nsub");
674 Value *IdxCmp;
675 if (LatchBR->getSuccessor(0) == Header)
676 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
677 else
678 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
679 NewIdx->addIncoming(TestVal, NewPreHeader);
680 NewIdx->addIncoming(IdxSub, Latch);
681 LatchBR->setCondition(IdxCmp);
682 } else {
683 // Connect the prolog code to the original loop and update the
684 // PHI functions.
685 ConnectProlog(L, BECount, Count, PrologExit, PreHeader, NewPreHeader,
686 VMap, DT, LI, PreserveLCSSA);
687 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000688 NumRuntimeUnrolled++;
689 return true;
690}