blob: eaef32ce2ccbe8d77234187f88e02bae227f3ced [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
Andrew Trickd04d15292011-12-09 06:19:40 +000019// unrolled loop to execute the 'left over' iterations. Other strategies
20// include generate a loop before or after the unrolled loop.
21//
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,
Andrew Trickd04d15292011-12-09 06:19:40 +000063 BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
64 BasicBlock *OrigPH, BasicBlock *NewPH,
Chandler Carruth96ada252015-07-22 09:52:54 +000065 ValueToValueMapTy &VMap, DominatorTree *DT,
66 LoopInfo *LI, Pass *P) {
Andrew Trickd04d15292011-12-09 06:19:40 +000067 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000068 assert(Latch && "Loop must have a 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.
73 // The new PHI name is added as an operand of a PHI node in either
74 // the loop header or the loop exit block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +000075 for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
76 SBI != SBE; ++SBI) {
77 for (BasicBlock::iterator BBI = (*SBI)->begin();
Andrew Trickd04d15292011-12-09 06:19:40 +000078 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
79
80 // Add a new PHI node to the prolog end block and add the
81 // appropriate incoming values.
82 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
83 PrologEnd->getTerminator());
84 // Adding a value to the new PHI node from the original loop preheader.
85 // This is the value that skips all the prolog code.
86 if (L->contains(PN)) {
87 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
88 } else {
David Majnemer453f7a12015-07-01 05:38:07 +000089 NewPN->addIncoming(UndefValue::get(PN->getType()), OrigPH);
Andrew Trickd04d15292011-12-09 06:19:40 +000090 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +000091
92 Value *V = PN->getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +000093 if (Instruction *I = dyn_cast<Instruction>(V)) {
94 if (L->contains(I)) {
Kevin Qinfc02e3c2014-09-29 11:15:00 +000095 V = VMap[I];
Andrew Trickd04d15292011-12-09 06:19:40 +000096 }
97 }
98 // Adding a value to the new PHI node from the last prolog block
99 // that was created.
100 NewPN->addIncoming(V, LastPrologBB);
101
102 // Update the existing PHI node operand with the value from the
103 // new PHI node. How this is done depends on if the existing
104 // PHI node is in the original loop block, or the exit block.
105 if (L->contains(PN)) {
106 PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
107 } else {
108 PN->addIncoming(NewPN, PrologEnd);
109 }
110 }
111 }
112
Sanjoy Das11b279a2015-02-18 19:32:25 +0000113 // Create a branch around the orignal loop, which is taken if there are no
114 // iterations remaining to be executed after running the prologue.
Andrew Trickd04d15292011-12-09 06:19:40 +0000115 Instruction *InsertPt = PrologEnd->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000116 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000117
118 assert(Count != 0 && "nonsensical Count!");
119
120 // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
121 // (since Count is a power of 2). This means %xtraiter is (BECount + 1) and
122 // and all of the iterations of this loop were executed by the prologue. Note
123 // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000124 Value *BrLoopExit =
125 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000126 BasicBlock *Exit = L->getUniqueExitBlock();
Craig Toppere73658d2014-04-28 04:05:08 +0000127 assert(Exit && "Loop must have a single exit block only");
Andrew Trickd04d15292011-12-09 06:19:40 +0000128 // Split the exit to maintain loop canonicalization guarantees
129 SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
Chandler Carruth96ada252015-07-22 09:52:54 +0000130 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI,
Philip Reames9198b332015-01-28 23:06:47 +0000131 P->mustPreserveAnalysisID(LCSSAID));
Andrew Trickd04d15292011-12-09 06:19:40 +0000132 // Add the branch to the exit block (around the unrolled loop)
Alexey Samsonovea201992015-06-11 18:25:44 +0000133 B.CreateCondBr(BrLoopExit, Exit, NewPH);
Andrew Trickd04d15292011-12-09 06:19:40 +0000134 InsertPt->eraseFromParent();
135}
136
137/// Create a clone of the blocks in a loop and connect them together.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000138/// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
139/// loop will be created including all cloned blocks, and the iterator of it
140/// switches to count NewIter down to 0.
Andrew Trickd04d15292011-12-09 06:19:40 +0000141///
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000142static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
143 BasicBlock *InsertTop, BasicBlock *InsertBot,
Andrew Trickd04d15292011-12-09 06:19:40 +0000144 std::vector<BasicBlock *> &NewBlocks,
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000145 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Kevin Qin65b07b82015-03-09 07:26:37 +0000146 LoopInfo *LI) {
Andrew Trickd04d15292011-12-09 06:19:40 +0000147 BasicBlock *Preheader = L->getLoopPreheader();
148 BasicBlock *Header = L->getHeader();
149 BasicBlock *Latch = L->getLoopLatch();
150 Function *F = Header->getParent();
151 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
152 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000153 Loop *NewLoop = nullptr;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000154 Loop *ParentLoop = L->getParentLoop();
155 if (!UnrollProlog) {
156 NewLoop = new Loop();
Kevin Qin65b07b82015-03-09 07:26:37 +0000157 if (ParentLoop)
158 ParentLoop->addChildLoop(NewLoop);
159 else
160 LI->addTopLevelLoop(NewLoop);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000161 }
162
Andrew Trickd04d15292011-12-09 06:19:40 +0000163 // For each block in the original loop, create a new copy,
164 // and update the value map with the newly created values.
165 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000166 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000167 NewBlocks.push_back(NewBB);
168
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000169 if (NewLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000170 NewLoop->addBasicBlockToLoop(NewBB, *LI);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000171 else if (ParentLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000172 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000173
174 VMap[*BB] = NewBB;
175 if (Header == *BB) {
176 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000177 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000178 InsertTop->getTerminator()->setSuccessor(0, NewBB);
179
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000180 }
181 if (Latch == *BB) {
182 // For the last block, if UnrollProlog is true, create a direct jump to
183 // InsertBot. If not, create a loop back to cloned head.
184 VMap.erase((*BB)->getTerminator());
185 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
186 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000187 IRBuilder<> Builder(LatchBR);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000188 if (UnrollProlog) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000189 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000190 } else {
191 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
192 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000193 Value *IdxSub =
194 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
195 NewIdx->getName() + ".sub");
196 Value *IdxCmp =
197 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000198 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000199 NewIdx->addIncoming(NewIter, InsertTop);
200 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000201 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000202 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000203 }
204 }
205
206 // Change the incoming values to the ones defined in the preheader or
207 // cloned loop.
208 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
209 PHINode *NewPHI = cast<PHINode>(VMap[I]);
210 if (UnrollProlog) {
211 VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
212 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
213 } else {
214 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
215 NewPHI->setIncomingBlock(idx, InsertTop);
216 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
217 idx = NewPHI->getBasicBlockIndex(Latch);
218 Value *InVal = NewPHI->getIncomingValue(idx);
219 NewPHI->setIncomingBlock(idx, NewLatch);
220 if (VMap[InVal])
221 NewPHI->setIncomingValue(idx, VMap[InVal]);
222 }
223 }
224 if (NewLoop) {
225 // Add unroll disable metadata to disable future unrolling for this loop.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000226 SmallVector<Metadata *, 4> MDs;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000227 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000228 MDs.push_back(nullptr);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000229 MDNode *LoopID = NewLoop->getLoopID();
230 if (LoopID) {
231 // First remove any existing loop unrolling metadata.
232 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
233 bool IsUnrollMetadata = false;
234 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
235 if (MD) {
236 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
237 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
Andrew Trickd04d15292011-12-09 06:19:40 +0000238 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000239 if (!IsUnrollMetadata)
240 MDs.push_back(LoopID->getOperand(i));
Andrew Trickd04d15292011-12-09 06:19:40 +0000241 }
242 }
243
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000244 LLVMContext &Context = NewLoop->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000245 SmallVector<Metadata *, 1> DisableOperands;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000246 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
247 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000248 MDs.push_back(DisableNode);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000249
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000250 MDNode *NewLoopID = MDNode::get(Context, MDs);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000251 // Set operand 0 to refer to the loop id itself.
252 NewLoopID->replaceOperandWith(0, NewLoopID);
253 NewLoop->setLoopID(NewLoopID);
Andrew Trickd04d15292011-12-09 06:19:40 +0000254 }
255}
256
257/// Insert code in the prolog code when unrolling a loop with a
258/// run-time trip-count.
259///
260/// This method assumes that the loop unroll factor is total number
261/// of loop bodes in the loop after unrolling. (Some folks refer
262/// to the unroll factor as the number of *extra* copies added).
263/// We assume also that the loop unroll factor is a power-of-two. So, after
264/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000265/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000266/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
267/// the switch instruction is generated.
268///
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000269/// extraiters = tripcount % loopfactor
270/// if (extraiters == 0) jump Loop:
271/// else jump Prol
272/// Prol: LoopBody;
273/// extraiters -= 1 // Omitted if unroll factor is 2.
274/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
275/// if (tripcount < loopfactor) jump End
276/// Loop:
277/// ...
278/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000279///
Sanjoy Dase178f462015-04-14 03:20:38 +0000280bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count,
281 bool AllowExpensiveTripCount, LoopInfo *LI,
Andrew Trickd04d15292011-12-09 06:19:40 +0000282 LPPassManager *LPM) {
283 // for now, only unroll loops that contain a single exit
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000284 if (!L->getExitingBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000285 return false;
286
287 // Make sure the loop is in canonical form, and there is a single
288 // exit block only.
Craig Topperf40110f2014-04-25 05:29:35 +0000289 if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000290 return false;
291
292 // Use Scalar Evolution to compute the trip count. This allows more
293 // loops to be unrolled than relying on induction var simplification
Andrew Trickd29cd732012-05-08 02:52:09 +0000294 if (!LPM)
295 return false;
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000296 auto *SEWP = LPM->getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
297 if (!SEWP)
Andrew Trickd04d15292011-12-09 06:19:40 +0000298 return false;
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000299 ScalarEvolution &SE = SEWP->getSE();
Andrew Trickd04d15292011-12-09 06:19:40 +0000300
301 // Only unroll loops with a computable trip count and the trip count needs
302 // to be an int value (allowing a pointer type is a TODO item)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000303 const SCEV *BECountSC = SE.getBackedgeTakenCount(L);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000304 if (isa<SCEVCouldNotCompute>(BECountSC) ||
305 !BECountSC->getType()->isIntegerTy())
Andrew Trickd04d15292011-12-09 06:19:40 +0000306 return false;
307
Sanjoy Das11b279a2015-02-18 19:32:25 +0000308 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000309
Andrew Trickd04d15292011-12-09 06:19:40 +0000310 // Add 1 since the backedge count doesn't include the first loop iteration
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000311 const SCEV *TripCountSC =
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000312 SE.getAddExpr(BECountSC, SE.getConstant(BECountSC->getType(), 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000313 if (isa<SCEVCouldNotCompute>(TripCountSC))
314 return false;
315
Sanjoy Dase178f462015-04-14 03:20:38 +0000316 BasicBlock *Header = L->getHeader();
317 const DataLayout &DL = Header->getModule()->getDataLayout();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000318 SCEVExpander Expander(SE, DL, "loop-unroll");
Sanjoy Dase178f462015-04-14 03:20:38 +0000319 if (!AllowExpensiveTripCount && Expander.isHighCostExpansion(TripCountSC, L))
320 return false;
321
Andrew Trickd04d15292011-12-09 06:19:40 +0000322 // We only handle cases when the unroll factor is a power of 2.
323 // Count is the loop unroll factor, the number of extra copies added + 1.
Sanjoy Das11b279a2015-02-18 19:32:25 +0000324 if (!isPowerOf2_32(Count))
325 return false;
326
327 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000328 // comment on ModVal below.
329 if (Log2_32(Count) > BEWidth)
Andrew Trickd04d15292011-12-09 06:19:40 +0000330 return false;
331
332 // If this loop is nested, then the loop unroller changes the code in
333 // parent loop, so the Scalar Evolution pass needs to be run again
334 if (Loop *ParentLoop = L->getParentLoop())
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000335 SE.forgetLoop(ParentLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000336
Chandler Carruthb5797b62015-01-18 09:21:15 +0000337 // Grab analyses that we preserve.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000338 auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
339 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
340
Andrew Trickd04d15292011-12-09 06:19:40 +0000341 BasicBlock *PH = L->getLoopPreheader();
Andrew Trickd04d15292011-12-09 06:19:40 +0000342 BasicBlock *Latch = L->getLoopLatch();
343 // It helps to splits the original preheader twice, one for the end of the
344 // prolog code and one for a new loop preheader
Chandler Carruthd4500562015-01-19 12:36:53 +0000345 BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000346 BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000347 BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
348
349 // Compute the number of extra iterations required, which is:
350 // extra iterations = run-time trip count % (loop unroll factor + 1)
Andrew Trickd04d15292011-12-09 06:19:40 +0000351 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
352 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000353 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
354 PreHeaderBR);
Andrew Trickd04d15292011-12-09 06:19:40 +0000355
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000356 IRBuilder<> B(PreHeaderBR);
357 Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
358
Sanjoy Das11b279a2015-02-18 19:32:25 +0000359 // If ModVal is zero, we know that either
360 // 1. there are no iteration to be run in the prologue loop
361 // OR
362 // 2. the addition computing TripCount overflowed
363 //
364 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so the
365 // number of iterations that remain to be run in the original loop is a
366 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
367 // explicitly check this above).
368
369 Value *BranchVal = B.CreateIsNotNull(ModVal, "lcmp.mod");
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000370
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000371 // Branch to either the extra iterations or the cloned/unrolled loop
Andrew Trickd04d15292011-12-09 06:19:40 +0000372 // We will fix up the true branch label when adding loop body copies
Alexey Samsonovea201992015-06-11 18:25:44 +0000373 B.CreateCondBr(BranchVal, PEnd, PEnd);
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000374 assert(PreHeaderBR->isUnconditional() &&
375 PreHeaderBR->getSuccessor(0) == PEnd &&
Andrew Trickd04d15292011-12-09 06:19:40 +0000376 "CFG edges in Preheader are not correct");
377 PreHeaderBR->eraseFromParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000378 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000379 // Get an ordered list of blocks in the loop to help with the ordering of the
380 // cloned blocks in the prolog code
381 LoopBlocksDFS LoopBlocks(L);
382 LoopBlocks.perform(LI);
383
384 //
385 // For each extra loop iteration, create a copy of the loop's basic blocks
386 // and generate a condition that branches to the copy depending on the
387 // number of 'left over' iterations.
388 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000389 std::vector<BasicBlock *> NewBlocks;
390 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000391
Sanjoy Das11b279a2015-02-18 19:32:25 +0000392 bool UnrollPrologue = Count == 2;
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000393
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000394 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
395 // the loop, otherwise we create a cloned loop to execute the extra
396 // iterations. This function adds the appropriate CFG connections.
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000397 CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
Kevin Qin65b07b82015-03-09 07:26:37 +0000398 VMap, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000399
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000400 // Insert the cloned blocks into function just before the original loop
401 F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
402 F->end());
Andrew Trickd04d15292011-12-09 06:19:40 +0000403
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000404 // Rewrite the cloned instruction operands to use the values
405 // created when the clone is created.
406 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
407 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
408 E = NewBlocks[i]->end();
409 I != E; ++I) {
410 RemapInstruction(I, VMap,
411 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Andrew Trickd04d15292011-12-09 06:19:40 +0000412 }
413 }
414
415 // Connect the prolog code to the original loop and update the
416 // PHI functions.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000417 BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
Chandler Carruth96ada252015-07-22 09:52:54 +0000418 ConnectProlog(L, BECount, Count, LastLoopBB, PEnd, PH, NewPH, VMap, DT, LI,
419 LPM->getAsPass());
Andrew Trickd04d15292011-12-09 06:19:40 +0000420 NumRuntimeUnrolled++;
421 return true;
422}