LoopUnroll.cpp revision f230d8ad15f7ad5cdc5f3950b9d4f0c773d0bac0
1//===-- UnrollLoop.cpp - 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. It does not define any 11// actual pass or policy, but provides a single function to perform loop 12// unrolling. 13// 14// It works best when loops have been canonicalized by the -indvars pass, 15// allowing it to determine the trip counts of loops easily. 16// 17// The process of unrolling can produce extraneous basic blocks linked with 18// unconditional branches. This will be corrected in the future. 19//===----------------------------------------------------------------------===// 20 21#define DEBUG_TYPE "loop-unroll" 22#include "llvm/Transforms/Utils/UnrollLoop.h" 23#include "llvm/BasicBlock.h" 24#include "llvm/ADT/Statistic.h" 25#include "llvm/Analysis/ConstantFolding.h" 26#include "llvm/Analysis/LoopPass.h" 27#include "llvm/Support/Debug.h" 28#include "llvm/Support/raw_ostream.h" 29#include "llvm/Transforms/Utils/BasicBlockUtils.h" 30#include "llvm/Transforms/Utils/Cloning.h" 31#include "llvm/Transforms/Utils/Local.h" 32#include <cstdio> 33 34using namespace llvm; 35 36// TODO: Should these be here or in LoopUnroll? 37STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled"); 38STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)"); 39 40/// RemapInstruction - Convert the instruction operands from referencing the 41/// current values into those specified by ValueMap. 42static inline void RemapInstruction(Instruction *I, 43 DenseMap<const Value *, Value*> &ValueMap) { 44 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 45 Value *Op = I->getOperand(op); 46 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op); 47 if (It != ValueMap.end()) 48 I->setOperand(op, It->second); 49 } 50} 51 52/// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true 53/// if unrolling was succesful, or false if the loop was unmodified. Unrolling 54/// can only fail when the loop's latch block is not terminated by a conditional 55/// branch instruction. However, if the trip count (and multiple) are not known, 56/// loop unrolling will mostly produce more code that is no faster. 57/// 58/// The LoopInfo Analysis that is passed will be kept consistent. 59/// 60/// If a LoopPassManager is passed in, and the loop is fully removed, it will be 61/// removed from the LoopPassManager as well. LPM can also be NULL. 62bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) { 63 assert(L->isLCSSAForm()); 64 65 BasicBlock *Header = L->getHeader(); 66 BasicBlock *LatchBlock = L->getLoopLatch(); 67 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 68 69 if (!BI || BI->isUnconditional()) { 70 // The loop-rotate pass can be helpful to avoid this in many cases. 71 DEBUG(errs() << 72 " Can't unroll; loop not terminated by a conditional branch.\n"); 73 return false; 74 } 75 76 // Find trip count 77 unsigned TripCount = L->getSmallConstantTripCount(); 78 // Find trip multiple if count is not available 79 unsigned TripMultiple = 1; 80 if (TripCount == 0) 81 TripMultiple = L->getSmallConstantTripMultiple(); 82 83 if (TripCount != 0) 84 DEBUG(errs() << " Trip Count = " << TripCount << "\n"); 85 if (TripMultiple != 1) 86 DEBUG(errs() << " Trip Multiple = " << TripMultiple << "\n"); 87 88 // Effectively "DCE" unrolled iterations that are beyond the tripcount 89 // and will never be executed. 90 if (TripCount != 0 && Count > TripCount) 91 Count = TripCount; 92 93 assert(Count > 0); 94 assert(TripMultiple > 0); 95 assert(TripCount == 0 || TripCount % TripMultiple == 0); 96 97 // Are we eliminating the loop control altogether? 98 bool CompletelyUnroll = Count == TripCount; 99 100 // If we know the trip count, we know the multiple... 101 unsigned BreakoutTrip = 0; 102 if (TripCount != 0) { 103 BreakoutTrip = TripCount % Count; 104 TripMultiple = 0; 105 } else { 106 // Figure out what multiple to use. 107 BreakoutTrip = TripMultiple = 108 (unsigned)GreatestCommonDivisor64(Count, TripMultiple); 109 } 110 111 if (CompletelyUnroll) { 112 DEBUG(errs() << "COMPLETELY UNROLLING loop %" << Header->getName() 113 << " with trip count " << TripCount << "!\n"); 114 } else { 115 DEBUG(errs() << "UNROLLING loop %" << Header->getName() 116 << " by " << Count); 117 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) { 118 DEBUG(errs() << " with a breakout at trip " << BreakoutTrip); 119 } else if (TripMultiple != 1) { 120 DEBUG(errs() << " with " << TripMultiple << " trips per branch"); 121 } 122 DEBUG(errs() << "!\n"); 123 } 124 125 std::vector<BasicBlock*> LoopBlocks = L->getBlocks(); 126 127 bool ContinueOnTrue = L->contains(BI->getSuccessor(0)); 128 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue); 129 130 // For the first iteration of the loop, we should use the precloned values for 131 // PHI nodes. Insert associations now. 132 typedef DenseMap<const Value*, Value*> ValueMapTy; 133 ValueMapTy LastValueMap; 134 std::vector<PHINode*> OrigPHINode; 135 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 136 PHINode *PN = cast<PHINode>(I); 137 OrigPHINode.push_back(PN); 138 if (Instruction *I = 139 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock))) 140 if (L->contains(I->getParent())) 141 LastValueMap[I] = I; 142 } 143 144 std::vector<BasicBlock*> Headers; 145 std::vector<BasicBlock*> Latches; 146 Headers.push_back(Header); 147 Latches.push_back(LatchBlock); 148 149 for (unsigned It = 1; It != Count; ++It) { 150 char SuffixBuffer[100]; 151 sprintf(SuffixBuffer, ".%d", It); 152 153 std::vector<BasicBlock*> NewBlocks; 154 155 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(), 156 E = LoopBlocks.end(); BB != E; ++BB) { 157 ValueMapTy ValueMap; 158 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer); 159 Header->getParent()->getBasicBlockList().push_back(New); 160 161 // Loop over all of the PHI nodes in the block, changing them to use the 162 // incoming values from the previous block. 163 if (*BB == Header) 164 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 165 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]); 166 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 167 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 168 if (It > 1 && L->contains(InValI->getParent())) 169 InVal = LastValueMap[InValI]; 170 ValueMap[OrigPHINode[i]] = InVal; 171 New->getInstList().erase(NewPHI); 172 } 173 174 // Update our running map of newest clones 175 LastValueMap[*BB] = New; 176 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end(); 177 VI != VE; ++VI) 178 LastValueMap[VI->first] = VI->second; 179 180 L->addBasicBlockToLoop(New, LI->getBase()); 181 182 // Add phi entries for newly created values to all exit blocks except 183 // the successor of the latch block. The successor of the exit block will 184 // be updated specially after unrolling all the way. 185 if (*BB != LatchBlock) 186 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end(); 187 UI != UE;) { 188 Instruction *UseInst = cast<Instruction>(*UI); 189 ++UI; 190 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) { 191 PHINode *phi = cast<PHINode>(UseInst); 192 Value *Incoming = phi->getIncomingValueForBlock(*BB); 193 phi->addIncoming(Incoming, New); 194 } 195 } 196 197 // Keep track of new headers and latches as we create them, so that 198 // we can insert the proper branches later. 199 if (*BB == Header) 200 Headers.push_back(New); 201 if (*BB == LatchBlock) { 202 Latches.push_back(New); 203 204 // Also, clear out the new latch's back edge so that it doesn't look 205 // like a new loop, so that it's amenable to being merged with adjacent 206 // blocks later on. 207 TerminatorInst *Term = New->getTerminator(); 208 assert(L->contains(Term->getSuccessor(!ContinueOnTrue))); 209 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit); 210 Term->setSuccessor(!ContinueOnTrue, NULL); 211 } 212 213 NewBlocks.push_back(New); 214 } 215 216 // Remap all instructions in the most recent iteration 217 for (unsigned i = 0; i < NewBlocks.size(); ++i) 218 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 219 E = NewBlocks[i]->end(); I != E; ++I) 220 RemapInstruction(I, LastValueMap); 221 } 222 223 // The latch block exits the loop. If there are any PHI nodes in the 224 // successor blocks, update them to use the appropriate values computed as the 225 // last iteration of the loop. 226 if (Count != 1) { 227 SmallPtrSet<PHINode*, 8> Users; 228 for (Value::use_iterator UI = LatchBlock->use_begin(), 229 UE = LatchBlock->use_end(); UI != UE; ++UI) 230 if (PHINode *phi = dyn_cast<PHINode>(*UI)) 231 Users.insert(phi); 232 233 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]); 234 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end(); 235 SI != SE; ++SI) { 236 PHINode *PN = *SI; 237 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 238 // If this value was defined in the loop, take the value defined by the 239 // last iteration of the loop. 240 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 241 if (L->contains(InValI->getParent())) 242 InVal = LastValueMap[InVal]; 243 } 244 PN->addIncoming(InVal, LastIterationBB); 245 } 246 } 247 248 // Now, if we're doing complete unrolling, loop over the PHI nodes in the 249 // original block, setting them to their incoming values. 250 if (CompletelyUnroll) { 251 BasicBlock *Preheader = L->getLoopPreheader(); 252 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 253 PHINode *PN = OrigPHINode[i]; 254 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 255 Header->getInstList().erase(PN); 256 } 257 } 258 259 // Now that all the basic blocks for the unrolled iterations are in place, 260 // set up the branches to connect them. 261 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 262 // The original branch was replicated in each unrolled iteration. 263 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 264 265 // The branch destination. 266 unsigned j = (i + 1) % e; 267 BasicBlock *Dest = Headers[j]; 268 bool NeedConditional = true; 269 270 // For a complete unroll, make the last iteration end with a branch 271 // to the exit block. 272 if (CompletelyUnroll && j == 0) { 273 Dest = LoopExit; 274 NeedConditional = false; 275 } 276 277 // If we know the trip count or a multiple of it, we can safely use an 278 // unconditional branch for some iterations. 279 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) { 280 NeedConditional = false; 281 } 282 283 if (NeedConditional) { 284 // Update the conditional branch's successor for the following 285 // iteration. 286 Term->setSuccessor(!ContinueOnTrue, Dest); 287 } else { 288 Term->setUnconditionalDest(Dest); 289 // Merge adjacent basic blocks, if possible. 290 if (BasicBlock *Fold = MergeBlockIntoPredecessor(Dest, LI)) { 291 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 292 std::replace(Headers.begin(), Headers.end(), Dest, Fold); 293 } 294 } 295 } 296 297 // At this point, the code is well formed. We now do a quick sweep over the 298 // inserted code, doing constant propagation and dead code elimination as we 299 // go. 300 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks(); 301 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(), 302 BBE = NewLoopBlocks.end(); BB != BBE; ++BB) 303 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) { 304 Instruction *Inst = I++; 305 306 if (isInstructionTriviallyDead(Inst)) 307 (*BB)->getInstList().erase(Inst); 308 else if (Constant *C = ConstantFoldInstruction(Inst, 309 Header->getContext())) { 310 Inst->replaceAllUsesWith(C); 311 (*BB)->getInstList().erase(Inst); 312 } 313 } 314 315 NumCompletelyUnrolled += CompletelyUnroll; 316 ++NumUnrolled; 317 // Remove the loop from the LoopPassManager if it's completely removed. 318 if (CompletelyUnroll && LPM != NULL) 319 LPM->deleteLoopFromQueue(L); 320 321 // If we didn't completely unroll the loop, it should still be in LCSSA form. 322 if (!CompletelyUnroll) 323 assert(L->isLCSSAForm()); 324 325 return true; 326} 327