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"
34 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
37 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
38 cl::desc("The cut-off point for loop unrolling"));
40 class LoopUnroll : public FunctionPass {
41 LoopInfo *LI; // The current loop information
43 virtual bool runOnFunction(Function &F);
44 bool visitLoop(Loop *L);
46 /// This transformation requires natural loop information & requires that
47 /// loop preheaders be inserted into the CFG...
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequiredID(LoopSimplifyID);
52 AU.addRequired<LoopInfo>();
55 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
58 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
60 bool LoopUnroll::runOnFunction(Function &F) {
62 LI = &getAnalysis<LoopInfo>();
64 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
65 Changed |= visitLoop(*I);
70 /// ApproximateLoopSize - Approximate the size of the loop after it has been
72 static unsigned ApproximateLoopSize(const Loop *L) {
74 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
75 BasicBlock *BB = L->getBlocks()[i];
76 Instruction *Term = BB->getTerminator();
77 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
78 if (isa<PHINode>(I) && BB == L->getHeader()) {
79 // Ignore PHI nodes in the header.
80 } else if (I->hasOneUse() && I->use_back() == Term) {
81 // Ignore instructions only used by the loop terminator.
86 // TODO: Ignore expressions derived from PHI and constants if inval of phi
87 // is a constant, or if operation is associative. This will get induction
95 // RemapInstruction - Convert the instruction operands from referencing the
96 // current values into those specified by ValueMap.
98 static inline void RemapInstruction(Instruction *I,
99 std::map<const Value *, Value*> &ValueMap) {
100 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
101 Value *Op = I->getOperand(op);
102 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
103 if (It != ValueMap.end()) Op = It->second;
104 I->setOperand(op, Op);
109 bool LoopUnroll::visitLoop(Loop *L) {
110 bool Changed = false;
112 // Recurse through all subloops before we process this loop. Copy the loop
113 // list so that the child can update the loop tree if it needs to delete the
115 std::vector<Loop*> SubLoops(L->begin(), L->end());
116 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
117 Changed |= visitLoop(SubLoops[i]);
119 // We only handle single basic block loops right now.
120 if (L->getBlocks().size() != 1)
123 BasicBlock *BB = L->getHeader();
124 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
125 if (BI == 0) return Changed; // Must end in a conditional branch
127 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
128 if (!TripCountC) return Changed; // Must have constant trip count!
130 unsigned TripCount = TripCountC->getRawValue();
131 if (TripCount != TripCountC->getRawValue())
132 return Changed; // More than 2^32 iterations???
134 unsigned LoopSize = ApproximateLoopSize(L);
135 DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
136 << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
137 << " Trip Count = " << TripCount << " - ");
138 if (LoopSize*TripCount > UnrollThreshold) {
139 DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
140 << UnrollThreshold << "\n");
143 DEBUG(std::cerr << "UNROLLING!\n");
145 assert(L->getExitBlocks().size() == 1 && "Must have exactly one exit block!");
146 BasicBlock *LoopExit = L->getExitBlocks()[0];
148 // Create a new basic block to temporarily hold all of the cloned code.
149 BasicBlock *NewBlock = new BasicBlock();
151 // For the first iteration of the loop, we should use the precloned values for
152 // PHI nodes. Insert associations now.
153 std::map<const Value*, Value*> LastValueMap;
154 std::vector<PHINode*> OrigPHINode;
155 for (BasicBlock::iterator I = BB->begin();
156 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
157 OrigPHINode.push_back(PN);
158 if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
159 if (I->getParent() == BB)
163 // Remove the exit branch from the loop
164 BB->getInstList().erase(BI);
166 assert(TripCount != 0 && "Trip count of 0 is impossible!");
167 for (unsigned It = 1; It != TripCount; ++It) {
168 char SuffixBuffer[100];
169 sprintf(SuffixBuffer, ".%d", It);
170 std::map<const Value*, Value*> ValueMap;
171 BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
173 // Loop over all of the PHI nodes in the block, changing them to use the
174 // incoming values from the previous block.
175 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
176 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
177 Value *InVal = NewPHI->getIncomingValueForBlock(BB);
178 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
179 if (InValI->getParent() == BB)
180 InVal = LastValueMap[InValI];
181 ValueMap[OrigPHINode[i]] = InVal;
182 New->getInstList().erase(NewPHI);
185 for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
186 RemapInstruction(I, ValueMap);
188 // Now that all of the instructions are remapped, splice them into the end
190 NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
193 // LastValue map now contains values from this iteration.
194 std::swap(LastValueMap, ValueMap);
197 // If there was more than one iteration, replace any uses of values computed
198 // in the loop with values computed during last iteration of the loop.
200 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
201 std::vector<User*> Users(I->use_begin(), I->use_end());
202 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
203 Instruction *UI = cast<Instruction>(Users[i]);
204 if (UI->getParent() != BB && UI->getParent() != NewBlock)
205 UI->replaceUsesOfWith(I, LastValueMap[I]);
209 // Now that we cloned the block as many times as we needed, stitch the new
210 // code into the original block and delete the temporary block.
211 BB->getInstList().splice(BB->end(), NewBlock->getInstList());
214 // Now loop over the PHI nodes in the original block, setting them to their
216 BasicBlock *Preheader = L->getLoopPreheader();
217 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
218 PHINode *PN = OrigPHINode[i];
219 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
220 BB->getInstList().erase(PN);
223 // Finally, add an unconditional branch to the block to continue into the exit
225 new BranchInst(LoopExit, BB);
227 // At this point, the code is well formed. We now do a quick sweep over the
228 // inserted code, doing constant propagation and dead code elimination as we
230 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
231 Instruction *Inst = I++;
233 if (isInstructionTriviallyDead(Inst))
234 BB->getInstList().erase(Inst);
235 else if (Constant *C = ConstantFoldInstruction(Inst)) {
236 Inst->replaceAllUsesWith(C);
237 BB->getInstList().erase(Inst);
241 // FIXME: Should update analyses
243 // FIXME: Should fold into preheader and exit block