LLVM API Documentation
00001 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements some loop unrolling utilities. It does not define any 00011 // actual pass or policy, but provides a single function to perform loop 00012 // unrolling. 00013 // 00014 // It works best when loops have been canonicalized by the -indvars pass, 00015 // allowing it to determine the trip counts of loops easily. 00016 // 00017 // The process of unrolling can produce extraneous basic blocks linked with 00018 // unconditional branches. This will be corrected in the future. 00019 //===----------------------------------------------------------------------===// 00020 00021 #define DEBUG_TYPE "loop-unroll" 00022 #include "llvm/Transforms/Utils/UnrollLoop.h" 00023 #include "llvm/BasicBlock.h" 00024 #include "llvm/ADT/Statistic.h" 00025 #include "llvm/Analysis/ConstantFolding.h" 00026 #include "llvm/Analysis/LoopPass.h" 00027 #include "llvm/Support/Debug.h" 00028 #include "llvm/Support/raw_ostream.h" 00029 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00030 #include "llvm/Transforms/Utils/Cloning.h" 00031 #include "llvm/Transforms/Utils/Local.h" 00032 #include <cstdio> 00033 00034 using namespace llvm; 00035 00036 // TODO: Should these be here or in LoopUnroll? 00037 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled"); 00038 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)"); 00039 00040 /// RemapInstruction - Convert the instruction operands from referencing the 00041 /// current values into those specified by ValueMap. 00042 static inline void RemapInstruction(Instruction *I, 00043 DenseMap<const Value *, Value*> &ValueMap) { 00044 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 00045 Value *Op = I->getOperand(op); 00046 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op); 00047 if (It != ValueMap.end()) Op = It->second; 00048 I->setOperand(op, Op); 00049 } 00050 } 00051 00052 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it 00053 /// only has one predecessor, and that predecessor only has one successor. 00054 /// The LoopInfo Analysis that is passed will be kept consistent. 00055 /// Returns the new combined block. 00056 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) { 00057 // Merge basic blocks into their predecessor if there is only one distinct 00058 // pred, and if there is only one distinct successor of the predecessor, and 00059 // if there are no PHI nodes. 00060 BasicBlock *OnlyPred = BB->getSinglePredecessor(); 00061 if (!OnlyPred) return 0; 00062 00063 if (OnlyPred->getTerminator()->getNumSuccessors() != 1) 00064 return 0; 00065 00066 DOUT << "Merging: " << *BB << "into: " << *OnlyPred; 00067 00068 // Resolve any PHI nodes at the start of the block. They are all 00069 // guaranteed to have exactly one entry if they exist, unless there are 00070 // multiple duplicate (but guaranteed to be equal) entries for the 00071 // incoming edges. This occurs when there are multiple edges from 00072 // OnlyPred to OnlySucc. 00073 FoldSingleEntryPHINodes(BB); 00074 00075 // Delete the unconditional branch from the predecessor... 00076 OnlyPred->getInstList().pop_back(); 00077 00078 // Move all definitions in the successor to the predecessor... 00079 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList()); 00080 00081 // Make all PHI nodes that referred to BB now refer to Pred as their 00082 // source... 00083 BB->replaceAllUsesWith(OnlyPred); 00084 00085 std::string OldName = BB->getName(); 00086 00087 // Erase basic block from the function... 00088 LI->removeBlock(BB); 00089 BB->eraseFromParent(); 00090 00091 // Inherit predecessor's name if it exists... 00092 if (!OldName.empty() && !OnlyPred->hasName()) 00093 OnlyPred->setName(OldName); 00094 00095 return OnlyPred; 00096 } 00097 00098 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true 00099 /// if unrolling was succesful, or false if the loop was unmodified. Unrolling 00100 /// can only fail when the loop's latch block is not terminated by a conditional 00101 /// branch instruction. However, if the trip count (and multiple) are not known, 00102 /// loop unrolling will mostly produce more code that is no faster. 00103 /// 00104 /// The LoopInfo Analysis that is passed will be kept consistent. 00105 /// 00106 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be 00107 /// removed from the LoopPassManager as well. LPM can also be NULL. 00108 bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) { 00109 assert(L->isLCSSAForm()); 00110 00111 BasicBlock *Header = L->getHeader(); 00112 BasicBlock *LatchBlock = L->getLoopLatch(); 00113 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 00114 00115 if (!BI || BI->isUnconditional()) { 00116 // The loop-rotate pass can be helpful to avoid this in many cases. 00117 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n"; 00118 return false; 00119 } 00120 00121 // Find trip count 00122 unsigned TripCount = L->getSmallConstantTripCount(); 00123 // Find trip multiple if count is not available 00124 unsigned TripMultiple = 1; 00125 if (TripCount == 0) 00126 TripMultiple = L->getSmallConstantTripMultiple(); 00127 00128 if (TripCount != 0) 00129 DOUT << " Trip Count = " << TripCount << "\n"; 00130 if (TripMultiple != 1) 00131 DOUT << " Trip Multiple = " << TripMultiple << "\n"; 00132 00133 // Effectively "DCE" unrolled iterations that are beyond the tripcount 00134 // and will never be executed. 00135 if (TripCount != 0 && Count > TripCount) 00136 Count = TripCount; 00137 00138 assert(Count > 0); 00139 assert(TripMultiple > 0); 00140 assert(TripCount == 0 || TripCount % TripMultiple == 0); 00141 00142 // Are we eliminating the loop control altogether? 00143 bool CompletelyUnroll = Count == TripCount; 00144 00145 // If we know the trip count, we know the multiple... 00146 unsigned BreakoutTrip = 0; 00147 if (TripCount != 0) { 00148 BreakoutTrip = TripCount % Count; 00149 TripMultiple = 0; 00150 } else { 00151 // Figure out what multiple to use. 00152 BreakoutTrip = TripMultiple = 00153 (unsigned)GreatestCommonDivisor64(Count, TripMultiple); 00154 } 00155 00156 if (CompletelyUnroll) { 00157 DEBUG(errs() << "COMPLETELY UNROLLING loop %" << Header->getName() 00158 << " with trip count " << TripCount << "!\n"); 00159 } else { 00160 DEBUG(errs() << "UNROLLING loop %" << Header->getName() 00161 << " by " << Count); 00162 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) { 00163 DOUT << " with a breakout at trip " << BreakoutTrip; 00164 } else if (TripMultiple != 1) { 00165 DOUT << " with " << TripMultiple << " trips per branch"; 00166 } 00167 DOUT << "!\n"; 00168 } 00169 00170 std::vector<BasicBlock*> LoopBlocks = L->getBlocks(); 00171 00172 bool ContinueOnTrue = L->contains(BI->getSuccessor(0)); 00173 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue); 00174 00175 // For the first iteration of the loop, we should use the precloned values for 00176 // PHI nodes. Insert associations now. 00177 typedef DenseMap<const Value*, Value*> ValueMapTy; 00178 ValueMapTy LastValueMap; 00179 std::vector<PHINode*> OrigPHINode; 00180 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 00181 PHINode *PN = cast<PHINode>(I); 00182 OrigPHINode.push_back(PN); 00183 if (Instruction *I = 00184 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock))) 00185 if (L->contains(I->getParent())) 00186 LastValueMap[I] = I; 00187 } 00188 00189 std::vector<BasicBlock*> Headers; 00190 std::vector<BasicBlock*> Latches; 00191 Headers.push_back(Header); 00192 Latches.push_back(LatchBlock); 00193 00194 for (unsigned It = 1; It != Count; ++It) { 00195 char SuffixBuffer[100]; 00196 sprintf(SuffixBuffer, ".%d", It); 00197 00198 std::vector<BasicBlock*> NewBlocks; 00199 00200 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(), 00201 E = LoopBlocks.end(); BB != E; ++BB) { 00202 ValueMapTy ValueMap; 00203 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer); 00204 Header->getParent()->getBasicBlockList().push_back(New); 00205 00206 // Loop over all of the PHI nodes in the block, changing them to use the 00207 // incoming values from the previous block. 00208 if (*BB == Header) 00209 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 00210 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]); 00211 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 00212 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 00213 if (It > 1 && L->contains(InValI->getParent())) 00214 InVal = LastValueMap[InValI]; 00215 ValueMap[OrigPHINode[i]] = InVal; 00216 New->getInstList().erase(NewPHI); 00217 } 00218 00219 // Update our running map of newest clones 00220 LastValueMap[*BB] = New; 00221 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end(); 00222 VI != VE; ++VI) 00223 LastValueMap[VI->first] = VI->second; 00224 00225 L->addBasicBlockToLoop(New, LI->getBase()); 00226 00227 // Add phi entries for newly created values to all exit blocks except 00228 // the successor of the latch block. The successor of the exit block will 00229 // be updated specially after unrolling all the way. 00230 if (*BB != LatchBlock) 00231 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end(); 00232 UI != UE;) { 00233 Instruction *UseInst = cast<Instruction>(*UI); 00234 ++UI; 00235 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) { 00236 PHINode *phi = cast<PHINode>(UseInst); 00237 Value *Incoming = phi->getIncomingValueForBlock(*BB); 00238 phi->addIncoming(Incoming, New); 00239 } 00240 } 00241 00242 // Keep track of new headers and latches as we create them, so that 00243 // we can insert the proper branches later. 00244 if (*BB == Header) 00245 Headers.push_back(New); 00246 if (*BB == LatchBlock) { 00247 Latches.push_back(New); 00248 00249 // Also, clear out the new latch's back edge so that it doesn't look 00250 // like a new loop, so that it's amenable to being merged with adjacent 00251 // blocks later on. 00252 TerminatorInst *Term = New->getTerminator(); 00253 assert(L->contains(Term->getSuccessor(!ContinueOnTrue))); 00254 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit); 00255 Term->setSuccessor(!ContinueOnTrue, NULL); 00256 } 00257 00258 NewBlocks.push_back(New); 00259 } 00260 00261 // Remap all instructions in the most recent iteration 00262 for (unsigned i = 0; i < NewBlocks.size(); ++i) 00263 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 00264 E = NewBlocks[i]->end(); I != E; ++I) 00265 RemapInstruction(I, LastValueMap); 00266 } 00267 00268 // The latch block exits the loop. If there are any PHI nodes in the 00269 // successor blocks, update them to use the appropriate values computed as the 00270 // last iteration of the loop. 00271 if (Count != 1) { 00272 SmallPtrSet<PHINode*, 8> Users; 00273 for (Value::use_iterator UI = LatchBlock->use_begin(), 00274 UE = LatchBlock->use_end(); UI != UE; ++UI) 00275 if (PHINode *phi = dyn_cast<PHINode>(*UI)) 00276 Users.insert(phi); 00277 00278 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]); 00279 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end(); 00280 SI != SE; ++SI) { 00281 PHINode *PN = *SI; 00282 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 00283 // If this value was defined in the loop, take the value defined by the 00284 // last iteration of the loop. 00285 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 00286 if (L->contains(InValI->getParent())) 00287 InVal = LastValueMap[InVal]; 00288 } 00289 PN->addIncoming(InVal, LastIterationBB); 00290 } 00291 } 00292 00293 // Now, if we're doing complete unrolling, loop over the PHI nodes in the 00294 // original block, setting them to their incoming values. 00295 if (CompletelyUnroll) { 00296 BasicBlock *Preheader = L->getLoopPreheader(); 00297 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 00298 PHINode *PN = OrigPHINode[i]; 00299 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 00300 Header->getInstList().erase(PN); 00301 } 00302 } 00303 00304 // Now that all the basic blocks for the unrolled iterations are in place, 00305 // set up the branches to connect them. 00306 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 00307 // The original branch was replicated in each unrolled iteration. 00308 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 00309 00310 // The branch destination. 00311 unsigned j = (i + 1) % e; 00312 BasicBlock *Dest = Headers[j]; 00313 bool NeedConditional = true; 00314 00315 // For a complete unroll, make the last iteration end with a branch 00316 // to the exit block. 00317 if (CompletelyUnroll && j == 0) { 00318 Dest = LoopExit; 00319 NeedConditional = false; 00320 } 00321 00322 // If we know the trip count or a multiple of it, we can safely use an 00323 // unconditional branch for some iterations. 00324 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) { 00325 NeedConditional = false; 00326 } 00327 00328 if (NeedConditional) { 00329 // Update the conditional branch's successor for the following 00330 // iteration. 00331 Term->setSuccessor(!ContinueOnTrue, Dest); 00332 } else { 00333 Term->setUnconditionalDest(Dest); 00334 // Merge adjacent basic blocks, if possible. 00335 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) { 00336 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 00337 std::replace(Headers.begin(), Headers.end(), Dest, Fold); 00338 } 00339 } 00340 } 00341 00342 // At this point, the code is well formed. We now do a quick sweep over the 00343 // inserted code, doing constant propagation and dead code elimination as we 00344 // go. 00345 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks(); 00346 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(), 00347 BBE = NewLoopBlocks.end(); BB != BBE; ++BB) 00348 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) { 00349 Instruction *Inst = I++; 00350 00351 if (isInstructionTriviallyDead(Inst)) 00352 (*BB)->getInstList().erase(Inst); 00353 else if (Constant *C = ConstantFoldInstruction(Inst, 00354 Header->getContext())) { 00355 Inst->replaceAllUsesWith(C); 00356 (*BB)->getInstList().erase(Inst); 00357 } 00358 } 00359 00360 NumCompletelyUnrolled += CompletelyUnroll; 00361 ++NumUnrolled; 00362 // Remove the loop from the LoopPassManager if it's completely removed. 00363 if (CompletelyUnroll && LPM != NULL) 00364 LPM->deleteLoopFromQueue(L); 00365 00366 // If we didn't completely unroll the loop, it should still be in LCSSA form. 00367 if (!CompletelyUnroll) 00368 assert(L->isLCSSAForm()); 00369 00370 return true; 00371 }