LLVM API Documentation

SSAUpdaterImpl.h
Go to the documentation of this file.
00001 //===-- SSAUpdaterImpl.h - SSA Updater Implementation -----------*- C++ -*-===//
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 provides a template that implements the core algorithm for the
00011 // SSAUpdater and MachineSSAUpdater.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
00016 #define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
00017 
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/Support/Allocator.h"
00021 #include "llvm/Support/Debug.h"
00022 #include "llvm/Support/ValueHandle.h"
00023 
00024 namespace llvm {
00025 
00026 class CastInst;
00027 class PHINode;
00028 template<typename T> class SSAUpdaterTraits;
00029 
00030 template<typename UpdaterT>
00031 class SSAUpdaterImpl {
00032 private:
00033   UpdaterT *Updater;
00034 
00035   typedef SSAUpdaterTraits<UpdaterT> Traits;
00036   typedef typename Traits::BlkT BlkT;
00037   typedef typename Traits::ValT ValT;
00038   typedef typename Traits::PhiT PhiT;
00039 
00040   /// BBInfo - Per-basic block information used internally by SSAUpdaterImpl.
00041   /// The predecessors of each block are cached here since pred_iterator is
00042   /// slow and we need to iterate over the blocks at least a few times.
00043   class BBInfo {
00044   public:
00045     BlkT *BB;          // Back-pointer to the corresponding block.
00046     ValT AvailableVal; // Value to use in this block.
00047     BBInfo *DefBB;     // Block that defines the available value.
00048     int BlkNum;        // Postorder number.
00049     BBInfo *IDom;      // Immediate dominator.
00050     unsigned NumPreds; // Number of predecessor blocks.
00051     BBInfo **Preds;    // Array[NumPreds] of predecessor blocks.
00052     PhiT *PHITag;      // Marker for existing PHIs that match.
00053 
00054     BBInfo(BlkT *ThisBB, ValT V)
00055       : BB(ThisBB), AvailableVal(V), DefBB(V ? this : 0), BlkNum(0), IDom(0),
00056       NumPreds(0), Preds(0), PHITag(0) { }
00057   };
00058 
00059   typedef DenseMap<BlkT*, ValT> AvailableValsTy;
00060   AvailableValsTy *AvailableVals;
00061 
00062   SmallVectorImpl<PhiT*> *InsertedPHIs;
00063 
00064   typedef SmallVectorImpl<BBInfo*> BlockListTy;
00065   typedef DenseMap<BlkT*, BBInfo*> BBMapTy;
00066   BBMapTy BBMap;
00067   BumpPtrAllocator Allocator;
00068 
00069 public:
00070   explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A,
00071                           SmallVectorImpl<PhiT*> *Ins) :
00072     Updater(U), AvailableVals(A), InsertedPHIs(Ins) { }
00073 
00074   /// GetValue - Check to see if AvailableVals has an entry for the specified
00075   /// BB and if so, return it.  If not, construct SSA form by first
00076   /// calculating the required placement of PHIs and then inserting new PHIs
00077   /// where needed.
00078   ValT GetValue(BlkT *BB) {
00079     SmallVector<BBInfo*, 100> BlockList;
00080     BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList);
00081 
00082     // Special case: bail out if BB is unreachable.
00083     if (BlockList.size() == 0) {
00084       ValT V = Traits::GetUndefVal(BB, Updater);
00085       (*AvailableVals)[BB] = V;
00086       return V;
00087     }
00088 
00089     FindDominators(&BlockList, PseudoEntry);
00090     FindPHIPlacement(&BlockList);
00091     FindAvailableVals(&BlockList);
00092 
00093     return BBMap[BB]->DefBB->AvailableVal;
00094   }
00095 
00096   /// BuildBlockList - Starting from the specified basic block, traverse back
00097   /// through its predecessors until reaching blocks with known values.
00098   /// Create BBInfo structures for the blocks and append them to the block
00099   /// list.
00100   BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) {
00101     SmallVector<BBInfo*, 10> RootList;
00102     SmallVector<BBInfo*, 64> WorkList;
00103 
00104     BBInfo *Info = new (Allocator) BBInfo(BB, 0);
00105     BBMap[BB] = Info;
00106     WorkList.push_back(Info);
00107 
00108     // Search backward from BB, creating BBInfos along the way and stopping
00109     // when reaching blocks that define the value.  Record those defining
00110     // blocks on the RootList.
00111     SmallVector<BlkT*, 10> Preds;
00112     while (!WorkList.empty()) {
00113       Info = WorkList.pop_back_val();
00114       Preds.clear();
00115       Traits::FindPredecessorBlocks(Info->BB, &Preds);
00116       Info->NumPreds = Preds.size();
00117       if (Info->NumPreds == 0)
00118         Info->Preds = 0;
00119       else
00120         Info->Preds = static_cast<BBInfo**>
00121           (Allocator.Allocate(Info->NumPreds * sizeof(BBInfo*),
00122                               AlignOf<BBInfo*>::Alignment));
00123 
00124       for (unsigned p = 0; p != Info->NumPreds; ++p) {
00125         BlkT *Pred = Preds[p];
00126         // Check if BBMap already has a BBInfo for the predecessor block.
00127         typename BBMapTy::value_type &BBMapBucket =
00128           BBMap.FindAndConstruct(Pred);
00129         if (BBMapBucket.second) {
00130           Info->Preds[p] = BBMapBucket.second;
00131           continue;
00132         }
00133 
00134         // Create a new BBInfo for the predecessor.
00135         ValT PredVal = AvailableVals->lookup(Pred);
00136         BBInfo *PredInfo = new (Allocator) BBInfo(Pred, PredVal);
00137         BBMapBucket.second = PredInfo;
00138         Info->Preds[p] = PredInfo;
00139 
00140         if (PredInfo->AvailableVal) {
00141           RootList.push_back(PredInfo);
00142           continue;
00143         }
00144         WorkList.push_back(PredInfo);
00145       }
00146     }
00147 
00148     // Now that we know what blocks are backwards-reachable from the starting
00149     // block, do a forward depth-first traversal to assign postorder numbers
00150     // to those blocks.
00151     BBInfo *PseudoEntry = new (Allocator) BBInfo(0, 0);
00152     unsigned BlkNum = 1;
00153 
00154     // Initialize the worklist with the roots from the backward traversal.
00155     while (!RootList.empty()) {
00156       Info = RootList.pop_back_val();
00157       Info->IDom = PseudoEntry;
00158       Info->BlkNum = -1;
00159       WorkList.push_back(Info);
00160     }
00161 
00162     while (!WorkList.empty()) {
00163       Info = WorkList.back();
00164 
00165       if (Info->BlkNum == -2) {
00166         // All the successors have been handled; assign the postorder number.
00167         Info->BlkNum = BlkNum++;
00168         // If not a root, put it on the BlockList.
00169         if (!Info->AvailableVal)
00170           BlockList->push_back(Info);
00171         WorkList.pop_back();
00172         continue;
00173       }
00174 
00175       // Leave this entry on the worklist, but set its BlkNum to mark that its
00176       // successors have been put on the worklist.  When it returns to the top
00177       // the list, after handling its successors, it will be assigned a
00178       // number.
00179       Info->BlkNum = -2;
00180 
00181       // Add unvisited successors to the work list.
00182       for (typename Traits::BlkSucc_iterator SI =
00183              Traits::BlkSucc_begin(Info->BB),
00184              E = Traits::BlkSucc_end(Info->BB); SI != E; ++SI) {
00185         BBInfo *SuccInfo = BBMap[*SI];
00186         if (!SuccInfo || SuccInfo->BlkNum)
00187           continue;
00188         SuccInfo->BlkNum = -1;
00189         WorkList.push_back(SuccInfo);
00190       }
00191     }
00192     PseudoEntry->BlkNum = BlkNum;
00193     return PseudoEntry;
00194   }
00195 
00196   /// IntersectDominators - This is the dataflow lattice "meet" operation for
00197   /// finding dominators.  Given two basic blocks, it walks up the dominator
00198   /// tree until it finds a common dominator of both.  It uses the postorder
00199   /// number of the blocks to determine how to do that.
00200   BBInfo *IntersectDominators(BBInfo *Blk1, BBInfo *Blk2) {
00201     while (Blk1 != Blk2) {
00202       while (Blk1->BlkNum < Blk2->BlkNum) {
00203         Blk1 = Blk1->IDom;
00204         if (!Blk1)
00205           return Blk2;
00206       }
00207       while (Blk2->BlkNum < Blk1->BlkNum) {
00208         Blk2 = Blk2->IDom;
00209         if (!Blk2)
00210           return Blk1;
00211       }
00212     }
00213     return Blk1;
00214   }
00215 
00216   /// FindDominators - Calculate the dominator tree for the subset of the CFG
00217   /// corresponding to the basic blocks on the BlockList.  This uses the
00218   /// algorithm from: "A Simple, Fast Dominance Algorithm" by Cooper, Harvey
00219   /// and Kennedy, published in Software--Practice and Experience, 2001,
00220   /// 4:1-10.  Because the CFG subset does not include any edges leading into
00221   /// blocks that define the value, the results are not the usual dominator
00222   /// tree.  The CFG subset has a single pseudo-entry node with edges to a set
00223   /// of root nodes for blocks that define the value.  The dominators for this
00224   /// subset CFG are not the standard dominators but they are adequate for
00225   /// placing PHIs within the subset CFG.
00226   void FindDominators(BlockListTy *BlockList, BBInfo *PseudoEntry) {
00227     bool Changed;
00228     do {
00229       Changed = false;
00230       // Iterate over the list in reverse order, i.e., forward on CFG edges.
00231       for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
00232              E = BlockList->rend(); I != E; ++I) {
00233         BBInfo *Info = *I;
00234         BBInfo *NewIDom = 0;
00235 
00236         // Iterate through the block's predecessors.
00237         for (unsigned p = 0; p != Info->NumPreds; ++p) {
00238           BBInfo *Pred = Info->Preds[p];
00239 
00240           // Treat an unreachable predecessor as a definition with 'undef'.
00241           if (Pred->BlkNum == 0) {
00242             Pred->AvailableVal = Traits::GetUndefVal(Pred->BB, Updater);
00243             (*AvailableVals)[Pred->BB] = Pred->AvailableVal;
00244             Pred->DefBB = Pred;
00245             Pred->BlkNum = PseudoEntry->BlkNum;
00246             PseudoEntry->BlkNum++;
00247           }
00248 
00249           if (!NewIDom)
00250             NewIDom = Pred;
00251           else
00252             NewIDom = IntersectDominators(NewIDom, Pred);
00253         }
00254 
00255         // Check if the IDom value has changed.
00256         if (NewIDom && NewIDom != Info->IDom) {
00257           Info->IDom = NewIDom;
00258           Changed = true;
00259         }
00260       }
00261     } while (Changed);
00262   }
00263 
00264   /// IsDefInDomFrontier - Search up the dominator tree from Pred to IDom for
00265   /// any blocks containing definitions of the value.  If one is found, then
00266   /// the successor of Pred is in the dominance frontier for the definition,
00267   /// and this function returns true.
00268   bool IsDefInDomFrontier(const BBInfo *Pred, const BBInfo *IDom) {
00269     for (; Pred != IDom; Pred = Pred->IDom) {
00270       if (Pred->DefBB == Pred)
00271         return true;
00272     }
00273     return false;
00274   }
00275 
00276   /// FindPHIPlacement - PHIs are needed in the iterated dominance frontiers
00277   /// of the known definitions.  Iteratively add PHIs in the dom frontiers
00278   /// until nothing changes.  Along the way, keep track of the nearest
00279   /// dominating definitions for non-PHI blocks.
00280   void FindPHIPlacement(BlockListTy *BlockList) {
00281     bool Changed;
00282     do {
00283       Changed = false;
00284       // Iterate over the list in reverse order, i.e., forward on CFG edges.
00285       for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
00286              E = BlockList->rend(); I != E; ++I) {
00287         BBInfo *Info = *I;
00288 
00289         // If this block already needs a PHI, there is nothing to do here.
00290         if (Info->DefBB == Info)
00291           continue;
00292 
00293         // Default to use the same def as the immediate dominator.
00294         BBInfo *NewDefBB = Info->IDom->DefBB;
00295         for (unsigned p = 0; p != Info->NumPreds; ++p) {
00296           if (IsDefInDomFrontier(Info->Preds[p], Info->IDom)) {
00297             // Need a PHI here.
00298             NewDefBB = Info;
00299             break;
00300           }
00301         }
00302 
00303         // Check if anything changed.
00304         if (NewDefBB != Info->DefBB) {
00305           Info->DefBB = NewDefBB;
00306           Changed = true;
00307         }
00308       }
00309     } while (Changed);
00310   }
00311 
00312   /// FindAvailableVal - If this block requires a PHI, first check if an
00313   /// existing PHI matches the PHI placement and reaching definitions computed
00314   /// earlier, and if not, create a new PHI.  Visit all the block's
00315   /// predecessors to calculate the available value for each one and fill in
00316   /// the incoming values for a new PHI.
00317   void FindAvailableVals(BlockListTy *BlockList) {
00318     // Go through the worklist in forward order (i.e., backward through the CFG)
00319     // and check if existing PHIs can be used.  If not, create empty PHIs where
00320     // they are needed.
00321     for (typename BlockListTy::iterator I = BlockList->begin(),
00322            E = BlockList->end(); I != E; ++I) {
00323       BBInfo *Info = *I;
00324       // Check if there needs to be a PHI in BB.
00325       if (Info->DefBB != Info)
00326         continue;
00327 
00328       // Look for an existing PHI.
00329       FindExistingPHI(Info->BB, BlockList);
00330       if (Info->AvailableVal)
00331         continue;
00332 
00333       ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
00334       Info->AvailableVal = PHI;
00335       (*AvailableVals)[Info->BB] = PHI;
00336     }
00337 
00338     // Now go back through the worklist in reverse order to fill in the
00339     // arguments for any new PHIs added in the forward traversal.
00340     for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
00341            E = BlockList->rend(); I != E; ++I) {
00342       BBInfo *Info = *I;
00343 
00344       if (Info->DefBB != Info) {
00345         // Record the available value at join nodes to speed up subsequent
00346         // uses of this SSAUpdater for the same value.
00347         if (Info->NumPreds > 1)
00348           (*AvailableVals)[Info->BB] = Info->DefBB->AvailableVal;
00349         continue;
00350       }
00351 
00352       // Check if this block contains a newly added PHI.
00353       PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
00354       if (!PHI)
00355         continue;
00356 
00357       // Iterate through the block's predecessors.
00358       for (unsigned p = 0; p != Info->NumPreds; ++p) {
00359         BBInfo *PredInfo = Info->Preds[p];
00360         BlkT *Pred = PredInfo->BB;
00361         // Skip to the nearest preceding definition.
00362         if (PredInfo->DefBB != PredInfo)
00363           PredInfo = PredInfo->DefBB;
00364         Traits::AddPHIOperand(PHI, PredInfo->AvailableVal, Pred);
00365       }
00366 
00367       DEBUG(dbgs() << "  Inserted PHI: " << *PHI << "\n");
00368 
00369       // If the client wants to know about all new instructions, tell it.
00370       if (InsertedPHIs) InsertedPHIs->push_back(PHI);
00371     }
00372   }
00373 
00374   /// FindExistingPHI - Look through the PHI nodes in a block to see if any of
00375   /// them match what is needed.
00376   void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
00377     for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
00378          BBI != BBE; ++BBI) {
00379       PhiT *SomePHI = Traits::InstrIsPHI(BBI);
00380       if (!SomePHI)
00381         break;
00382       if (CheckIfPHIMatches(SomePHI)) {
00383         RecordMatchingPHIs(BlockList);
00384         break;
00385       }
00386       // Match failed: clear all the PHITag values.
00387       for (typename BlockListTy::iterator I = BlockList->begin(),
00388              E = BlockList->end(); I != E; ++I)
00389         (*I)->PHITag = 0;
00390     }
00391   }
00392 
00393   /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
00394   /// in the BBMap.
00395   bool CheckIfPHIMatches(PhiT *PHI) {
00396     SmallVector<PhiT*, 20> WorkList;
00397     WorkList.push_back(PHI);
00398 
00399     // Mark that the block containing this PHI has been visited.
00400     BBMap[PHI->getParent()]->PHITag = PHI;
00401 
00402     while (!WorkList.empty()) {
00403       PHI = WorkList.pop_back_val();
00404 
00405       // Iterate through the PHI's incoming values.
00406       for (typename Traits::PHI_iterator I = Traits::PHI_begin(PHI),
00407              E = Traits::PHI_end(PHI); I != E; ++I) {
00408         ValT IncomingVal = I.getIncomingValue();
00409         BBInfo *PredInfo = BBMap[I.getIncomingBlock()];
00410         // Skip to the nearest preceding definition.
00411         if (PredInfo->DefBB != PredInfo)
00412           PredInfo = PredInfo->DefBB;
00413 
00414         // Check if it matches the expected value.
00415         if (PredInfo->AvailableVal) {
00416           if (IncomingVal == PredInfo->AvailableVal)
00417             continue;
00418           return false;
00419         }
00420 
00421         // Check if the value is a PHI in the correct block.
00422         PhiT *IncomingPHIVal = Traits::ValueIsPHI(IncomingVal, Updater);
00423         if (!IncomingPHIVal || IncomingPHIVal->getParent() != PredInfo->BB)
00424           return false;
00425 
00426         // If this block has already been visited, check if this PHI matches.
00427         if (PredInfo->PHITag) {
00428           if (IncomingPHIVal == PredInfo->PHITag)
00429             continue;
00430           return false;
00431         }
00432         PredInfo->PHITag = IncomingPHIVal;
00433 
00434         WorkList.push_back(IncomingPHIVal);
00435       }
00436     }
00437     return true;
00438   }
00439 
00440   /// RecordMatchingPHIs - For each PHI node that matches, record it in both
00441   /// the BBMap and the AvailableVals mapping.
00442   void RecordMatchingPHIs(BlockListTy *BlockList) {
00443     for (typename BlockListTy::iterator I = BlockList->begin(),
00444            E = BlockList->end(); I != E; ++I)
00445       if (PhiT *PHI = (*I)->PHITag) {
00446         BlkT *BB = PHI->getParent();
00447         ValT PHIVal = Traits::GetPHIValue(PHI);
00448         (*AvailableVals)[BB] = PHIVal;
00449         BBMap[BB]->AvailableVal = PHIVal;
00450       }
00451   }
00452 };
00453 
00454 } // End llvm namespace
00455 
00456 #endif