LLVM API Documentation

LoopRotation.cpp

Go to the documentation of this file.
00001 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
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 Loop Rotation Pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "loop-rotate"
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/Function.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Analysis/LoopInfo.h"
00019 #include "llvm/Analysis/LoopPass.h"
00020 #include "llvm/Analysis/Dominators.h"
00021 #include "llvm/Analysis/ScalarEvolution.h"
00022 #include "llvm/Transforms/Utils/Local.h"
00023 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00024 #include "llvm/Support/CommandLine.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/ADT/SmallVector.h"
00028 using namespace llvm;
00029 
00030 #define MAX_HEADER_SIZE 16
00031 
00032 STATISTIC(NumRotated, "Number of loops rotated");
00033 namespace {
00034 
00035   class VISIBILITY_HIDDEN RenameData {
00036   public:
00037     RenameData(Instruction *O, Value *P, Instruction *H) 
00038       : Original(O), PreHeader(P), Header(H) { }
00039   public:
00040     Instruction *Original; // Original instruction
00041     Value *PreHeader; // Original pre-header replacement
00042     Instruction *Header; // New header replacement
00043   };
00044   
00045   class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
00046 
00047   public:
00048     static char ID; // Pass ID, replacement for typeid
00049     LoopRotate() : LoopPass(&ID) {}
00050 
00051     // Rotate Loop L as many times as possible. Return true if
00052     // loop is rotated at least once.
00053     bool runOnLoop(Loop *L, LPPassManager &LPM);
00054 
00055     // LCSSA form makes instruction renaming easier.
00056     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00057       AU.addRequiredID(LoopSimplifyID);
00058       AU.addPreservedID(LoopSimplifyID);
00059       AU.addRequiredID(LCSSAID);
00060       AU.addPreservedID(LCSSAID);
00061       AU.addPreserved<ScalarEvolution>();
00062       AU.addPreserved<LoopInfo>();
00063       AU.addPreserved<DominatorTree>();
00064       AU.addPreserved<DominanceFrontier>();
00065     }
00066 
00067     // Helper functions
00068 
00069     /// Do actual work
00070     bool rotateLoop(Loop *L, LPPassManager &LPM);
00071     
00072     /// Initialize local data
00073     void initialize();
00074 
00075     /// Make sure all Exit block PHINodes have required incoming values.
00076     /// If incoming value is constant or defined outside the loop then
00077     /// PHINode may not have an entry for original pre-header. 
00078     void  updateExitBlock();
00079 
00080     /// Return true if this instruction is used outside original header.
00081     bool usedOutsideOriginalHeader(Instruction *In);
00082 
00083     /// Find Replacement information for instruction. Return NULL if it is
00084     /// not available.
00085     const RenameData *findReplacementData(Instruction *I);
00086 
00087     /// After loop rotation, loop pre-header has multiple sucessors.
00088     /// Insert one forwarding basic block to ensure that loop pre-header
00089     /// has only one successor.
00090     void preserveCanonicalLoopForm(LPPassManager &LPM);
00091 
00092   private:
00093 
00094     Loop *L;
00095     BasicBlock *OrigHeader;
00096     BasicBlock *OrigPreHeader;
00097     BasicBlock *OrigLatch;
00098     BasicBlock *NewHeader;
00099     BasicBlock *Exit;
00100     LPPassManager *LPM_Ptr;
00101     SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
00102   };
00103 }
00104   
00105 char LoopRotate::ID = 0;
00106 static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
00107 
00108 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
00109 
00110 /// Rotate Loop L as many times as possible. Return true if
00111 /// loop is rotated at least once.
00112 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
00113 
00114   bool RotatedOneLoop = false;
00115   initialize();
00116   LPM_Ptr = &LPM;
00117 
00118   // One loop can be rotated multiple times.
00119   while (rotateLoop(Lp,LPM)) {
00120     RotatedOneLoop = true;
00121     initialize();
00122   }
00123 
00124   return RotatedOneLoop;
00125 }
00126 
00127 /// Rotate loop LP. Return true if the loop is rotated.
00128 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
00129   L = Lp;
00130 
00131   OrigHeader =  L->getHeader();
00132   OrigPreHeader = L->getLoopPreheader();
00133   OrigLatch = L->getLoopLatch();
00134 
00135   // If loop has only one block then there is not much to rotate.
00136   if (L->getBlocks().size() == 1)
00137     return false;
00138 
00139   assert(OrigHeader && OrigLatch && OrigPreHeader &&
00140          "Loop is not in canonical form");
00141 
00142   // If loop header is not one of the loop exit block then
00143   // either this loop is already rotated or it is not 
00144   // suitable for loop rotation transformations.
00145   if (!L->isLoopExit(OrigHeader))
00146     return false;
00147 
00148   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
00149   if (!BI)
00150     return false;
00151   assert(BI->isConditional() && "Branch Instruction is not conditional");
00152 
00153   // Updating PHInodes in loops with multiple exits adds complexity. 
00154   // Keep it simple, and restrict loop rotation to loops with one exit only.
00155   // In future, lift this restriction and support for multiple exits if
00156   // required.
00157   SmallVector<BasicBlock*, 8> ExitBlocks;
00158   L->getExitBlocks(ExitBlocks);
00159   if (ExitBlocks.size() > 1)
00160     return false;
00161 
00162   // Check size of original header and reject
00163   // loop if it is very big.
00164   if (OrigHeader->size() > MAX_HEADER_SIZE)
00165     return false;
00166 
00167   // Now, this loop is suitable for rotation.
00168 
00169   // Find new Loop header. NewHeader is a Header's one and only successor
00170   // that is inside loop.  Header's other successor is outside the
00171   // loop.  Otherwise loop is not suitable for rotation.
00172   Exit = BI->getSuccessor(0);
00173   NewHeader = BI->getSuccessor(1);
00174   if (L->contains(Exit))
00175     std::swap(Exit, NewHeader);
00176   assert(NewHeader && "Unable to determine new loop header");
00177   assert(L->contains(NewHeader) && !L->contains(Exit) && 
00178          "Unable to determine loop header and exit blocks");
00179   
00180   // This code assumes that new header has exactly one predecessor.  Remove any
00181   // single entry PHI nodes in it.
00182   assert(NewHeader->getSinglePredecessor() &&
00183          "New header doesn't have one pred!");
00184   FoldSingleEntryPHINodes(NewHeader);
00185 
00186   // Copy PHI nodes and other instructions from original header
00187   // into original pre-header. Unlike original header, original pre-header is
00188   // not a member of loop. 
00189   //
00190   // New loop header is one and only successor of original header that 
00191   // is inside the loop. All other original header successors are outside 
00192   // the loop. Copy PHI Nodes from original header into new loop header. 
00193   // Add second incoming value, from original loop pre-header into these phi 
00194   // nodes. If a value defined in original header is used outside original 
00195   // header then new loop header will need new phi nodes with two incoming 
00196   // values, one definition from original header and second definition is 
00197   // from original loop pre-header.
00198 
00199   // Remove terminator from Original pre-header. Original pre-header will
00200   // receive a clone of original header terminator as a new terminator.
00201   OrigPreHeader->getInstList().pop_back();
00202   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
00203   PHINode *PN = 0;
00204   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
00205     // PHI nodes are not copied into original pre-header. Instead their values
00206     // are directly propagated.
00207     Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
00208 
00209     // Create new PHI node with two incoming values for NewHeader.
00210     // One incoming value is from OrigLatch (through OrigHeader) and 
00211     // second incoming value is from original pre-header.
00212     PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
00213                                   NewHeader->begin());
00214     NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
00215     NH->addIncoming(NPV, OrigPreHeader);
00216     
00217     // "In" can be replaced by NH at various places.
00218     LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
00219   }
00220 
00221   // Now, handle non-phi instructions.
00222   for (; I != E; ++I) {
00223     Instruction *In = I;
00224     assert(!isa<PHINode>(In) && "PHINode is not expected here");
00225     
00226     // This is not a PHI instruction. Insert its clone into original pre-header.
00227     // If this instruction is using a value from same basic block then
00228     // update it to use value from cloned instruction.
00229     Instruction *C = In->clone();
00230     C->setName(In->getName());
00231     OrigPreHeader->getInstList().push_back(C);
00232 
00233     for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
00234       Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
00235       if (!OpInsn) continue;  // Ignore non-instruction values.
00236       if (const RenameData *D = findReplacementData(OpInsn))
00237         C->setOperand(opi, D->PreHeader);
00238     }
00239 
00240     // If this instruction is used outside this basic block then
00241     // create new PHINode for this instruction.
00242     Instruction *NewHeaderReplacement = NULL;
00243     if (usedOutsideOriginalHeader(In)) {
00244       PHINode *PN = PHINode::Create(In->getType(), In->getName(),
00245                                     NewHeader->begin());
00246       PN->addIncoming(In, OrigHeader);
00247       PN->addIncoming(C, OrigPreHeader);
00248       NewHeaderReplacement = PN;
00249     }
00250     LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
00251   }
00252 
00253   // Rename uses of original header instructions to reflect their new
00254   // definitions (either from original pre-header node or from newly created
00255   // new header PHINodes.
00256   //
00257   // Original header instructions are used in
00258   // 1) Original header:
00259   //
00260   //    If instruction is used in non-phi instructions then it is using
00261   //    defintion from original heder iteself. Do not replace this use
00262   //    with definition from new header or original pre-header.
00263   //
00264   //    If instruction is used in phi node then it is an incoming 
00265   //    value. Rename its use to reflect new definition from new-preheader
00266   //    or new header.
00267   //
00268   // 2) Inside loop but not in original header
00269   //
00270   //    Replace this use to reflect definition from new header.
00271   for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
00272     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
00273 
00274     if (!ILoopHeaderInfo.Header)
00275       continue;
00276 
00277     Instruction *OldPhi = ILoopHeaderInfo.Original;
00278     Instruction *NewPhi = ILoopHeaderInfo.Header;
00279 
00280     // Before replacing uses, collect them first, so that iterator is
00281     // not invalidated.
00282     SmallVector<Instruction *, 16> AllUses;
00283     for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
00284          UI != UE; ++UI)
00285       AllUses.push_back(cast<Instruction>(UI));
00286 
00287     for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(), 
00288            UE = AllUses.end(); UI != UE; ++UI) {
00289       Instruction *U = *UI;
00290       BasicBlock *Parent = U->getParent();
00291 
00292       // Used inside original header
00293       if (Parent == OrigHeader) {
00294         // Do not rename uses inside original header non-phi instructions.
00295         PHINode *PU = dyn_cast<PHINode>(U);
00296         if (!PU)
00297           continue;
00298 
00299         // Do not rename uses inside original header phi nodes, if the
00300         // incoming value is for new header.
00301         if (PU->getBasicBlockIndex(NewHeader) != -1
00302             && PU->getIncomingValueForBlock(NewHeader) == U)
00303           continue;
00304         
00305        U->replaceUsesOfWith(OldPhi, NewPhi);
00306        continue;
00307       }
00308 
00309       // Used inside loop, but not in original header.
00310       if (L->contains(U->getParent())) {
00311         if (U != NewPhi)
00312           U->replaceUsesOfWith(OldPhi, NewPhi);
00313         continue;
00314       }
00315       
00316       // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
00317       if (U->getParent() == Exit) {
00318         assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
00319         
00320         PHINode *UPhi = cast<PHINode>(U);
00321         // UPhi already has one incoming argument from original header. 
00322         // Add second incoming argument from new Pre header.
00323         UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
00324       } else {
00325         // Used outside Exit block. Create a new PHI node from exit block
00326         // to receive value from ne new header ane pre header.
00327         PHINode *PN = PHINode::Create(U->getType(), U->getName(),
00328                                       Exit->begin());
00329         PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
00330         PN->addIncoming(OldPhi, OrigHeader);
00331         U->replaceUsesOfWith(OldPhi, PN);
00332       }
00333     }
00334   }
00335   
00336   /// Make sure all Exit block PHINodes have required incoming values.
00337   updateExitBlock();
00338 
00339   // Update CFG
00340 
00341   // Removing incoming branch from loop preheader to original header.
00342   // Now original header is inside the loop.
00343   for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
00344        I != E; ++I)
00345     if (PHINode *PN = dyn_cast<PHINode>(I))
00346       PN->removeIncomingValue(OrigPreHeader);
00347 
00348   // Make NewHeader as the new header for the loop.
00349   L->moveToHeader(NewHeader);
00350 
00351   preserveCanonicalLoopForm(LPM);
00352 
00353   NumRotated++;
00354   return true;
00355 }
00356 
00357 /// Make sure all Exit block PHINodes have required incoming values.
00358 /// If incoming value is constant or defined outside the loop then
00359 /// PHINode may not have an entry for original pre-header. 
00360 void LoopRotate::updateExitBlock() {
00361 
00362   for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
00363        I != E; ++I) {
00364 
00365     PHINode *PN = dyn_cast<PHINode>(I);
00366     if (!PN)
00367       break;
00368 
00369     // There is already one incoming value from original pre-header block.
00370     if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
00371       continue;
00372 
00373     const RenameData *ILoopHeaderInfo;
00374     Value *V = PN->getIncomingValueForBlock(OrigHeader);
00375     if (isa<Instruction>(V) && 
00376         (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
00377       assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
00378       PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
00379     } else {
00380       PN->addIncoming(V, OrigPreHeader);
00381     }
00382   }
00383 }
00384 
00385 /// Initialize local data
00386 void LoopRotate::initialize() {
00387   L = NULL;
00388   OrigHeader = NULL;
00389   OrigPreHeader = NULL;
00390   NewHeader = NULL;
00391   Exit = NULL;
00392 
00393   LoopHeaderInfo.clear();
00394 }
00395 
00396 /// Return true if this instruction is used by any instructions in the loop that
00397 /// aren't in original header.
00398 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
00399   for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
00400        UI != UE; ++UI) {
00401     BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
00402     if (UserBB != OrigHeader && L->contains(UserBB))
00403       return true;
00404   }
00405 
00406   return false;
00407 }
00408 
00409 /// Find Replacement information for instruction. Return NULL if it is
00410 /// not available.
00411 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
00412 
00413   // Since LoopHeaderInfo is small, linear walk is OK.
00414   for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
00415     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
00416     if (ILoopHeaderInfo.Original == In)
00417       return &ILoopHeaderInfo;
00418   }
00419   return NULL;
00420 }
00421 
00422 /// After loop rotation, loop pre-header has multiple sucessors.
00423 /// Insert one forwarding basic block to ensure that loop pre-header
00424 /// has only one successor.
00425 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
00426 
00427   // Right now original pre-header has two successors, new header and
00428   // exit block. Insert new block between original pre-header and
00429   // new header such that loop's new pre-header has only one successor.
00430   BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph",
00431                                                 OrigHeader->getParent(), 
00432                                                 NewHeader);
00433   LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
00434   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
00435     PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
00436   BranchInst::Create(NewHeader, NewPreHeader);
00437   
00438   BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
00439   if (OrigPH_BI->getSuccessor(0) == NewHeader)
00440     OrigPH_BI->setSuccessor(0, NewPreHeader);
00441   else {
00442     assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
00443            "Unexpected original pre-header terminator");
00444     OrigPH_BI->setSuccessor(1, NewPreHeader);
00445   }
00446   
00447   for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
00448        I != E; ++I) {
00449     PHINode *PN = dyn_cast<PHINode>(I);
00450     if (!PN)
00451       break;
00452 
00453     int index = PN->getBasicBlockIndex(OrigPreHeader);
00454     assert(index != -1 && "Expected incoming value from Original PreHeader");
00455     PN->setIncomingBlock(index, NewPreHeader);
00456     assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 && 
00457            "Expected only one incoming value from Original PreHeader");
00458   }
00459 
00460   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
00461     DT->addNewBlock(NewPreHeader, OrigPreHeader);
00462     DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
00463     DT->changeImmediateDominator(Exit, OrigPreHeader);
00464     for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
00465          BI != BE; ++BI) {
00466       BasicBlock *B = *BI;
00467       if (L->getHeader() != B) {
00468         DomTreeNode *Node = DT->getNode(B);
00469         if (Node && Node->getBlock() == OrigHeader)
00470           DT->changeImmediateDominator(*BI, L->getHeader());
00471       }
00472     }
00473     DT->changeImmediateDominator(OrigHeader, OrigLatch);
00474   }
00475 
00476   if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
00477     // New Preheader's dominance frontier is Exit block.
00478     DominanceFrontier::DomSetType NewPHSet;
00479     NewPHSet.insert(Exit);
00480     DF->addBasicBlock(NewPreHeader, NewPHSet);
00481 
00482     // New Header's dominance frontier now includes itself and Exit block
00483     DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
00484     if (HeadI != DF->end()) {
00485       DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
00486       HeaderSet.clear();
00487       HeaderSet.insert(L->getHeader());
00488       HeaderSet.insert(Exit);
00489     } else {
00490       DominanceFrontier::DomSetType HeaderSet;
00491       HeaderSet.insert(L->getHeader());
00492       HeaderSet.insert(Exit);
00493       DF->addBasicBlock(L->getHeader(), HeaderSet);
00494     }
00495 
00496     // Original header (new Loop Latch)'s dominance frontier is Exit.
00497     DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
00498     if (LatchI != DF->end()) {
00499       DominanceFrontier::DomSetType &LatchSet = LatchI->second;
00500       LatchSet = LatchI->second;
00501       LatchSet.clear();
00502       LatchSet.insert(Exit);
00503     } else {
00504       DominanceFrontier::DomSetType LatchSet;
00505       LatchSet.insert(Exit);
00506       DF->addBasicBlock(L->getHeader(), LatchSet);
00507     }
00508 
00509     // If a loop block dominates new loop latch then its frontier is
00510     // new header and Exit.
00511     BasicBlock *NewLatch = L->getLoopLatch();
00512     DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>();
00513     for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
00514          BI != BE; ++BI) {
00515       BasicBlock *B = *BI;
00516       if (DT->dominates(B, NewLatch)) {
00517         DominanceFrontier::iterator BDFI = DF->find(B);
00518         if (BDFI != DF->end()) {
00519           DominanceFrontier::DomSetType &BSet = BDFI->second;
00520           BSet = BDFI->second;
00521           BSet.clear();
00522           BSet.insert(L->getHeader());
00523           BSet.insert(Exit);
00524         } else {
00525           DominanceFrontier::DomSetType BSet;
00526           BSet.insert(L->getHeader());
00527           BSet.insert(Exit);
00528           DF->addBasicBlock(B, BSet);
00529         }
00530       }
00531     }
00532   }
00533 
00534   // Preserve canonical loop form, which means Exit block should
00535   // have only one predecessor.
00536   BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
00537 
00538   // Preserve LCSSA.
00539   BasicBlock::iterator I = Exit->begin(), E = Exit->end();
00540   PHINode *PN = NULL;
00541   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
00542     unsigned N = PN->getNumIncomingValues();
00543     for (unsigned index = 0; index < N; ++index)
00544       if (PN->getIncomingBlock(index) == NExit) {
00545         PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName(),
00546                                          NExit->begin());
00547         NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
00548         PN->setIncomingValue(index, NewPN);
00549         PN->setIncomingBlock(index, NExit);
00550         break;
00551       }
00552   }
00553 
00554   assert(NewHeader && L->getHeader() == NewHeader &&
00555          "Invalid loop header after loop rotation");
00556   assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
00557          "Invalid loop preheader after loop rotation");
00558   assert(L->getLoopLatch() &&
00559          "Invalid loop latch after loop rotation");
00560 }