LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

LoopUnroll.cpp

Go to the documentation of this file.
00001 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass implements a simple loop unroller.  It works best when loops have
00011 // been canonicalized by the -indvars pass, allowing it to determine the trip
00012 // counts of loops easily.
00013 //
00014 // This pass is currently extremely limited.  It only currently only unrolls
00015 // single basic block loops that execute a constant number of times.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #define DEBUG_TYPE "loop-unroll"
00020 #include "llvm/Transforms/Scalar.h"
00021 #include "llvm/Constants.h"
00022 #include "llvm/Function.h"
00023 #include "llvm/Instructions.h"
00024 #include "llvm/Analysis/LoopInfo.h"
00025 #include "llvm/Transforms/Utils/Cloning.h"
00026 #include "llvm/Transforms/Utils/Local.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/ADT/Statistic.h"
00030 #include "llvm/ADT/STLExtras.h"
00031 #include "llvm/IntrinsicInst.h"
00032 #include <cstdio>
00033 #include <set>
00034 #include <algorithm>
00035 
00036 using namespace llvm;
00037 
00038 namespace {
00039   Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
00040 
00041   cl::opt<unsigned>
00042   UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
00043                   cl::desc("The cut-off point for loop unrolling"));
00044 
00045   class LoopUnroll : public FunctionPass {
00046     LoopInfo *LI;  // The current loop information
00047   public:
00048     virtual bool runOnFunction(Function &F);
00049     bool visitLoop(Loop *L);
00050 
00051     /// This transformation requires natural loop information & requires that
00052     /// loop preheaders be inserted into the CFG...
00053     ///
00054     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00055       AU.addRequiredID(LoopSimplifyID);
00056       AU.addRequired<LoopInfo>();
00057       AU.addPreserved<LoopInfo>();
00058     }
00059   };
00060   RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
00061 }
00062 
00063 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
00064 
00065 bool LoopUnroll::runOnFunction(Function &F) {
00066   bool Changed = false;
00067   LI = &getAnalysis<LoopInfo>();
00068 
00069   // Transform all the top-level loops.  Copy the loop list so that the child
00070   // can update the loop tree if it needs to delete the loop.
00071   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
00072   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
00073     Changed |= visitLoop(SubLoops[i]);
00074 
00075   return Changed;
00076 }
00077 
00078 /// ApproximateLoopSize - Approximate the size of the loop after it has been
00079 /// unrolled.
00080 static unsigned ApproximateLoopSize(const Loop *L) {
00081   unsigned Size = 0;
00082   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
00083     BasicBlock *BB = L->getBlocks()[i];
00084     Instruction *Term = BB->getTerminator();
00085     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00086       if (isa<PHINode>(I) && BB == L->getHeader()) {
00087         // Ignore PHI nodes in the header.
00088       } else if (I->hasOneUse() && I->use_back() == Term) {
00089         // Ignore instructions only used by the loop terminator.
00090       } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
00091   // Ignore debug instructions 
00092       } else {
00093         ++Size;
00094       }
00095 
00096       // TODO: Ignore expressions derived from PHI and constants if inval of phi
00097       // is a constant, or if operation is associative.  This will get induction
00098       // variables.
00099     }
00100   }
00101 
00102   return Size;
00103 }
00104 
00105 // RemapInstruction - Convert the instruction operands from referencing the 
00106 // current values into those specified by ValueMap.
00107 //
00108 static inline void RemapInstruction(Instruction *I, 
00109                                     std::map<const Value *, Value*> &ValueMap) {
00110   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
00111     Value *Op = I->getOperand(op);
00112     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
00113     if (It != ValueMap.end()) Op = It->second;
00114     I->setOperand(op, Op);
00115   }
00116 }
00117 
00118 bool LoopUnroll::visitLoop(Loop *L) {
00119   bool Changed = false;
00120 
00121   // Recurse through all subloops before we process this loop.  Copy the loop
00122   // list so that the child can update the loop tree if it needs to delete the
00123   // loop.
00124   std::vector<Loop*> SubLoops(L->begin(), L->end());
00125   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
00126     Changed |= visitLoop(SubLoops[i]);
00127 
00128   // We only handle single basic block loops right now.
00129   if (L->getBlocks().size() != 1)
00130     return Changed;
00131 
00132   BasicBlock *BB = L->getHeader();
00133   BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
00134   if (BI == 0) return Changed;  // Must end in a conditional branch
00135 
00136   ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
00137   if (!TripCountC) return Changed;  // Must have constant trip count!
00138 
00139   unsigned TripCount = TripCountC->getRawValue();
00140   if (TripCount != TripCountC->getRawValue() || TripCount == 0)
00141     return Changed; // More than 2^32 iterations???
00142 
00143   unsigned LoopSize = ApproximateLoopSize(L);
00144   DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
00145         << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
00146         << " Trip Count = " << TripCount << " - ");
00147   uint64_t Size = (uint64_t)LoopSize*(uint64_t)TripCount;
00148   if (Size > UnrollThreshold) {
00149     DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
00150     return Changed;
00151   }
00152   DEBUG(std::cerr << "UNROLLING!\n");
00153   
00154   BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
00155 
00156   // Create a new basic block to temporarily hold all of the cloned code.
00157   BasicBlock *NewBlock = new BasicBlock();
00158 
00159   // For the first iteration of the loop, we should use the precloned values for
00160   // PHI nodes.  Insert associations now.
00161   std::map<const Value*, Value*> LastValueMap;
00162   std::vector<PHINode*> OrigPHINode;
00163   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
00164     PHINode *PN = cast<PHINode>(I);
00165     OrigPHINode.push_back(PN);
00166     if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
00167       if (I->getParent() == BB)
00168         LastValueMap[I] = I;
00169   }
00170 
00171   // Remove the exit branch from the loop
00172   BB->getInstList().erase(BI);
00173 
00174   assert(TripCount != 0 && "Trip count of 0 is impossible!");
00175   for (unsigned It = 1; It != TripCount; ++It) {
00176     char SuffixBuffer[100];
00177     sprintf(SuffixBuffer, ".%d", It);
00178     std::map<const Value*, Value*> ValueMap;
00179     BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
00180 
00181     // Loop over all of the PHI nodes in the block, changing them to use the
00182     // incoming values from the previous block.
00183     for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00184       PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
00185       Value *InVal = NewPHI->getIncomingValueForBlock(BB);
00186       if (Instruction *InValI = dyn_cast<Instruction>(InVal))
00187         if (InValI->getParent() == BB)
00188           InVal = LastValueMap[InValI];
00189       ValueMap[OrigPHINode[i]] = InVal;
00190       New->getInstList().erase(NewPHI);
00191     }
00192 
00193     for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
00194       RemapInstruction(I, ValueMap);
00195 
00196     // Now that all of the instructions are remapped, splice them into the end
00197     // of the NewBlock.
00198     NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
00199     delete New;
00200 
00201     // LastValue map now contains values from this iteration.
00202     std::swap(LastValueMap, ValueMap);
00203   }
00204 
00205   // If there was more than one iteration, replace any uses of values computed
00206   // in the loop with values computed during the last iteration of the loop.
00207   if (TripCount != 1) {
00208     std::set<User*> Users;
00209     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00210       Users.insert(I->use_begin(), I->use_end());
00211 
00212     // We don't want to reprocess entries with PHI nodes in them.  For this
00213     // reason, we look at each operand of each user exactly once, performing the
00214     // stubstitution exactly once.
00215     for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
00216          ++UI) {
00217       Instruction *I = cast<Instruction>(*UI);
00218       if (I->getParent() != BB && I->getParent() != NewBlock)
00219         RemapInstruction(I, LastValueMap);
00220     }
00221   }
00222 
00223   // Now that we cloned the block as many times as we needed, stitch the new
00224   // code into the original block and delete the temporary block.
00225   BB->getInstList().splice(BB->end(), NewBlock->getInstList());
00226   delete NewBlock;
00227 
00228   // Now loop over the PHI nodes in the original block, setting them to their
00229   // incoming values.
00230   BasicBlock *Preheader = L->getLoopPreheader();
00231   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00232     PHINode *PN = OrigPHINode[i];
00233     PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
00234     BB->getInstList().erase(PN);
00235   }
00236  
00237   // Finally, add an unconditional branch to the block to continue into the exit
00238   // block.
00239   new BranchInst(LoopExit, BB);
00240 
00241   // At this point, the code is well formed.  We now do a quick sweep over the
00242   // inserted code, doing constant propagation and dead code elimination as we
00243   // go.
00244   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00245     Instruction *Inst = I++;
00246     
00247     if (isInstructionTriviallyDead(Inst))
00248       BB->getInstList().erase(Inst);
00249     else if (Constant *C = ConstantFoldInstruction(Inst)) {
00250       Inst->replaceAllUsesWith(C);
00251       BB->getInstList().erase(Inst);
00252     }
00253   }
00254 
00255   // Update the loop information for this loop.
00256   Loop *Parent = L->getParentLoop();
00257 
00258   // Move all of the basic blocks in the loop into the parent loop.
00259   LI->changeLoopFor(BB, Parent);
00260 
00261   // Remove the loop from the parent.
00262   if (Parent)
00263     delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
00264   else
00265     delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
00266 
00267 
00268   // FIXME: Should update dominator analyses
00269 
00270 
00271   // Now that everything is up-to-date that will be, we fold the loop block into
00272   // the preheader and exit block, updating our analyses as we go.
00273   LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
00274                                  BB->getInstList().begin(),
00275                                  prior(BB->getInstList().end()));
00276   LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
00277                                  Preheader->getInstList().begin(),
00278                                  prior(Preheader->getInstList().end()));
00279 
00280   // Make all other blocks in the program branch to LoopExit now instead of
00281   // Preheader.
00282   Preheader->replaceAllUsesWith(LoopExit);
00283 
00284   // Remove BB and LoopExit from our analyses.
00285   LI->removeBlock(Preheader);
00286   LI->removeBlock(BB);
00287 
00288   // If the preheader was the entry block of this function, move the exit block
00289   // to be the new entry of the loop.
00290   Function *F = LoopExit->getParent();
00291   if (Preheader == &F->front())
00292     F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);
00293 
00294   // Actually delete the blocks now.
00295   F->getBasicBlockList().erase(Preheader);
00296   F->getBasicBlockList().erase(BB);
00297 
00298   ++NumUnrolled;
00299   return true;
00300 }