LLVM API Documentation

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 #include <iostream>
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   uint64_t TripCountFull = TripCountC->getRawValue();
00140   if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 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 = " << TripCountFull << " - ");
00147   uint64_t Size = (uint64_t)LoopSize*TripCountFull;
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   unsigned TripCount = (unsigned)TripCountFull;
00155 
00156   BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
00157 
00158   // Create a new basic block to temporarily hold all of the cloned code.
00159   BasicBlock *NewBlock = new BasicBlock();
00160 
00161   // For the first iteration of the loop, we should use the precloned values for
00162   // PHI nodes.  Insert associations now.
00163   std::map<const Value*, Value*> LastValueMap;
00164   std::vector<PHINode*> OrigPHINode;
00165   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
00166     PHINode *PN = cast<PHINode>(I);
00167     OrigPHINode.push_back(PN);
00168     if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
00169       if (I->getParent() == BB)
00170         LastValueMap[I] = I;
00171   }
00172 
00173   // Remove the exit branch from the loop
00174   BB->getInstList().erase(BI);
00175 
00176   assert(TripCount != 0 && "Trip count of 0 is impossible!");
00177   for (unsigned It = 1; It != TripCount; ++It) {
00178     char SuffixBuffer[100];
00179     sprintf(SuffixBuffer, ".%d", It);
00180     std::map<const Value*, Value*> ValueMap;
00181     BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
00182 
00183     // Loop over all of the PHI nodes in the block, changing them to use the
00184     // incoming values from the previous block.
00185     for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00186       PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
00187       Value *InVal = NewPHI->getIncomingValueForBlock(BB);
00188       if (Instruction *InValI = dyn_cast<Instruction>(InVal))
00189         if (InValI->getParent() == BB)
00190           InVal = LastValueMap[InValI];
00191       ValueMap[OrigPHINode[i]] = InVal;
00192       New->getInstList().erase(NewPHI);
00193     }
00194 
00195     for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
00196       RemapInstruction(I, ValueMap);
00197 
00198     // Now that all of the instructions are remapped, splice them into the end
00199     // of the NewBlock.
00200     NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
00201     delete New;
00202 
00203     // LastValue map now contains values from this iteration.
00204     std::swap(LastValueMap, ValueMap);
00205   }
00206 
00207   // If there was more than one iteration, replace any uses of values computed
00208   // in the loop with values computed during the last iteration of the loop.
00209   if (TripCount != 1) {
00210     std::set<User*> Users;
00211     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00212       Users.insert(I->use_begin(), I->use_end());
00213 
00214     // We don't want to reprocess entries with PHI nodes in them.  For this
00215     // reason, we look at each operand of each user exactly once, performing the
00216     // substitution exactly once.
00217     for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
00218          ++UI) {
00219       Instruction *I = cast<Instruction>(*UI);
00220       if (I->getParent() != BB && I->getParent() != NewBlock)
00221         RemapInstruction(I, LastValueMap);
00222     }
00223   }
00224 
00225   // Now that we cloned the block as many times as we needed, stitch the new
00226   // code into the original block and delete the temporary block.
00227   BB->getInstList().splice(BB->end(), NewBlock->getInstList());
00228   delete NewBlock;
00229 
00230   // Now loop over the PHI nodes in the original block, setting them to their
00231   // incoming values.
00232   BasicBlock *Preheader = L->getLoopPreheader();
00233   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00234     PHINode *PN = OrigPHINode[i];
00235     PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
00236     BB->getInstList().erase(PN);
00237   }
00238 
00239   // Finally, add an unconditional branch to the block to continue into the exit
00240   // block.
00241   new BranchInst(LoopExit, BB);
00242 
00243   // At this point, the code is well formed.  We now do a quick sweep over the
00244   // inserted code, doing constant propagation and dead code elimination as we
00245   // go.
00246   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00247     Instruction *Inst = I++;
00248 
00249     if (isInstructionTriviallyDead(Inst))
00250       BB->getInstList().erase(Inst);
00251     else if (Constant *C = ConstantFoldInstruction(Inst)) {
00252       Inst->replaceAllUsesWith(C);
00253       BB->getInstList().erase(Inst);
00254     }
00255   }
00256 
00257   // Update the loop information for this loop.
00258   Loop *Parent = L->getParentLoop();
00259 
00260   // Move all of the basic blocks in the loop into the parent loop.
00261   LI->changeLoopFor(BB, Parent);
00262 
00263   // Remove the loop from the parent.
00264   if (Parent)
00265     delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
00266   else
00267     delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
00268 
00269   // Remove single-entry Phis from the exit block.
00270   for (BasicBlock::iterator ExitInstr = LoopExit->begin();
00271        PHINode* PN = dyn_cast<PHINode>(ExitInstr); ++ExitInstr) {
00272     assert(PN->getNumIncomingValues() == 1
00273            && "Block should only have one pred, so Phi's must be single entry");
00274     PN->replaceAllUsesWith(PN->getOperand(0));
00275     PN->eraseFromParent();
00276   }
00277   
00278   // FIXME: Should update dominator analyses
00279   
00280   // Now that everything is up-to-date that will be, we fold the loop block into
00281   // the preheader and exit block, updating our analyses as we go.
00282   LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
00283                                  BB->getInstList().begin(),
00284                                  prior(BB->getInstList().end()));
00285   LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
00286                                  Preheader->getInstList().begin(),
00287                                  prior(Preheader->getInstList().end()));
00288 
00289   // Make all other blocks in the program branch to LoopExit now instead of
00290   // Preheader.
00291   Preheader->replaceAllUsesWith(LoopExit);
00292 
00293   Function *F = LoopExit->getParent();
00294   if (Parent) {
00295     // Otherwise, if this is a sub-loop, and the preheader was the loop header
00296     // of the parent loop, move the exit block to be the new parent loop header.
00297     if (Parent->getHeader() == Preheader) {
00298       assert(Parent->contains(LoopExit) &&
00299              "Exit block isn't contained in parent?");
00300       Parent->moveToHeader(LoopExit);
00301     }
00302   } else {
00303     // If the preheader was the entry block of this function, move the exit
00304     // block to be the new entry of the function.
00305     if (Preheader == &F->front())
00306       F->getBasicBlockList().splice(F->begin(),
00307                                     F->getBasicBlockList(), LoopExit);
00308   }
00309 
00310   // Remove BB and LoopExit from our analyses.
00311   LI->removeBlock(Preheader);
00312   LI->removeBlock(BB);
00313 
00314   // Actually delete the blocks now.
00315   F->getBasicBlockList().erase(Preheader);
00316   F->getBasicBlockList().erase(BB);
00317 
00318   ++NumUnrolled;
00319   return true;
00320 }