blob: 861a50cf354d821424f7894987e68a6ddfa2ae02 [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
Sanjay Patele08381a2016-02-08 19:27:33 +0000115 // Create a branch around the original loop, which is taken if there are no
Sanjoy Das11b279a2015-02-18 19:32:25 +0000116 // iterations remaining to be executed after running the prologue.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000117 Instruction *InsertPt = PrologExit->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000118 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000119
120 assert(Count != 0 && "nonsensical Count!");
121
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000122 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
123 // This means %xtraiter is (BECount + 1) and all of the iterations of this
124 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
125 // then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000126 Value *BrLoopExit =
127 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000128 BasicBlock *Exit = L->getUniqueExitBlock();
Craig Toppere73658d2014-04-28 04:05:08 +0000129 assert(Exit && "Loop must have a single exit block only");
Andrew Trickd04d15292011-12-09 06:19:40 +0000130 // Split the exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000131 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
Chandler Carruth96ada252015-07-22 09:52:54 +0000132 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI,
Justin Bogner843fb202015-12-15 19:40:57 +0000133 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000134 // Add the branch to the exit block (around the unrolled loop)
David L Kreitzer188de5a2016-04-05 12:19:35 +0000135 B.CreateCondBr(BrLoopExit, Exit, NewPreHeader);
136 InsertPt->eraseFromParent();
137}
138
139/// Connect the unrolling epilog code to the original loop.
140/// The unrolling epilog code contains code to execute the
141/// 'extra' iterations if the run-time trip count modulo the
142/// unroll count is non-zero.
143///
144/// This function performs the following:
145/// - Update PHI nodes at the unrolling loop exit and epilog loop exit
146/// - Create PHI nodes at the unrolling loop exit to combine
147/// values that exit the unrolling loop code and jump around it.
148/// - Update PHI operands in the epilog loop by the new PHI nodes
149/// - Branch around the epilog loop if extra iters (ModVal) is zero.
150///
151static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
152 BasicBlock *Exit, BasicBlock *PreHeader,
153 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
154 ValueToValueMapTy &VMap, DominatorTree *DT,
155 LoopInfo *LI, bool PreserveLCSSA) {
156 BasicBlock *Latch = L->getLoopLatch();
157 assert(Latch && "Loop must have a latch");
158 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
159
160 // Loop structure should be the following:
161 //
162 // PreHeader
163 // NewPreHeader
164 // Header
165 // ...
166 // Latch
167 // NewExit (PN)
168 // EpilogPreHeader
169 // EpilogHeader
170 // ...
171 // EpilogLatch
172 // Exit (EpilogPN)
173
174 // Update PHI nodes at NewExit and Exit.
175 for (Instruction &BBI : *NewExit) {
176 PHINode *PN = dyn_cast<PHINode>(&BBI);
177 // Exit when we passed all PHI nodes.
178 if (!PN)
179 break;
180 // PN should be used in another PHI located in Exit block as
181 // Exit was split by SplitBlockPredecessors into Exit and NewExit
182 // Basicaly it should look like:
183 // NewExit:
184 // PN = PHI [I, Latch]
185 // ...
186 // Exit:
187 // EpilogPN = PHI [PN, EpilogPreHeader]
188 //
189 // There is EpilogPreHeader incoming block instead of NewExit as
190 // NewExit was spilt 1 more time to get EpilogPreHeader.
191 assert(PN->hasOneUse() && "The phi should have 1 use");
192 PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser());
193 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
194
195 // Add incoming PreHeader from branch around the Loop
196 PN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
197
198 Value *V = PN->getIncomingValueForBlock(Latch);
199 Instruction *I = dyn_cast<Instruction>(V);
200 if (I && L->contains(I))
201 // If value comes from an instruction in the loop add VMap value.
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000202 V = VMap.lookup(I);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000203 // For the instruction out of the loop, constant or undefined value
204 // insert value itself.
205 EpilogPN->addIncoming(V, EpilogLatch);
206
207 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
208 "EpilogPN should have EpilogPreHeader incoming block");
209 // Change EpilogPreHeader incoming block to NewExit.
210 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
211 NewExit);
212 // Now PHIs should look like:
213 // NewExit:
214 // PN = PHI [I, Latch], [undef, PreHeader]
215 // ...
216 // Exit:
217 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
218 }
219
220 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
221 // Update corresponding PHI nodes in epilog loop.
222 for (BasicBlock *Succ : successors(Latch)) {
223 // Skip this as we already updated phis in exit blocks.
224 if (!L->contains(Succ))
225 continue;
226 for (Instruction &BBI : *Succ) {
227 PHINode *PN = dyn_cast<PHINode>(&BBI);
228 // Exit when we passed all PHI nodes.
229 if (!PN)
230 break;
231 // Add new PHI nodes to the loop exit block and update epilog
232 // PHIs with the new PHI values.
233 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
234 NewExit->getFirstNonPHI());
235 // Adding a value to the new PHI node from the unrolling loop preheader.
236 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader);
237 // Adding a value to the new PHI node from the unrolling loop latch.
238 NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch);
239
240 // Update the existing PHI node operand with the value from the new PHI
241 // node. Corresponding instruction in epilog loop should be PHI.
242 PHINode *VPN = cast<PHINode>(VMap[&BBI]);
243 VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
244 }
245 }
246
247 Instruction *InsertPt = NewExit->getTerminator();
248 IRBuilder<> B(InsertPt);
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000249 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000250 assert(Exit && "Loop must have a single exit block only");
251 // Split the exit to maintain loop canonicalization guarantees
252 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
253 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI,
254 PreserveLCSSA);
255 // Add the branch to the exit block (around the unrolling loop)
256 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000257 InsertPt->eraseFromParent();
258}
259
260/// Create a clone of the blocks in a loop and connect them together.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000261/// If CreateRemainderLoop is false, loop structure will not be cloned,
262/// otherwise a new loop will be created including all cloned blocks, and the
263/// iterator of it switches to count NewIter down to 0.
264/// The cloned blocks should be inserted between InsertTop and InsertBot.
265/// If loop structure is cloned InsertTop should be new preheader, InsertBot
266/// new loop exit.
Andrew Trickd04d15292011-12-09 06:19:40 +0000267///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000268static void CloneLoopBlocks(Loop *L, Value *NewIter,
269 const bool CreateRemainderLoop,
270 const bool UseEpilogRemainder,
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000271 BasicBlock *InsertTop, BasicBlock *InsertBot,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000272 BasicBlock *Preheader,
Andrew Trickd04d15292011-12-09 06:19:40 +0000273 std::vector<BasicBlock *> &NewBlocks,
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000274 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Kevin Qin65b07b82015-03-09 07:26:37 +0000275 LoopInfo *LI) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000276 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
Andrew Trickd04d15292011-12-09 06:19:40 +0000277 BasicBlock *Header = L->getHeader();
278 BasicBlock *Latch = L->getLoopLatch();
279 Function *F = Header->getParent();
280 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
281 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000282 Loop *NewLoop = nullptr;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000283 Loop *ParentLoop = L->getParentLoop();
David L Kreitzer188de5a2016-04-05 12:19:35 +0000284 if (CreateRemainderLoop) {
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000285 NewLoop = new Loop();
Kevin Qin65b07b82015-03-09 07:26:37 +0000286 if (ParentLoop)
287 ParentLoop->addChildLoop(NewLoop);
288 else
289 LI->addTopLevelLoop(NewLoop);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000290 }
291
Andrew Trickd04d15292011-12-09 06:19:40 +0000292 // For each block in the original loop, create a new copy,
293 // and update the value map with the newly created values.
294 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000295 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000296 NewBlocks.push_back(NewBB);
297
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000298 if (NewLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000299 NewLoop->addBasicBlockToLoop(NewBB, *LI);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000300 else if (ParentLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000301 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000302
303 VMap[*BB] = NewBB;
304 if (Header == *BB) {
305 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000306 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000307 InsertTop->getTerminator()->setSuccessor(0, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000308 }
Junmo Park502ff662016-01-28 01:23:18 +0000309
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000310 if (Latch == *BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000311 // For the last block, if CreateRemainderLoop is false, create a direct
312 // jump to InsertBot. If not, create a loop back to cloned head.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000313 VMap.erase((*BB)->getTerminator());
314 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
315 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000316 IRBuilder<> Builder(LatchBR);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000317 if (!CreateRemainderLoop) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000318 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000319 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000320 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
321 suffix + ".iter",
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000322 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000323 Value *IdxSub =
324 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
325 NewIdx->getName() + ".sub");
326 Value *IdxCmp =
327 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000328 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000329 NewIdx->addIncoming(NewIter, InsertTop);
330 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000331 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000332 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000333 }
334 }
335
336 // Change the incoming values to the ones defined in the preheader or
337 // cloned loop.
338 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000339 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000340 if (!CreateRemainderLoop) {
341 if (UseEpilogRemainder) {
342 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
343 NewPHI->setIncomingBlock(idx, InsertTop);
344 NewPHI->removeIncomingValue(Latch, false);
345 } else {
346 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
347 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
348 }
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000349 } else {
350 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
351 NewPHI->setIncomingBlock(idx, InsertTop);
352 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
353 idx = NewPHI->getBasicBlockIndex(Latch);
354 Value *InVal = NewPHI->getIncomingValue(idx);
355 NewPHI->setIncomingBlock(idx, NewLatch);
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000356 if (Value *V = VMap.lookup(InVal))
357 NewPHI->setIncomingValue(idx, V);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000358 }
359 }
360 if (NewLoop) {
361 // Add unroll disable metadata to disable future unrolling for this loop.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000362 SmallVector<Metadata *, 4> MDs;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000363 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000364 MDs.push_back(nullptr);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000365 MDNode *LoopID = NewLoop->getLoopID();
366 if (LoopID) {
367 // First remove any existing loop unrolling metadata.
368 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
369 bool IsUnrollMetadata = false;
370 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
371 if (MD) {
372 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
373 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
Andrew Trickd04d15292011-12-09 06:19:40 +0000374 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000375 if (!IsUnrollMetadata)
376 MDs.push_back(LoopID->getOperand(i));
Andrew Trickd04d15292011-12-09 06:19:40 +0000377 }
378 }
379
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000380 LLVMContext &Context = NewLoop->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000381 SmallVector<Metadata *, 1> DisableOperands;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000382 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
383 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000384 MDs.push_back(DisableNode);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000385
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000386 MDNode *NewLoopID = MDNode::get(Context, MDs);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000387 // Set operand 0 to refer to the loop id itself.
388 NewLoopID->replaceOperandWith(0, NewLoopID);
389 NewLoop->setLoopID(NewLoopID);
Andrew Trickd04d15292011-12-09 06:19:40 +0000390 }
391}
392
David L Kreitzer188de5a2016-04-05 12:19:35 +0000393/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000394/// run-time trip-count.
395///
396/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000397/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000398/// to the unroll factor as the number of *extra* copies added).
399/// We assume also that the loop unroll factor is a power-of-two. So, after
400/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000401/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000402/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
403/// the switch instruction is generated.
404///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000405/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000406/// extraiters = tripcount % loopfactor
407/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000408/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000409/// Prol: LoopBody;
410/// extraiters -= 1 // Omitted if unroll factor is 2.
411/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000412/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000413/// Loop:
414/// ...
415/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000416///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000417/// ***Epilog case***
418/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000419/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000420/// unroll_iters = tripcount - extraiters
421/// Loop: LoopBody; (executes unroll_iter times);
422/// unroll_iter -= 1
423/// if (unroll_iter != 0) jump Loop:
424/// LoopExit:
425/// if (extraiters == 0) jump EpilExit:
426/// Epil: LoopBody; (executes extraiters times)
427/// extraiters -= 1 // Omitted if unroll factor is 2.
428/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
429/// EpilExit:
430
431bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
432 bool AllowExpensiveTripCount,
433 bool UseEpilogRemainder,
434 LoopInfo *LI, ScalarEvolution *SE,
435 DominatorTree *DT, bool PreserveLCSSA) {
436 // for now, only unroll loops that contain a single exit
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000437 if (!L->getExitingBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000438 return false;
439
440 // Make sure the loop is in canonical form, and there is a single
441 // exit block only.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000442 if (!L->isLoopSimplifyForm())
443 return false;
444 BasicBlock *Exit = L->getUniqueExitBlock(); // successor out of loop
445 if (!Exit)
Andrew Trickd04d15292011-12-09 06:19:40 +0000446 return false;
447
Sanjay Patele08381a2016-02-08 19:27:33 +0000448 // Use Scalar Evolution to compute the trip count. This allows more loops to
449 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000450 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000451 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000452
Sanjay Patele08381a2016-02-08 19:27:33 +0000453 // Only unroll loops with a computable trip count, and the trip count needs
454 // to be an int value (allowing a pointer type is a TODO item).
Justin Bogner843fb202015-12-15 19:40:57 +0000455 const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000456 if (isa<SCEVCouldNotCompute>(BECountSC) ||
457 !BECountSC->getType()->isIntegerTy())
Andrew Trickd04d15292011-12-09 06:19:40 +0000458 return false;
459
Sanjoy Das11b279a2015-02-18 19:32:25 +0000460 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000461
Sanjay Patele08381a2016-02-08 19:27:33 +0000462 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000463 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000464 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000465 if (isa<SCEVCouldNotCompute>(TripCountSC))
466 return false;
467
Sanjoy Dase178f462015-04-14 03:20:38 +0000468 BasicBlock *Header = L->getHeader();
David L Kreitzer188de5a2016-04-05 12:19:35 +0000469 BasicBlock *PreHeader = L->getLoopPreheader();
470 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000471 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000472 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000473 if (!AllowExpensiveTripCount &&
474 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR))
Sanjoy Dase178f462015-04-14 03:20:38 +0000475 return false;
476
Sanjoy Das11b279a2015-02-18 19:32:25 +0000477 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000478 // comment on ModVal below.
479 if (Log2_32(Count) > BEWidth)
Andrew Trickd04d15292011-12-09 06:19:40 +0000480 return false;
481
Sanjay Patele08381a2016-02-08 19:27:33 +0000482 // If this loop is nested, then the loop unroller changes the code in the
483 // parent loop, so the Scalar Evolution pass needs to be run again.
Andrew Trickd04d15292011-12-09 06:19:40 +0000484 if (Loop *ParentLoop = L->getParentLoop())
Justin Bogner843fb202015-12-15 19:40:57 +0000485 SE->forgetLoop(ParentLoop);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000486
Andrew Trickd04d15292011-12-09 06:19:40 +0000487 BasicBlock *Latch = L->getLoopLatch();
Andrew Trickd04d15292011-12-09 06:19:40 +0000488
David L Kreitzer188de5a2016-04-05 12:19:35 +0000489 // Loop structure is the following:
490 //
491 // PreHeader
492 // Header
493 // ...
494 // Latch
495 // Exit
496
497 BasicBlock *NewPreHeader;
498 BasicBlock *NewExit = nullptr;
499 BasicBlock *PrologExit = nullptr;
500 BasicBlock *EpilogPreHeader = nullptr;
501 BasicBlock *PrologPreHeader = nullptr;
502
503 if (UseEpilogRemainder) {
504 // If epilog remainder
505 // Split PreHeader to insert a branch around loop for unrolling.
506 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
507 NewPreHeader->setName(PreHeader->getName() + ".new");
508 // Split Exit to create phi nodes from branch above.
509 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
510 NewExit = SplitBlockPredecessors(Exit, Preds, ".unr-lcssa",
511 DT, LI, PreserveLCSSA);
512 // Split NewExit to insert epilog remainder loop.
513 EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
514 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
515 } else {
516 // If prolog remainder
517 // Split the original preheader twice to insert prolog remainder loop
518 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
519 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
520 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
521 DT, LI);
522 PrologExit->setName(Header->getName() + ".prol.loopexit");
523 // Split PrologExit to get NewPreHeader.
524 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
525 NewPreHeader->setName(PreHeader->getName() + ".new");
526 }
527 // Loop structure should be the following:
528 // Epilog Prolog
529 //
530 // PreHeader PreHeader
531 // *NewPreHeader *PrologPreHeader
532 // Header *PrologExit
533 // ... *NewPreHeader
534 // Latch Header
535 // *NewExit ...
536 // *EpilogPreHeader Latch
537 // Exit Exit
538
539 // Calculate conditions for branch around loop for unrolling
540 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000541 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000542 // extra iterations = run-time trip count % loop unroll factor
543 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000544 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
545 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000546 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
547 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000548 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000549 Value *ModVal;
550 // Calculate ModVal = (BECount + 1) % Count.
551 // Note that TripCount is BECount + 1.
552 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000553 // When Count is power of 2 we don't BECount for epilog case, however we'll
554 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000555 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000556 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000557 // OR
558 // 2. The addition computing TripCount overflowed.
559 //
560 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
561 // the number of iterations that remain to be run in the original loop is a
562 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
563 // explicitly check this above).
564 } else {
565 // As (BECount + 1) can potentially unsigned overflow we count
566 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
567 Value *ModValTmp = B.CreateURem(BECount,
568 ConstantInt::get(BECount->getType(),
569 Count));
570 Value *ModValAdd = B.CreateAdd(ModValTmp,
571 ConstantInt::get(ModValTmp->getType(), 1));
572 // At that point (BECount % Count) + 1 could be equal to Count.
573 // To handle this case we need to take mod by Count one more time.
574 ModVal = B.CreateURem(ModValAdd,
575 ConstantInt::get(BECount->getType(), Count),
576 "xtraiter");
577 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000578 Value *BranchVal =
579 UseEpilogRemainder ? B.CreateICmpULT(BECount,
580 ConstantInt::get(BECount->getType(),
581 Count - 1)) :
582 B.CreateIsNotNull(ModVal, "lcmp.mod");
583 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
584 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000585 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000586 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000587 PreHeaderBR->eraseFromParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000588 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000589 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000590 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000591 LoopBlocksDFS LoopBlocks(L);
592 LoopBlocks.perform(LI);
593
594 //
595 // For each extra loop iteration, create a copy of the loop's basic blocks
596 // and generate a condition that branches to the copy depending on the
597 // number of 'left over' iterations.
598 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000599 std::vector<BasicBlock *> NewBlocks;
600 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000601
David L Kreitzer188de5a2016-04-05 12:19:35 +0000602 // For unroll factor 2 remainder loop will have 1 iterations.
603 // Do not create 1 iteration loop.
604 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000605
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000606 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
607 // the loop, otherwise we create a cloned loop to execute the extra
608 // iterations. This function adds the appropriate CFG connections.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000609 BasicBlock *InsertBot = UseEpilogRemainder ? Exit : PrologExit;
610 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
611 CloneLoopBlocks(L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop,
612 InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000613
David L Kreitzer188de5a2016-04-05 12:19:35 +0000614 // Insert the cloned blocks into the function.
615 F->getBasicBlockList().splice(InsertBot->getIterator(),
616 F->getBasicBlockList(),
617 NewBlocks[0]->getIterator(),
618 F->end());
619
620 // Loop structure should be the following:
621 // Epilog Prolog
622 //
623 // PreHeader PreHeader
624 // NewPreHeader PrologPreHeader
625 // Header PrologHeader
626 // ... ...
627 // Latch PrologLatch
628 // NewExit PrologExit
629 // EpilogPreHeader NewPreHeader
630 // EpilogHeader Header
631 // ... ...
632 // EpilogLatch Latch
633 // Exit Exit
Andrew Trickd04d15292011-12-09 06:19:40 +0000634
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000635 // Rewrite the cloned instruction operands to use the values created when the
636 // clone is created.
637 for (BasicBlock *BB : NewBlocks) {
638 for (Instruction &I : *BB) {
639 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000640 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000641 }
642 }
643
David L Kreitzer188de5a2016-04-05 12:19:35 +0000644 if (UseEpilogRemainder) {
645 // Connect the epilog code to the original loop and update the
646 // PHI functions.
647 ConnectEpilog(L, ModVal, NewExit, Exit, PreHeader,
648 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
649 PreserveLCSSA);
650
651 // Update counter in loop for unrolling.
652 // I should be multiply of Count.
653 IRBuilder<> B2(NewPreHeader->getTerminator());
654 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
655 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
656 B2.SetInsertPoint(LatchBR);
657 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
658 Header->getFirstNonPHI());
659 Value *IdxSub =
660 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
661 NewIdx->getName() + ".nsub");
662 Value *IdxCmp;
663 if (LatchBR->getSuccessor(0) == Header)
664 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
665 else
666 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
667 NewIdx->addIncoming(TestVal, NewPreHeader);
668 NewIdx->addIncoming(IdxSub, Latch);
669 LatchBR->setCondition(IdxCmp);
670 } else {
671 // Connect the prolog code to the original loop and update the
672 // PHI functions.
673 ConnectProlog(L, BECount, Count, PrologExit, PreHeader, NewPreHeader,
674 VMap, DT, LI, PreserveLCSSA);
675 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000676 NumRuntimeUnrolled++;
677 return true;
678}