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 is currently extremely limited. It only currently only unrolls
15 // single basic block loops that execute a constant number of times.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "loop-unroll"
20 #include "llvm/Transforms/Scalar.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "Support/CommandLine.h"
28 #include "Support/Debug.h"
29 #include "Support/Statistic.h"
30 #include "Support/STLExtras.h"
35 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
38 UnrollThreshold("unroll-threshold", cl::init(250), cl::Hidden,
39 cl::desc("The cut-off point for loop unrolling"));
41 class LoopUnroll : public FunctionPass {
42 LoopInfo *LI; // The current loop information
44 virtual bool runOnFunction(Function &F);
45 bool visitLoop(Loop *L);
47 /// This transformation requires natural loop information & requires that
48 /// loop preheaders be inserted into the CFG...
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequiredID(LoopSimplifyID);
52 AU.addRequired<LoopInfo>();
53 AU.addPreserved<LoopInfo>();
56 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
59 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
61 bool LoopUnroll::runOnFunction(Function &F) {
63 LI = &getAnalysis<LoopInfo>();
65 // Transform all the top-level loops. Copy the loop list so that the child
66 // can update the loop tree if it needs to delete the loop.
67 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
68 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
69 Changed |= visitLoop(SubLoops[i]);
74 /// ApproximateLoopSize - Approximate the size of the loop after it has been
76 static unsigned ApproximateLoopSize(const Loop *L) {
78 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
79 BasicBlock *BB = L->getBlocks()[i];
80 Instruction *Term = BB->getTerminator();
81 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
82 if (isa<PHINode>(I) && BB == L->getHeader()) {
83 // Ignore PHI nodes in the header.
84 } else if (I->hasOneUse() && I->use_back() == Term) {
85 // Ignore instructions only used by the loop terminator.
90 // TODO: Ignore expressions derived from PHI and constants if inval of phi
91 // is a constant, or if operation is associative. This will get induction
99 // RemapInstruction - Convert the instruction operands from referencing the
100 // current values into those specified by ValueMap.
102 static inline void RemapInstruction(Instruction *I,
103 std::map<const Value *, Value*> &ValueMap) {
104 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
105 Value *Op = I->getOperand(op);
106 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
107 if (It != ValueMap.end()) Op = It->second;
108 I->setOperand(op, Op);
112 static void ChangeExitBlocksFromTo(Loop::iterator I, Loop::iterator E,
113 BasicBlock *Old, BasicBlock *New) {
114 for (; I != E; ++I) {
116 if (L->hasExitBlock(Old)) {
117 L->changeExitBlock(Old, New);
118 ChangeExitBlocksFromTo(L->begin(), L->end(), Old, New);
124 bool LoopUnroll::visitLoop(Loop *L) {
125 bool Changed = false;
127 // Recurse through all subloops before we process this loop. Copy the loop
128 // list so that the child can update the loop tree if it needs to delete the
130 std::vector<Loop*> SubLoops(L->begin(), L->end());
131 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
132 Changed |= visitLoop(SubLoops[i]);
134 // We only handle single basic block loops right now.
135 if (L->getBlocks().size() != 1)
138 BasicBlock *BB = L->getHeader();
139 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
140 if (BI == 0) return Changed; // Must end in a conditional branch
142 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
143 if (!TripCountC) return Changed; // Must have constant trip count!
145 unsigned TripCount = TripCountC->getRawValue();
146 if (TripCount != TripCountC->getRawValue())
147 return Changed; // More than 2^32 iterations???
149 unsigned LoopSize = ApproximateLoopSize(L);
150 DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
151 << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
152 << " Trip Count = " << TripCount << " - ");
153 if (LoopSize*TripCount > UnrollThreshold) {
154 DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
155 << UnrollThreshold << "\n");
158 DEBUG(std::cerr << "UNROLLING!\n");
160 assert(L->getExitBlocks().size() == 1 && "Must have exactly one exit block!");
161 BasicBlock *LoopExit = L->getExitBlocks()[0];
163 // Create a new basic block to temporarily hold all of the cloned code.
164 BasicBlock *NewBlock = new BasicBlock();
166 // For the first iteration of the loop, we should use the precloned values for
167 // PHI nodes. Insert associations now.
168 std::map<const Value*, Value*> LastValueMap;
169 std::vector<PHINode*> OrigPHINode;
170 for (BasicBlock::iterator I = BB->begin();
171 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
172 OrigPHINode.push_back(PN);
173 if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
174 if (I->getParent() == BB)
178 // Remove the exit branch from the loop
179 BB->getInstList().erase(BI);
181 assert(TripCount != 0 && "Trip count of 0 is impossible!");
182 for (unsigned It = 1; It != TripCount; ++It) {
183 char SuffixBuffer[100];
184 sprintf(SuffixBuffer, ".%d", It);
185 std::map<const Value*, Value*> ValueMap;
186 BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
188 // Loop over all of the PHI nodes in the block, changing them to use the
189 // incoming values from the previous block.
190 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
191 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
192 Value *InVal = NewPHI->getIncomingValueForBlock(BB);
193 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
194 if (InValI->getParent() == BB)
195 InVal = LastValueMap[InValI];
196 ValueMap[OrigPHINode[i]] = InVal;
197 New->getInstList().erase(NewPHI);
200 for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
201 RemapInstruction(I, ValueMap);
203 // Now that all of the instructions are remapped, splice them into the end
205 NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
208 // LastValue map now contains values from this iteration.
209 std::swap(LastValueMap, ValueMap);
212 // If there was more than one iteration, replace any uses of values computed
213 // in the loop with values computed during last iteration of the loop.
215 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
216 std::vector<User*> Users(I->use_begin(), I->use_end());
217 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
218 Instruction *UI = cast<Instruction>(Users[i]);
219 if (UI->getParent() != BB && UI->getParent() != NewBlock)
220 UI->replaceUsesOfWith(I, LastValueMap[I]);
224 // Now that we cloned the block as many times as we needed, stitch the new
225 // code into the original block and delete the temporary block.
226 BB->getInstList().splice(BB->end(), NewBlock->getInstList());
229 // Now loop over the PHI nodes in the original block, setting them to their
231 BasicBlock *Preheader = L->getLoopPreheader();
232 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
233 PHINode *PN = OrigPHINode[i];
234 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
235 BB->getInstList().erase(PN);
238 // Finally, add an unconditional branch to the block to continue into the exit
240 new BranchInst(LoopExit, BB);
242 // At this point, the code is well formed. We now do a quick sweep over the
243 // inserted code, doing constant propagation and dead code elimination as we
245 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
246 Instruction *Inst = I++;
248 if (isInstructionTriviallyDead(Inst))
249 BB->getInstList().erase(Inst);
250 else if (Constant *C = ConstantFoldInstruction(Inst)) {
251 Inst->replaceAllUsesWith(C);
252 BB->getInstList().erase(Inst);
256 // Update the loop information for this loop.
257 Loop *Parent = L->getParentLoop();
259 // Move all of the basic blocks in the loop into the parent loop.
260 LI->changeLoopFor(BB, Parent);
262 // Remove the loop from the parent.
264 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
266 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
269 // FIXME: Should update dominator analyses
272 // Now that everything is up-to-date that will be, we fold the loop block into
273 // the preheader and exit block, updating our analyses as we go.
274 LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
275 BB->getInstList().begin(),
276 prior(BB->getInstList().end()));
277 LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
278 Preheader->getInstList().begin(),
279 prior(Preheader->getInstList().end()));
281 // Make all other blocks in the program branch to LoopExit now instead of
283 Preheader->replaceAllUsesWith(LoopExit);
285 // Remove BB and LoopExit from our analyses.
286 LI->removeBlock(Preheader);
289 // If any loops used Preheader as an exit block, update them to use LoopExit.
291 ChangeExitBlocksFromTo(Parent->begin(), Parent->end(),
292 Preheader, LoopExit);
294 ChangeExitBlocksFromTo(LI->begin(), LI->end(),
295 Preheader, LoopExit);
298 // Actually delete the blocks now.
299 LoopExit->getParent()->getBasicBlockList().erase(Preheader);
300 LoopExit->getParent()->getBasicBlockList().erase(BB);