LLVM API Documentation

LoopUnroll.cpp
Go to the documentation of this file.
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 // The process of unrolling can produce extraneous basic blocks linked with
00015 // unconditional branches.  This will be corrected in the future.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #define DEBUG_TYPE "loop-unroll"
00020 #include "llvm/Transforms/Utils/UnrollLoop.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/InstructionSimplify.h"
00023 #include "llvm/Analysis/LoopIterator.h"
00024 #include "llvm/Analysis/LoopPass.h"
00025 #include "llvm/Analysis/ScalarEvolution.h"
00026 #include "llvm/IR/BasicBlock.h"
00027 #include "llvm/IR/Dominators.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00031 #include "llvm/Transforms/Utils/Cloning.h"
00032 #include "llvm/Transforms/Utils/Local.h"
00033 #include "llvm/Transforms/Utils/LoopUtils.h"
00034 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00035 using namespace llvm;
00036 
00037 // TODO: Should these be here or in LoopUnroll?
00038 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
00039 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
00040 
00041 /// RemapInstruction - Convert the instruction operands from referencing the
00042 /// current values into those specified by VMap.
00043 static inline void RemapInstruction(Instruction *I,
00044                                     ValueToValueMapTy &VMap) {
00045   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
00046     Value *Op = I->getOperand(op);
00047     ValueToValueMapTy::iterator It = VMap.find(Op);
00048     if (It != VMap.end())
00049       I->setOperand(op, It->second);
00050   }
00051 
00052   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00053     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00054       ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
00055       if (It != VMap.end())
00056         PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
00057     }
00058   }
00059 }
00060 
00061 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
00062 /// only has one predecessor, and that predecessor only has one successor.
00063 /// The LoopInfo Analysis that is passed will be kept consistent.
00064 /// Returns the new combined block.
00065 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
00066                                             LPPassManager *LPM) {
00067   // Merge basic blocks into their predecessor if there is only one distinct
00068   // pred, and if there is only one distinct successor of the predecessor, and
00069   // if there are no PHI nodes.
00070   BasicBlock *OnlyPred = BB->getSinglePredecessor();
00071   if (!OnlyPred) return 0;
00072 
00073   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
00074     return 0;
00075 
00076   DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
00077 
00078   // Resolve any PHI nodes at the start of the block.  They are all
00079   // guaranteed to have exactly one entry if they exist, unless there are
00080   // multiple duplicate (but guaranteed to be equal) entries for the
00081   // incoming edges.  This occurs when there are multiple edges from
00082   // OnlyPred to OnlySucc.
00083   FoldSingleEntryPHINodes(BB);
00084 
00085   // Delete the unconditional branch from the predecessor...
00086   OnlyPred->getInstList().pop_back();
00087 
00088   // Make all PHI nodes that referred to BB now refer to Pred as their
00089   // source...
00090   BB->replaceAllUsesWith(OnlyPred);
00091 
00092   // Move all definitions in the successor to the predecessor...
00093   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
00094 
00095   // OldName will be valid until erased.
00096   StringRef OldName = BB->getName();
00097 
00098   // Erase basic block from the function...
00099 
00100   // ScalarEvolution holds references to loop exit blocks.
00101   if (LPM) {
00102     if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
00103       if (Loop *L = LI->getLoopFor(BB))
00104         SE->forgetLoop(L);
00105     }
00106   }
00107   LI->removeBlock(BB);
00108 
00109   // Inherit predecessor's name if it exists...
00110   if (!OldName.empty() && !OnlyPred->hasName())
00111     OnlyPred->setName(OldName);
00112 
00113   BB->eraseFromParent();
00114 
00115   return OnlyPred;
00116 }
00117 
00118 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
00119 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
00120 /// can only fail when the loop's latch block is not terminated by a conditional
00121 /// branch instruction. However, if the trip count (and multiple) are not known,
00122 /// loop unrolling will mostly produce more code that is no faster.
00123 ///
00124 /// TripCount is generally defined as the number of times the loop header
00125 /// executes. UnrollLoop relaxes the definition to permit early exits: here
00126 /// TripCount is the iteration on which control exits LatchBlock if no early
00127 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
00128 /// terminates LatchBlock in order to remove unnecesssary instances of the
00129 /// test. In other words, control may exit the loop prior to TripCount
00130 /// iterations via an early branch, but control may not exit the loop from the
00131 /// LatchBlock's terminator prior to TripCount iterations.
00132 ///
00133 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
00134 /// execute without exiting the loop.
00135 ///
00136 /// The LoopInfo Analysis that is passed will be kept consistent.
00137 ///
00138 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
00139 /// removed from the LoopPassManager as well. LPM can also be NULL.
00140 ///
00141 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
00142 /// available from the Pass it must also preserve those analyses.
00143 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
00144                       bool AllowRuntime, unsigned TripMultiple,
00145                       LoopInfo *LI, Pass *PP, LPPassManager *LPM) {
00146   BasicBlock *Preheader = L->getLoopPreheader();
00147   if (!Preheader) {
00148     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
00149     return false;
00150   }
00151 
00152   BasicBlock *LatchBlock = L->getLoopLatch();
00153   if (!LatchBlock) {
00154     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
00155     return false;
00156   }
00157 
00158   // Loops with indirectbr cannot be cloned.
00159   if (!L->isSafeToClone()) {
00160     DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
00161     return false;
00162   }
00163 
00164   BasicBlock *Header = L->getHeader();
00165   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
00166 
00167   if (!BI || BI->isUnconditional()) {
00168     // The loop-rotate pass can be helpful to avoid this in many cases.
00169     DEBUG(dbgs() <<
00170              "  Can't unroll; loop not terminated by a conditional branch.\n");
00171     return false;
00172   }
00173 
00174   if (Header->hasAddressTaken()) {
00175     // The loop-rotate pass can be helpful to avoid this in many cases.
00176     DEBUG(dbgs() <<
00177           "  Won't unroll loop: address of header block is taken.\n");
00178     return false;
00179   }
00180 
00181   if (TripCount != 0)
00182     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
00183   if (TripMultiple != 1)
00184     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
00185 
00186   // Effectively "DCE" unrolled iterations that are beyond the tripcount
00187   // and will never be executed.
00188   if (TripCount != 0 && Count > TripCount)
00189     Count = TripCount;
00190 
00191   // Don't enter the unroll code if there is nothing to do. This way we don't
00192   // need to support "partial unrolling by 1".
00193   if (TripCount == 0 && Count < 2)
00194     return false;
00195 
00196   assert(Count > 0);
00197   assert(TripMultiple > 0);
00198   assert(TripCount == 0 || TripCount % TripMultiple == 0);
00199 
00200   // Are we eliminating the loop control altogether?
00201   bool CompletelyUnroll = Count == TripCount;
00202 
00203   // We assume a run-time trip count if the compiler cannot
00204   // figure out the loop trip count and the unroll-runtime
00205   // flag is specified.
00206   bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
00207 
00208   if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
00209     return false;
00210 
00211   // Notify ScalarEvolution that the loop will be substantially changed,
00212   // if not outright eliminated.
00213   if (PP) {
00214     ScalarEvolution *SE = PP->getAnalysisIfAvailable<ScalarEvolution>();
00215     if (SE)
00216       SE->forgetLoop(L);
00217   }
00218 
00219   // If we know the trip count, we know the multiple...
00220   unsigned BreakoutTrip = 0;
00221   if (TripCount != 0) {
00222     BreakoutTrip = TripCount % Count;
00223     TripMultiple = 0;
00224   } else {
00225     // Figure out what multiple to use.
00226     BreakoutTrip = TripMultiple =
00227       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
00228   }
00229 
00230   if (CompletelyUnroll) {
00231     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
00232           << " with trip count " << TripCount << "!\n");
00233   } else {
00234     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
00235           << " by " << Count);
00236     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
00237       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
00238     } else if (TripMultiple != 1) {
00239       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
00240     } else if (RuntimeTripCount) {
00241       DEBUG(dbgs() << " with run-time trip count");
00242     }
00243     DEBUG(dbgs() << "!\n");
00244   }
00245 
00246   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
00247   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
00248 
00249   // For the first iteration of the loop, we should use the precloned values for
00250   // PHI nodes.  Insert associations now.
00251   ValueToValueMapTy LastValueMap;
00252   std::vector<PHINode*> OrigPHINode;
00253   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00254     OrigPHINode.push_back(cast<PHINode>(I));
00255   }
00256 
00257   std::vector<BasicBlock*> Headers;
00258   std::vector<BasicBlock*> Latches;
00259   Headers.push_back(Header);
00260   Latches.push_back(LatchBlock);
00261 
00262   // The current on-the-fly SSA update requires blocks to be processed in
00263   // reverse postorder so that LastValueMap contains the correct value at each
00264   // exit.
00265   LoopBlocksDFS DFS(L);
00266   DFS.perform(LI);
00267 
00268   // Stash the DFS iterators before adding blocks to the loop.
00269   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
00270   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
00271 
00272   for (unsigned It = 1; It != Count; ++It) {
00273     std::vector<BasicBlock*> NewBlocks;
00274 
00275     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
00276       ValueToValueMapTy VMap;
00277       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
00278       Header->getParent()->getBasicBlockList().push_back(New);
00279 
00280       // Loop over all of the PHI nodes in the block, changing them to use the
00281       // incoming values from the previous block.
00282       if (*BB == Header)
00283         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00284           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
00285           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
00286           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
00287             if (It > 1 && L->contains(InValI))
00288               InVal = LastValueMap[InValI];
00289           VMap[OrigPHINode[i]] = InVal;
00290           New->getInstList().erase(NewPHI);
00291         }
00292 
00293       // Update our running map of newest clones
00294       LastValueMap[*BB] = New;
00295       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
00296            VI != VE; ++VI)
00297         LastValueMap[VI->first] = VI->second;
00298 
00299       L->addBasicBlockToLoop(New, LI->getBase());
00300 
00301       // Add phi entries for newly created values to all exit blocks.
00302       for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
00303            SI != SE; ++SI) {
00304         if (L->contains(*SI))
00305           continue;
00306         for (BasicBlock::iterator BBI = (*SI)->begin();
00307              PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
00308           Value *Incoming = phi->getIncomingValueForBlock(*BB);
00309           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
00310           if (It != LastValueMap.end())
00311             Incoming = It->second;
00312           phi->addIncoming(Incoming, New);
00313         }
00314       }
00315       // Keep track of new headers and latches as we create them, so that
00316       // we can insert the proper branches later.
00317       if (*BB == Header)
00318         Headers.push_back(New);
00319       if (*BB == LatchBlock)
00320         Latches.push_back(New);
00321 
00322       NewBlocks.push_back(New);
00323     }
00324 
00325     // Remap all instructions in the most recent iteration
00326     for (unsigned i = 0; i < NewBlocks.size(); ++i)
00327       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00328            E = NewBlocks[i]->end(); I != E; ++I)
00329         ::RemapInstruction(I, LastValueMap);
00330   }
00331 
00332   // Loop over the PHI nodes in the original block, setting incoming values.
00333   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00334     PHINode *PN = OrigPHINode[i];
00335     if (CompletelyUnroll) {
00336       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
00337       Header->getInstList().erase(PN);
00338     }
00339     else if (Count > 1) {
00340       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
00341       // If this value was defined in the loop, take the value defined by the
00342       // last iteration of the loop.
00343       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
00344         if (L->contains(InValI))
00345           InVal = LastValueMap[InVal];
00346       }
00347       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
00348       PN->addIncoming(InVal, Latches.back());
00349     }
00350   }
00351 
00352   // Now that all the basic blocks for the unrolled iterations are in place,
00353   // set up the branches to connect them.
00354   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
00355     // The original branch was replicated in each unrolled iteration.
00356     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
00357 
00358     // The branch destination.
00359     unsigned j = (i + 1) % e;
00360     BasicBlock *Dest = Headers[j];
00361     bool NeedConditional = true;
00362 
00363     if (RuntimeTripCount && j != 0) {
00364       NeedConditional = false;
00365     }
00366 
00367     // For a complete unroll, make the last iteration end with a branch
00368     // to the exit block.
00369     if (CompletelyUnroll && j == 0) {
00370       Dest = LoopExit;
00371       NeedConditional = false;
00372     }
00373 
00374     // If we know the trip count or a multiple of it, we can safely use an
00375     // unconditional branch for some iterations.
00376     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
00377       NeedConditional = false;
00378     }
00379 
00380     if (NeedConditional) {
00381       // Update the conditional branch's successor for the following
00382       // iteration.
00383       Term->setSuccessor(!ContinueOnTrue, Dest);
00384     } else {
00385       // Remove phi operands at this loop exit
00386       if (Dest != LoopExit) {
00387         BasicBlock *BB = Latches[i];
00388         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
00389              SI != SE; ++SI) {
00390           if (*SI == Headers[i])
00391             continue;
00392           for (BasicBlock::iterator BBI = (*SI)->begin();
00393                PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
00394             Phi->removeIncomingValue(BB, false);
00395           }
00396         }
00397       }
00398       // Replace the conditional branch with an unconditional one.
00399       BranchInst::Create(Dest, Term);
00400       Term->eraseFromParent();
00401     }
00402   }
00403 
00404   // Merge adjacent basic blocks, if possible.
00405   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
00406     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
00407     if (Term->isUnconditional()) {
00408       BasicBlock *Dest = Term->getSuccessor(0);
00409       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
00410         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
00411     }
00412   }
00413 
00414   DominatorTree *DT = 0;
00415   if (PP) {
00416     // FIXME: Reconstruct dom info, because it is not preserved properly.
00417     // Incrementally updating domtree after loop unrolling would be easy.
00418     if (DominatorTreeWrapperPass *DTWP =
00419             PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00420       DT = &DTWP->getDomTree();
00421       DT->recalculate(*L->getHeader()->getParent());
00422     }
00423 
00424     // Simplify any new induction variables in the partially unrolled loop.
00425     ScalarEvolution *SE = PP->getAnalysisIfAvailable<ScalarEvolution>();
00426     if (SE && !CompletelyUnroll) {
00427       SmallVector<WeakVH, 16> DeadInsts;
00428       simplifyLoopIVs(L, SE, LPM, DeadInsts);
00429 
00430       // Aggressively clean up dead instructions that simplifyLoopIVs already
00431       // identified. Any remaining should be cleaned up below.
00432       while (!DeadInsts.empty())
00433         if (Instruction *Inst =
00434             dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
00435           RecursivelyDeleteTriviallyDeadInstructions(Inst);
00436     }
00437   }
00438   // At this point, the code is well formed.  We now do a quick sweep over the
00439   // inserted code, doing constant propagation and dead code elimination as we
00440   // go.
00441   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
00442   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
00443        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
00444     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
00445       Instruction *Inst = I++;
00446 
00447       if (isInstructionTriviallyDead(Inst))
00448         (*BB)->getInstList().erase(Inst);
00449       else if (Value *V = SimplifyInstruction(Inst))
00450         if (LI->replacementPreservesLCSSAForm(Inst, V)) {
00451           Inst->replaceAllUsesWith(V);
00452           (*BB)->getInstList().erase(Inst);
00453         }
00454     }
00455 
00456   NumCompletelyUnrolled += CompletelyUnroll;
00457   ++NumUnrolled;
00458 
00459   Loop *OuterL = L->getParentLoop();
00460   // Remove the loop from the LoopPassManager if it's completely removed.
00461   if (CompletelyUnroll && LPM != NULL)
00462     LPM->deleteLoopFromQueue(L);
00463 
00464   // If we have a pass and a DominatorTree we should re-simplify impacted loops
00465   // to ensure subsequent analyses can rely on this form. We want to simplify
00466   // at least one layer outside of the loop that was unrolled so that any
00467   // changes to the parent loop exposed by the unrolling are considered.
00468   if (PP && DT) {
00469     if (!OuterL && !CompletelyUnroll)
00470       OuterL = L;
00471     if (OuterL) {
00472       ScalarEvolution *SE = PP->getAnalysisIfAvailable<ScalarEvolution>();
00473       simplifyLoop(OuterL, DT, LI, PP, /*AliasAnalysis*/ 0, SE);
00474       formLCSSARecursively(*OuterL, *DT, SE);
00475     }
00476   }
00477 
00478   return true;
00479 }