1
//===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
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
14
// The functions in this file are used to generate extra code when the
15
// 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.
18
// The current strategy generates an if-then-else sequence prior to the
19
// unrolled loop to execute the 'left over' iterations. Other strategies
20
// include generate a loop before or after the unrolled loop.
22
//===----------------------------------------------------------------------===//
24
#define DEBUG_TYPE "loop-unroll"
25
#include "llvm/Transforms/Utils/UnrollLoop.h"
26
#include "llvm/BasicBlock.h"
27
#include "llvm/ADT/Statistic.h"
28
#include "llvm/Analysis/LoopIterator.h"
29
#include "llvm/Analysis/LoopPass.h"
30
#include "llvm/Analysis/ScalarEvolution.h"
31
#include "llvm/Analysis/ScalarEvolutionExpander.h"
32
#include "llvm/Support/Debug.h"
33
#include "llvm/Support/raw_ostream.h"
34
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
35
#include "llvm/Transforms/Utils/Cloning.h"
40
STATISTIC(NumRuntimeUnrolled,
41
"Number of loops unrolled with run-time trip counts");
43
/// Connect the unrolling prolog code to the original loop.
44
/// The unrolling prolog code contains code to execute the
45
/// 'extra' iterations if the run-time trip count modulo the
46
/// unroll count is non-zero.
48
/// This function performs the following:
49
/// - Create PHI nodes at prolog end block to combine values
50
/// that exit the prolog code and jump around the prolog.
51
/// - Add a PHI operand to a PHI node at the loop exit block
52
/// for values that exit the prolog and go around the loop.
53
/// - Branch around the original loop if the trip count is less
54
/// than the unroll factor.
56
static void ConnectProlog(Loop *L, Value *TripCount, unsigned Count,
57
BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
58
BasicBlock *OrigPH, BasicBlock *NewPH,
59
ValueToValueMapTy &LVMap, Pass *P) {
60
BasicBlock *Latch = L->getLoopLatch();
61
assert(Latch != 0 && "Loop must have a latch");
63
// Create a PHI node for each outgoing value from the original loop
64
// (which means it is an outgoing value from the prolog code too).
65
// The new PHI node is inserted in the prolog end basic block.
66
// The new PHI name is added as an operand of a PHI node in either
67
// the loop header or the loop exit block.
68
for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
70
for (BasicBlock::iterator BBI = (*SBI)->begin();
71
PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
73
// Add a new PHI node to the prolog end block and add the
74
// appropriate incoming values.
75
PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
76
PrologEnd->getTerminator());
77
// Adding a value to the new PHI node from the original loop preheader.
78
// This is the value that skips all the prolog code.
79
if (L->contains(PN)) {
80
NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
82
NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
85
Value *V = PN->getIncomingValueForBlock(Latch);
86
if (Instruction *I = dyn_cast<Instruction>(V)) {
91
// Adding a value to the new PHI node from the last prolog block
93
NewPN->addIncoming(V, LastPrologBB);
95
// Update the existing PHI node operand with the value from the
96
// new PHI node. How this is done depends on if the existing
97
// PHI node is in the original loop block, or the exit block.
98
if (L->contains(PN)) {
99
PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
101
PN->addIncoming(NewPN, PrologEnd);
106
// Create a branch around the orignal loop, which is taken if the
107
// trip count is less than the unroll factor.
108
Instruction *InsertPt = PrologEnd->getTerminator();
109
Instruction *BrLoopExit =
110
new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, TripCount,
111
ConstantInt::get(TripCount->getType(), Count));
112
BasicBlock *Exit = L->getUniqueExitBlock();
113
assert(Exit != 0 && "Loop must have a single exit block only");
114
// Split the exit to maintain loop canonicalization guarantees
115
SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
116
if (!Exit->isLandingPad()) {
117
SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", P);
119
SmallVector<BasicBlock*, 2> NewBBs;
120
SplitLandingPadPredecessors(Exit, Preds, ".unr1-lcssa", ".unr2-lcssa",
123
// Add the branch to the exit block (around the unrolled loop)
124
BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
125
InsertPt->eraseFromParent();
128
/// Create a clone of the blocks in a loop and connect them together.
129
/// This function doesn't create a clone of the loop structure.
131
/// There are two value maps that are defined and used. VMap is
132
/// for the values in the current loop instance. LVMap contains
133
/// the values from the last loop instance. We need the LVMap values
134
/// to update the inital values for the current loop instance.
136
static void CloneLoopBlocks(Loop *L,
138
BasicBlock *InsertTop,
139
BasicBlock *InsertBot,
140
std::vector<BasicBlock *> &NewBlocks,
141
LoopBlocksDFS &LoopBlocks,
142
ValueToValueMapTy &VMap,
143
ValueToValueMapTy &LVMap,
146
BasicBlock *Preheader = L->getLoopPreheader();
147
BasicBlock *Header = L->getHeader();
148
BasicBlock *Latch = L->getLoopLatch();
149
Function *F = Header->getParent();
150
LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
151
LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
152
// For each block in the original loop, create a new copy,
153
// and update the value map with the newly created values.
154
for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
155
BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".unr", F);
156
NewBlocks.push_back(NewBB);
158
if (Loop *ParentLoop = L->getParentLoop())
159
ParentLoop->addBasicBlockToLoop(NewBB, LI->getBase());
163
// For the first block, add a CFG connection to this newly
165
InsertTop->getTerminator()->setSuccessor(0, NewBB);
167
// Change the incoming values to the ones defined in the
168
// previously cloned loop.
169
for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
170
PHINode *NewPHI = cast<PHINode>(VMap[I]);
172
// We replace the first phi node with the value from the preheader
173
VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
174
NewBB->getInstList().erase(NewPHI);
176
// Update VMap with values from the previous block
177
unsigned idx = NewPHI->getBasicBlockIndex(Latch);
178
Value *InVal = NewPHI->getIncomingValue(idx);
179
if (Instruction *I = dyn_cast<Instruction>(InVal))
181
InVal = LVMap[InVal];
182
NewPHI->setIncomingValue(idx, InVal);
183
NewPHI->setIncomingBlock(idx, InsertTop);
189
VMap.erase((*BB)->getTerminator());
190
NewBB->getTerminator()->eraseFromParent();
191
BranchInst::Create(InsertBot, NewBB);
194
// LastValueMap is updated with the values for the current loop
195
// which are used the next time this function is called.
196
for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
198
LVMap[VI->first] = VI->second;
202
/// Insert code in the prolog code when unrolling a loop with a
203
/// run-time trip-count.
205
/// This method assumes that the loop unroll factor is total number
206
/// of loop bodes in the loop after unrolling. (Some folks refer
207
/// to the unroll factor as the number of *extra* copies added).
208
/// We assume also that the loop unroll factor is a power-of-two. So, after
209
/// unrolling the loop, the number of loop bodies executed is 2,
210
/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
211
/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
212
/// the switch instruction is generated.
214
/// extraiters = tripcount % loopfactor
215
/// if (extraiters == 0) jump Loop:
216
/// if (extraiters == loopfactor) jump L1
217
/// if (extraiters == loopfactor-1) jump L2
222
/// if tripcount < loopfactor jump End
227
bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
228
LPPassManager *LPM) {
229
// for now, only unroll loops that contain a single exit
230
if (!L->getExitingBlock())
233
// Make sure the loop is in canonical form, and there is a single
235
if (!L->isLoopSimplifyForm() || L->getUniqueExitBlock() == 0)
238
// Use Scalar Evolution to compute the trip count. This allows more
239
// loops to be unrolled than relying on induction var simplification
240
ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
244
// Only unroll loops with a computable trip count and the trip count needs
245
// to be an int value (allowing a pointer type is a TODO item)
246
const SCEV *BECount = SE->getBackedgeTakenCount(L);
247
if (isa<SCEVCouldNotCompute>(BECount) || !BECount->getType()->isIntegerTy())
250
// Add 1 since the backedge count doesn't include the first loop iteration
251
const SCEV *TripCountSC =
252
SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1));
253
if (isa<SCEVCouldNotCompute>(TripCountSC))
256
// We only handle cases when the unroll factor is a power of 2.
257
// Count is the loop unroll factor, the number of extra copies added + 1.
258
if ((Count & (Count-1)) != 0)
261
// If this loop is nested, then the loop unroller changes the code in
262
// parent loop, so the Scalar Evolution pass needs to be run again
263
if (Loop *ParentLoop = L->getParentLoop())
264
SE->forgetLoop(ParentLoop);
266
BasicBlock *PH = L->getLoopPreheader();
267
BasicBlock *Header = L->getHeader();
268
BasicBlock *Latch = L->getLoopLatch();
269
// It helps to splits the original preheader twice, one for the end of the
270
// prolog code and one for a new loop preheader
271
BasicBlock *PEnd = SplitEdge(PH, Header, LPM->getAsPass());
272
BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), LPM->getAsPass());
273
BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
275
// Compute the number of extra iterations required, which is:
276
// extra iterations = run-time trip count % (loop unroll factor + 1)
277
SCEVExpander Expander(*SE, "loop-unroll");
278
Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
280
Type *CountTy = TripCount->getType();
281
BinaryOperator *ModVal =
282
BinaryOperator::CreateURem(TripCount,
283
ConstantInt::get(CountTy, Count),
285
ModVal->insertBefore(PreHeaderBR);
287
// Check if for no extra iterations, then jump to unrolled loop
288
Value *BranchVal = new ICmpInst(PreHeaderBR,
289
ICmpInst::ICMP_NE, ModVal,
290
ConstantInt::get(CountTy, 0), "lcmp");
291
// Branch to either the extra iterations or the unrolled loop
292
// We will fix up the true branch label when adding loop body copies
293
BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
294
assert(PreHeaderBR->isUnconditional() &&
295
PreHeaderBR->getSuccessor(0) == PEnd &&
296
"CFG edges in Preheader are not correct");
297
PreHeaderBR->eraseFromParent();
299
ValueToValueMapTy LVMap;
300
Function *F = Header->getParent();
301
// These variables are used to update the CFG links in each iteration
302
BasicBlock *CompareBB = 0;
303
BasicBlock *LastLoopBB = PH;
304
// Get an ordered list of blocks in the loop to help with the ordering of the
305
// cloned blocks in the prolog code
306
LoopBlocksDFS LoopBlocks(L);
307
LoopBlocks.perform(LI);
310
// For each extra loop iteration, create a copy of the loop's basic blocks
311
// and generate a condition that branches to the copy depending on the
312
// number of 'left over' iterations.
314
for (unsigned leftOverIters = Count-1; leftOverIters > 0; --leftOverIters) {
315
std::vector<BasicBlock*> NewBlocks;
316
ValueToValueMapTy VMap;
318
// Clone all the basic blocks in the loop, but we don't clone the loop
319
// This function adds the appropriate CFG connections.
320
CloneLoopBlocks(L, (leftOverIters == Count-1), LastLoopBB, PEnd, NewBlocks,
321
LoopBlocks, VMap, LVMap, LI);
322
LastLoopBB = cast<BasicBlock>(VMap[Latch]);
324
// Insert the cloned blocks into function just before the original loop
325
F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(),
326
NewBlocks[0], F->end());
328
// Generate the code for the comparison which determines if the loop
329
// prolog code needs to be executed.
330
if (leftOverIters == Count-1) {
331
// There is no compare block for the fall-thru case when for the last
332
// left over iteration
333
CompareBB = NewBlocks[0];
335
// Create a new block for the comparison
336
BasicBlock *NewBB = BasicBlock::Create(CompareBB->getContext(), "unr.cmp",
338
if (Loop *ParentLoop = L->getParentLoop()) {
339
// Add the new block to the parent loop, if needed
340
ParentLoop->addBasicBlockToLoop(NewBB, LI->getBase());
343
// The comparison w/ the extra iteration value and branch
344
Value *BranchVal = new ICmpInst(*NewBB, ICmpInst::ICMP_EQ, ModVal,
345
ConstantInt::get(CountTy, leftOverIters),
347
// Branch to either the extra iterations or the unrolled loop
348
BranchInst::Create(NewBlocks[0], CompareBB,
351
PH->getTerminator()->setSuccessor(0, NewBB);
352
VMap[NewPH] = CompareBB;
355
// Rewrite the cloned instruction operands to use the values
356
// created when the clone is created.
357
for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
358
for (BasicBlock::iterator I = NewBlocks[i]->begin(),
359
E = NewBlocks[i]->end(); I != E; ++I) {
360
RemapInstruction(I, VMap,
361
RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
366
// Connect the prolog code to the original loop and update the
368
ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, LVMap,
370
NumRuntimeUnrolled++;