1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements a simple loop unroller. It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
14 // This pass will multi-block loops only if they contain no non-unrolled
15 // subloops. The process of unrolling can produce extraneous basic blocks
16 // linked with unconditional branches. This will be corrected in the future.
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "loop-unroll"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/IntrinsicInst.h"
40 Statistic NumUnrolled("loop-unroll", "Number of loops completely unrolled");
43 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
44 cl::desc("The cut-off point for loop unrolling"));
46 class LoopUnroll : public FunctionPass {
47 LoopInfo *LI; // The current loop information
49 virtual bool runOnFunction(Function &F);
50 bool visitLoop(Loop *L);
51 BasicBlock* FoldBlockIntoPredecessor(BasicBlock* BB);
53 /// This transformation requires natural loop information & requires that
54 /// loop preheaders be inserted into the CFG...
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequiredID(LoopSimplifyID);
58 AU.addRequiredID(LCSSAID);
59 AU.addRequired<LoopInfo>();
60 AU.addPreservedID(LCSSAID);
61 AU.addPreserved<LoopInfo>();
64 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
67 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
69 bool LoopUnroll::runOnFunction(Function &F) {
71 LI = &getAnalysis<LoopInfo>();
73 // Transform all the top-level loops. Copy the loop list so that the child
74 // can update the loop tree if it needs to delete the loop.
75 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
76 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
77 Changed |= visitLoop(SubLoops[i]);
82 /// ApproximateLoopSize - Approximate the size of the loop after it has been
84 static unsigned ApproximateLoopSize(const Loop *L) {
86 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
87 BasicBlock *BB = L->getBlocks()[i];
88 Instruction *Term = BB->getTerminator();
89 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
90 if (isa<PHINode>(I) && BB == L->getHeader()) {
91 // Ignore PHI nodes in the header.
92 } else if (I->hasOneUse() && I->use_back() == Term) {
93 // Ignore instructions only used by the loop terminator.
94 } else if (isa<DbgInfoIntrinsic>(I)) {
95 // Ignore debug instructions
100 // TODO: Ignore expressions derived from PHI and constants if inval of phi
101 // is a constant, or if operation is associative. This will get induction
109 // RemapInstruction - Convert the instruction operands from referencing the
110 // current values into those specified by ValueMap.
112 static inline void RemapInstruction(Instruction *I,
113 std::map<const Value *, Value*> &ValueMap) {
114 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
115 Value *Op = I->getOperand(op);
116 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
117 if (It != ValueMap.end()) Op = It->second;
118 I->setOperand(op, Op);
122 // FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
123 // only has one predecessor, and that predecessor only has one successor.
124 // Returns the new combined block.
125 BasicBlock* LoopUnroll::FoldBlockIntoPredecessor(BasicBlock* BB) {
126 // Merge basic blocks into their predecessor if there is only one distinct
127 // pred, and if there is only one distinct successor of the predecessor, and
128 // if there are no PHI nodes.
130 BasicBlock *OnlyPred = BB->getSinglePredecessor();
131 if (!OnlyPred) return 0;
133 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
136 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
138 // Resolve any PHI nodes at the start of the block. They are all
139 // guaranteed to have exactly one entry if they exist, unless there are
140 // multiple duplicate (but guaranteed to be equal) entries for the
141 // incoming edges. This occurs when there are multiple edges from
142 // OnlyPred to OnlySucc.
144 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
145 PN->replaceAllUsesWith(PN->getIncomingValue(0));
146 BB->getInstList().pop_front(); // Delete the phi node...
149 // Delete the unconditional branch from the predecessor...
150 OnlyPred->getInstList().pop_back();
152 // Move all definitions in the successor to the predecessor...
153 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
155 // Make all PHI nodes that referred to BB now refer to Pred as their
157 BB->replaceAllUsesWith(OnlyPred);
159 std::string OldName = BB->getName();
161 // Erase basic block from the function...
163 BB->eraseFromParent();
165 // Inherit predecessors name if it exists...
166 if (!OldName.empty() && !OnlyPred->hasName())
167 OnlyPred->setName(OldName);
172 bool LoopUnroll::visitLoop(Loop *L) {
173 bool Changed = false;
175 // Recurse through all subloops before we process this loop. Copy the loop
176 // list so that the child can update the loop tree if it needs to delete the
178 std::vector<Loop*> SubLoops(L->begin(), L->end());
179 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
180 Changed |= visitLoop(SubLoops[i]);
182 BasicBlock* Header = L->getHeader();
183 BasicBlock* LatchBlock = L->getLoopLatch();
185 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
186 if (BI == 0) return Changed; // Must end in a conditional branch
188 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
189 if (!TripCountC) return Changed; // Must have constant trip count!
191 uint64_t TripCountFull = TripCountC->getZExtValue();
192 if (TripCountFull != TripCountC->getZExtValue() || TripCountFull == 0)
193 return Changed; // More than 2^32 iterations???
195 unsigned LoopSize = ApproximateLoopSize(L);
196 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
197 << "] Loop %" << Header->getName() << " Loop Size = "
198 << LoopSize << " Trip Count = " << TripCountFull << " - ";
199 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
200 if (Size > UnrollThreshold) {
201 DOUT << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n";
204 DOUT << "UNROLLING!\n";
206 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
208 unsigned TripCount = (unsigned)TripCountFull;
210 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
212 // For the first iteration of the loop, we should use the precloned values for
213 // PHI nodes. Insert associations now.
214 std::map<const Value*, Value*> LastValueMap;
215 std::vector<PHINode*> OrigPHINode;
216 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
217 PHINode *PN = cast<PHINode>(I);
218 OrigPHINode.push_back(PN);
220 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
221 if (L->contains(I->getParent()))
225 // Remove the exit branch from the loop
226 LatchBlock->getInstList().erase(BI);
228 std::vector<BasicBlock*> Headers;
229 std::vector<BasicBlock*> Latches;
230 Headers.push_back(Header);
231 Latches.push_back(LatchBlock);
233 assert(TripCount != 0 && "Trip count of 0 is impossible!");
234 for (unsigned It = 1; It != TripCount; ++It) {
235 char SuffixBuffer[100];
236 sprintf(SuffixBuffer, ".%d", It);
238 std::vector<BasicBlock*> NewBlocks;
240 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
241 E = LoopBlocks.end(); BB != E; ++BB) {
242 std::map<const Value*, Value*> ValueMap;
243 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
244 Header->getParent()->getBasicBlockList().push_back(New);
246 // Loop over all of the PHI nodes in the block, changing them to use the
247 // incoming values from the previous block.
249 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
250 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
251 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
252 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
253 if (It > 1 && L->contains(InValI->getParent()))
254 InVal = LastValueMap[InValI];
255 ValueMap[OrigPHINode[i]] = InVal;
256 New->getInstList().erase(NewPHI);
259 // Update our running map of newest clones
260 LastValueMap[*BB] = New;
261 for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
262 VE = ValueMap.end(); VI != VE; ++VI)
263 LastValueMap[VI->first] = VI->second;
265 L->addBasicBlockToLoop(New, *LI);
267 // Add phi entries for newly created values to all exit blocks except
268 // the successor of the latch block. The successor of the exit block will
269 // be updated specially after unrolling all the way.
270 if (*BB != LatchBlock)
271 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
273 Instruction* UseInst = cast<Instruction>(*UI);
274 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
275 PHINode* phi = cast<PHINode>(UseInst);
276 Value* Incoming = phi->getIncomingValueForBlock(*BB);
277 if (isa<Instruction>(Incoming))
278 Incoming = LastValueMap[Incoming];
280 phi->addIncoming(Incoming, New);
284 // Keep track of new headers and latches as we create them, so that
285 // we can insert the proper branches later.
287 Headers.push_back(New);
288 if (*BB == LatchBlock)
289 Latches.push_back(New);
291 NewBlocks.push_back(New);
294 // Remap all instructions in the most recent iteration
295 for (unsigned i = 0; i < NewBlocks.size(); ++i)
296 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
297 E = NewBlocks[i]->end(); I != E; ++I)
298 RemapInstruction(I, LastValueMap);
303 // Update PHI nodes that reference the final latch block
305 std::set<PHINode*> Users;
306 for (Value::use_iterator UI = LatchBlock->use_begin(),
307 UE = LatchBlock->use_end(); UI != UE; ++UI)
308 if (PHINode* phi = dyn_cast<PHINode>(*UI))
311 for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
313 Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
314 if (isa<Instruction>(InVal))
315 InVal = LastValueMap[InVal];
316 (*SI)->removeIncomingValue(LatchBlock, false);
318 (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
322 // Now loop over the PHI nodes in the original block, setting them to their
324 BasicBlock *Preheader = L->getLoopPreheader();
325 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
326 PHINode *PN = OrigPHINode[i];
327 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
328 Header->getInstList().erase(PN);
331 // Insert the branches that link the different iterations together
332 for (unsigned i = 0; i < Latches.size()-1; ++i) {
333 new BranchInst(Headers[i+1], Latches[i]);
334 if(BasicBlock* Fold = FoldBlockIntoPredecessor(Headers[i+1])) {
335 std::replace(Latches.begin(), Latches.end(), Headers[i+1], Fold);
336 std::replace(Headers.begin(), Headers.end(), Headers[i+1], Fold);
340 // Finally, add an unconditional branch to the block to continue into the exit
342 new BranchInst(LoopExit, Latches[Latches.size()-1]);
343 FoldBlockIntoPredecessor(LoopExit);
345 // At this point, the code is well formed. We now do a quick sweep over the
346 // inserted code, doing constant propagation and dead code elimination as we
348 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
349 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
350 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
351 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
352 Instruction *Inst = I++;
354 if (isInstructionTriviallyDead(Inst))
355 (*BB)->getInstList().erase(Inst);
356 else if (Constant *C = ConstantFoldInstruction(Inst)) {
357 Inst->replaceAllUsesWith(C);
358 (*BB)->getInstList().erase(Inst);
362 // Update the loop information for this loop.
363 Loop *Parent = L->getParentLoop();
365 // Move all of the basic blocks in the loop into the parent loop.
366 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
367 E = NewLoopBlocks.end(); BB != E; ++BB)
368 LI->changeLoopFor(*BB, Parent);
370 // Remove the loop from the parent.
372 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
374 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));