Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 1 | //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 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. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 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. |
| 13 | // |
| 14 | // This pass is currently extremely limited. It only currently only unrolls |
| 15 | // single basic block loops that execute a constant number of times. |
| 16 | // |
| 17 | //===----------------------------------------------------------------------===// |
| 18 | |
| 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" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 27 | #include "llvm/Support/CommandLine.h" |
| 28 | #include "llvm/Support/Debug.h" |
| 29 | #include "llvm/ADT/Statistic.h" |
| 30 | #include "llvm/ADT/STLExtras.h" |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 31 | #include <cstdio> |
Chris Lattner | bc02177 | 2004-04-19 03:01:23 +0000 | [diff] [blame] | 32 | #include <set> |
Reid Spencer | ce07833 | 2004-10-18 14:38:48 +0000 | [diff] [blame^] | 33 | #include <algorithm> |
| 34 | |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 35 | using namespace llvm; |
| 36 | |
| 37 | namespace { |
| 38 | Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled"); |
| 39 | |
| 40 | cl::opt<unsigned> |
Chris Lattner | d152502 | 2004-04-18 18:06:14 +0000 | [diff] [blame] | 41 | UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden, |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 42 | cl::desc("The cut-off point for loop unrolling")); |
| 43 | |
| 44 | class LoopUnroll : public FunctionPass { |
| 45 | LoopInfo *LI; // The current loop information |
| 46 | public: |
| 47 | virtual bool runOnFunction(Function &F); |
| 48 | bool visitLoop(Loop *L); |
| 49 | |
| 50 | /// This transformation requires natural loop information & requires that |
| 51 | /// loop preheaders be inserted into the CFG... |
| 52 | /// |
| 53 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 54 | AU.addRequiredID(LoopSimplifyID); |
| 55 | AU.addRequired<LoopInfo>(); |
Chris Lattner | f2cc841 | 2004-04-18 05:38:37 +0000 | [diff] [blame] | 56 | AU.addPreserved<LoopInfo>(); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 57 | } |
| 58 | }; |
| 59 | RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops"); |
| 60 | } |
| 61 | |
| 62 | FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); } |
| 63 | |
| 64 | bool LoopUnroll::runOnFunction(Function &F) { |
| 65 | bool Changed = false; |
| 66 | LI = &getAnalysis<LoopInfo>(); |
| 67 | |
Chris Lattner | f2cc841 | 2004-04-18 05:38:37 +0000 | [diff] [blame] | 68 | // Transform all the top-level loops. Copy the loop list so that the child |
| 69 | // can update the loop tree if it needs to delete the loop. |
| 70 | std::vector<Loop*> SubLoops(LI->begin(), LI->end()); |
| 71 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 72 | Changed |= visitLoop(SubLoops[i]); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 73 | |
| 74 | return Changed; |
| 75 | } |
| 76 | |
| 77 | /// ApproximateLoopSize - Approximate the size of the loop after it has been |
| 78 | /// unrolled. |
| 79 | static unsigned ApproximateLoopSize(const Loop *L) { |
| 80 | unsigned Size = 0; |
| 81 | for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) { |
| 82 | BasicBlock *BB = L->getBlocks()[i]; |
| 83 | Instruction *Term = BB->getTerminator(); |
| 84 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 85 | if (isa<PHINode>(I) && BB == L->getHeader()) { |
| 86 | // Ignore PHI nodes in the header. |
| 87 | } else if (I->hasOneUse() && I->use_back() == Term) { |
| 88 | // Ignore instructions only used by the loop terminator. |
| 89 | } else { |
| 90 | ++Size; |
| 91 | } |
| 92 | |
| 93 | // TODO: Ignore expressions derived from PHI and constants if inval of phi |
| 94 | // is a constant, or if operation is associative. This will get induction |
| 95 | // variables. |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | return Size; |
| 100 | } |
| 101 | |
| 102 | // RemapInstruction - Convert the instruction operands from referencing the |
| 103 | // current values into those specified by ValueMap. |
| 104 | // |
| 105 | static inline void RemapInstruction(Instruction *I, |
| 106 | std::map<const Value *, Value*> &ValueMap) { |
| 107 | for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { |
| 108 | Value *Op = I->getOperand(op); |
| 109 | std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); |
| 110 | if (It != ValueMap.end()) Op = It->second; |
| 111 | I->setOperand(op, Op); |
| 112 | } |
| 113 | } |
| 114 | |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 115 | bool LoopUnroll::visitLoop(Loop *L) { |
| 116 | bool Changed = false; |
| 117 | |
| 118 | // Recurse through all subloops before we process this loop. Copy the loop |
| 119 | // list so that the child can update the loop tree if it needs to delete the |
| 120 | // loop. |
| 121 | std::vector<Loop*> SubLoops(L->begin(), L->end()); |
| 122 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 123 | Changed |= visitLoop(SubLoops[i]); |
| 124 | |
| 125 | // We only handle single basic block loops right now. |
| 126 | if (L->getBlocks().size() != 1) |
| 127 | return Changed; |
| 128 | |
| 129 | BasicBlock *BB = L->getHeader(); |
| 130 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 131 | if (BI == 0) return Changed; // Must end in a conditional branch |
| 132 | |
| 133 | ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount()); |
| 134 | if (!TripCountC) return Changed; // Must have constant trip count! |
| 135 | |
| 136 | unsigned TripCount = TripCountC->getRawValue(); |
Chris Lattner | c1aa21f | 2004-04-20 20:26:03 +0000 | [diff] [blame] | 137 | if (TripCount != TripCountC->getRawValue() || TripCount == 0) |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 138 | return Changed; // More than 2^32 iterations??? |
| 139 | |
| 140 | unsigned LoopSize = ApproximateLoopSize(L); |
| 141 | DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName() |
| 142 | << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize |
| 143 | << " Trip Count = " << TripCount << " - "); |
Chris Lattner | c12c945 | 2004-05-13 20:43:31 +0000 | [diff] [blame] | 144 | uint64_t Size = (uint64_t)LoopSize*(uint64_t)TripCount; |
| 145 | if (Size > UnrollThreshold) { |
| 146 | DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n"); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 147 | return Changed; |
| 148 | } |
| 149 | DEBUG(std::cerr << "UNROLLING!\n"); |
| 150 | |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 151 | BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0))); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 152 | |
| 153 | // Create a new basic block to temporarily hold all of the cloned code. |
| 154 | BasicBlock *NewBlock = new BasicBlock(); |
| 155 | |
| 156 | // For the first iteration of the loop, we should use the precloned values for |
| 157 | // PHI nodes. Insert associations now. |
| 158 | std::map<const Value*, Value*> LastValueMap; |
| 159 | std::vector<PHINode*> OrigPHINode; |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 160 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) { |
| 161 | PHINode *PN = cast<PHINode>(I); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 162 | OrigPHINode.push_back(PN); |
| 163 | if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB))) |
| 164 | if (I->getParent() == BB) |
| 165 | LastValueMap[I] = I; |
| 166 | } |
| 167 | |
| 168 | // Remove the exit branch from the loop |
| 169 | BB->getInstList().erase(BI); |
| 170 | |
| 171 | assert(TripCount != 0 && "Trip count of 0 is impossible!"); |
| 172 | for (unsigned It = 1; It != TripCount; ++It) { |
| 173 | char SuffixBuffer[100]; |
| 174 | sprintf(SuffixBuffer, ".%d", It); |
| 175 | std::map<const Value*, Value*> ValueMap; |
| 176 | BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer); |
| 177 | |
| 178 | // Loop over all of the PHI nodes in the block, changing them to use the |
| 179 | // incoming values from the previous block. |
| 180 | for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { |
| 181 | PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]); |
| 182 | Value *InVal = NewPHI->getIncomingValueForBlock(BB); |
| 183 | if (Instruction *InValI = dyn_cast<Instruction>(InVal)) |
| 184 | if (InValI->getParent() == BB) |
| 185 | InVal = LastValueMap[InValI]; |
| 186 | ValueMap[OrigPHINode[i]] = InVal; |
| 187 | New->getInstList().erase(NewPHI); |
| 188 | } |
| 189 | |
| 190 | for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I) |
| 191 | RemapInstruction(I, ValueMap); |
| 192 | |
| 193 | // Now that all of the instructions are remapped, splice them into the end |
| 194 | // of the NewBlock. |
| 195 | NewBlock->getInstList().splice(NewBlock->end(), New->getInstList()); |
| 196 | delete New; |
| 197 | |
| 198 | // LastValue map now contains values from this iteration. |
| 199 | std::swap(LastValueMap, ValueMap); |
| 200 | } |
| 201 | |
| 202 | // If there was more than one iteration, replace any uses of values computed |
Chris Lattner | 230bcb6 | 2004-04-18 17:32:39 +0000 | [diff] [blame] | 203 | // in the loop with values computed during the last iteration of the loop. |
| 204 | if (TripCount != 1) { |
| 205 | std::set<User*> Users; |
| 206 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
| 207 | Users.insert(I->use_begin(), I->use_end()); |
| 208 | |
| 209 | // We don't want to reprocess entries with PHI nodes in them. For this |
| 210 | // reason, we look at each operand of each user exactly once, performing the |
| 211 | // stubstitution exactly once. |
| 212 | for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E; |
| 213 | ++UI) { |
| 214 | Instruction *I = cast<Instruction>(*UI); |
| 215 | if (I->getParent() != BB && I->getParent() != NewBlock) |
| 216 | RemapInstruction(I, LastValueMap); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 217 | } |
Chris Lattner | 230bcb6 | 2004-04-18 17:32:39 +0000 | [diff] [blame] | 218 | } |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 219 | |
| 220 | // Now that we cloned the block as many times as we needed, stitch the new |
| 221 | // code into the original block and delete the temporary block. |
| 222 | BB->getInstList().splice(BB->end(), NewBlock->getInstList()); |
| 223 | delete NewBlock; |
| 224 | |
| 225 | // Now loop over the PHI nodes in the original block, setting them to their |
| 226 | // incoming values. |
| 227 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 228 | for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { |
| 229 | PHINode *PN = OrigPHINode[i]; |
| 230 | PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); |
| 231 | BB->getInstList().erase(PN); |
| 232 | } |
| 233 | |
| 234 | // Finally, add an unconditional branch to the block to continue into the exit |
| 235 | // block. |
| 236 | new BranchInst(LoopExit, BB); |
| 237 | |
| 238 | // At this point, the code is well formed. We now do a quick sweep over the |
| 239 | // inserted code, doing constant propagation and dead code elimination as we |
| 240 | // go. |
| 241 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { |
| 242 | Instruction *Inst = I++; |
| 243 | |
| 244 | if (isInstructionTriviallyDead(Inst)) |
| 245 | BB->getInstList().erase(Inst); |
| 246 | else if (Constant *C = ConstantFoldInstruction(Inst)) { |
| 247 | Inst->replaceAllUsesWith(C); |
| 248 | BB->getInstList().erase(Inst); |
| 249 | } |
| 250 | } |
| 251 | |
Chris Lattner | f2cc841 | 2004-04-18 05:38:37 +0000 | [diff] [blame] | 252 | // Update the loop information for this loop. |
| 253 | Loop *Parent = L->getParentLoop(); |
| 254 | |
| 255 | // Move all of the basic blocks in the loop into the parent loop. |
| 256 | LI->changeLoopFor(BB, Parent); |
| 257 | |
| 258 | // Remove the loop from the parent. |
| 259 | if (Parent) |
| 260 | delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L)); |
| 261 | else |
| 262 | delete LI->removeLoop(std::find(LI->begin(), LI->end(), L)); |
| 263 | |
| 264 | |
| 265 | // FIXME: Should update dominator analyses |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 266 | |
Chris Lattner | 4d52e1e | 2004-04-18 06:27:43 +0000 | [diff] [blame] | 267 | |
| 268 | // Now that everything is up-to-date that will be, we fold the loop block into |
| 269 | // the preheader and exit block, updating our analyses as we go. |
| 270 | LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(), |
| 271 | BB->getInstList().begin(), |
| 272 | prior(BB->getInstList().end())); |
| 273 | LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(), |
| 274 | Preheader->getInstList().begin(), |
| 275 | prior(Preheader->getInstList().end())); |
| 276 | |
| 277 | // Make all other blocks in the program branch to LoopExit now instead of |
| 278 | // Preheader. |
| 279 | Preheader->replaceAllUsesWith(LoopExit); |
| 280 | |
| 281 | // Remove BB and LoopExit from our analyses. |
| 282 | LI->removeBlock(Preheader); |
| 283 | LI->removeBlock(BB); |
| 284 | |
Chris Lattner | 30ae181 | 2004-04-18 17:38:42 +0000 | [diff] [blame] | 285 | // If the preheader was the entry block of this function, move the exit block |
| 286 | // to be the new entry of the loop. |
| 287 | Function *F = LoopExit->getParent(); |
| 288 | if (Preheader == &F->front()) |
| 289 | F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit); |
Chris Lattner | 4d52e1e | 2004-04-18 06:27:43 +0000 | [diff] [blame] | 290 | |
| 291 | // Actually delete the blocks now. |
Chris Lattner | 30ae181 | 2004-04-18 17:38:42 +0000 | [diff] [blame] | 292 | F->getBasicBlockList().erase(Preheader); |
| 293 | F->getBasicBlockList().erase(BB); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 294 | |
| 295 | ++NumUnrolled; |
| 296 | return true; |
| 297 | } |