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