Home | History | Annotate | Download | only in Utils
      1 //===-- SSAUpdaterImpl.h - SSA Updater Implementation -----------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file provides a template that implements the core algorithm for the
     11 // SSAUpdater and MachineSSAUpdater.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
     16 #define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
     17 
     18 #include "llvm/ADT/DenseMap.h"
     19 #include "llvm/ADT/SmallVector.h"
     20 #include "llvm/Support/Allocator.h"
     21 #include "llvm/Support/Debug.h"
     22 #include "llvm/Support/ValueHandle.h"
     23 
     24 namespace llvm {
     25 
     26 class CastInst;
     27 class PHINode;
     28 template<typename T> class SSAUpdaterTraits;
     29 
     30 template<typename UpdaterT>
     31 class SSAUpdaterImpl {
     32 private:
     33   UpdaterT *Updater;
     34 
     35   typedef SSAUpdaterTraits<UpdaterT> Traits;
     36   typedef typename Traits::BlkT BlkT;
     37   typedef typename Traits::ValT ValT;
     38   typedef typename Traits::PhiT PhiT;
     39 
     40   /// BBInfo - Per-basic block information used internally by SSAUpdaterImpl.
     41   /// The predecessors of each block are cached here since pred_iterator is
     42   /// slow and we need to iterate over the blocks at least a few times.
     43   class BBInfo {
     44   public:
     45     BlkT *BB;          // Back-pointer to the corresponding block.
     46     ValT AvailableVal; // Value to use in this block.
     47     BBInfo *DefBB;     // Block that defines the available value.
     48     int BlkNum;        // Postorder number.
     49     BBInfo *IDom;      // Immediate dominator.
     50     unsigned NumPreds; // Number of predecessor blocks.
     51     BBInfo **Preds;    // Array[NumPreds] of predecessor blocks.
     52     PhiT *PHITag;      // Marker for existing PHIs that match.
     53 
     54     BBInfo(BlkT *ThisBB, ValT V)
     55       : BB(ThisBB), AvailableVal(V), DefBB(V ? this : 0), BlkNum(0), IDom(0),
     56       NumPreds(0), Preds(0), PHITag(0) { }
     57   };
     58 
     59   typedef DenseMap<BlkT*, ValT> AvailableValsTy;
     60   AvailableValsTy *AvailableVals;
     61 
     62   SmallVectorImpl<PhiT*> *InsertedPHIs;
     63 
     64   typedef SmallVectorImpl<BBInfo*> BlockListTy;
     65   typedef DenseMap<BlkT*, BBInfo*> BBMapTy;
     66   BBMapTy BBMap;
     67   BumpPtrAllocator Allocator;
     68 
     69 public:
     70   explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A,
     71                           SmallVectorImpl<PhiT*> *Ins) :
     72     Updater(U), AvailableVals(A), InsertedPHIs(Ins) { }
     73 
     74   /// GetValue - Check to see if AvailableVals has an entry for the specified
     75   /// BB and if so, return it.  If not, construct SSA form by first
     76   /// calculating the required placement of PHIs and then inserting new PHIs
     77   /// where needed.
     78   ValT GetValue(BlkT *BB) {
     79     SmallVector<BBInfo*, 100> BlockList;
     80     BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList);
     81 
     82     // Special case: bail out if BB is unreachable.
     83     if (BlockList.size() == 0) {
     84       ValT V = Traits::GetUndefVal(BB, Updater);
     85       (*AvailableVals)[BB] = V;
     86       return V;
     87     }
     88 
     89     FindDominators(&BlockList, PseudoEntry);
     90     FindPHIPlacement(&BlockList);
     91     FindAvailableVals(&BlockList);
     92 
     93     return BBMap[BB]->DefBB->AvailableVal;
     94   }
     95 
     96   /// BuildBlockList - Starting from the specified basic block, traverse back
     97   /// through its predecessors until reaching blocks with known values.
     98   /// Create BBInfo structures for the blocks and append them to the block
     99   /// list.
    100   BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) {
    101     SmallVector<BBInfo*, 10> RootList;
    102     SmallVector<BBInfo*, 64> WorkList;
    103 
    104     BBInfo *Info = new (Allocator) BBInfo(BB, 0);
    105     BBMap[BB] = Info;
    106     WorkList.push_back(Info);
    107 
    108     // Search backward from BB, creating BBInfos along the way and stopping
    109     // when reaching blocks that define the value.  Record those defining
    110     // blocks on the RootList.
    111     SmallVector<BlkT*, 10> Preds;
    112     while (!WorkList.empty()) {
    113       Info = WorkList.pop_back_val();
    114       Preds.clear();
    115       Traits::FindPredecessorBlocks(Info->BB, &Preds);
    116       Info->NumPreds = Preds.size();
    117       if (Info->NumPreds == 0)
    118         Info->Preds = 0;
    119       else
    120         Info->Preds = static_cast<BBInfo**>
    121           (Allocator.Allocate(Info->NumPreds * sizeof(BBInfo*),
    122                               AlignOf<BBInfo*>::Alignment));
    123 
    124       for (unsigned p = 0; p != Info->NumPreds; ++p) {
    125         BlkT *Pred = Preds[p];
    126         // Check if BBMap already has a BBInfo for the predecessor block.
    127         typename BBMapTy::value_type &BBMapBucket =
    128           BBMap.FindAndConstruct(Pred);
    129         if (BBMapBucket.second) {
    130           Info->Preds[p] = BBMapBucket.second;
    131           continue;
    132         }
    133 
    134         // Create a new BBInfo for the predecessor.
    135         ValT PredVal = AvailableVals->lookup(Pred);
    136         BBInfo *PredInfo = new (Allocator) BBInfo(Pred, PredVal);
    137         BBMapBucket.second = PredInfo;
    138         Info->Preds[p] = PredInfo;
    139 
    140         if (PredInfo->AvailableVal) {
    141           RootList.push_back(PredInfo);
    142           continue;
    143         }
    144         WorkList.push_back(PredInfo);
    145       }
    146     }
    147 
    148     // Now that we know what blocks are backwards-reachable from the starting
    149     // block, do a forward depth-first traversal to assign postorder numbers
    150     // to those blocks.
    151     BBInfo *PseudoEntry = new (Allocator) BBInfo(0, 0);
    152     unsigned BlkNum = 1;
    153 
    154     // Initialize the worklist with the roots from the backward traversal.
    155     while (!RootList.empty()) {
    156       Info = RootList.pop_back_val();
    157       Info->IDom = PseudoEntry;
    158       Info->BlkNum = -1;
    159       WorkList.push_back(Info);
    160     }
    161 
    162     while (!WorkList.empty()) {
    163       Info = WorkList.back();
    164 
    165       if (Info->BlkNum == -2) {
    166         // All the successors have been handled; assign the postorder number.
    167         Info->BlkNum = BlkNum++;
    168         // If not a root, put it on the BlockList.
    169         if (!Info->AvailableVal)
    170           BlockList->push_back(Info);
    171         WorkList.pop_back();
    172         continue;
    173       }
    174 
    175       // Leave this entry on the worklist, but set its BlkNum to mark that its
    176       // successors have been put on the worklist.  When it returns to the top
    177       // the list, after handling its successors, it will be assigned a
    178       // number.
    179       Info->BlkNum = -2;
    180 
    181       // Add unvisited successors to the work list.
    182       for (typename Traits::BlkSucc_iterator SI =
    183              Traits::BlkSucc_begin(Info->BB),
    184              E = Traits::BlkSucc_end(Info->BB); SI != E; ++SI) {
    185         BBInfo *SuccInfo = BBMap[*SI];
    186         if (!SuccInfo || SuccInfo->BlkNum)
    187           continue;
    188         SuccInfo->BlkNum = -1;
    189         WorkList.push_back(SuccInfo);
    190       }
    191     }
    192     PseudoEntry->BlkNum = BlkNum;
    193     return PseudoEntry;
    194   }
    195 
    196   /// IntersectDominators - This is the dataflow lattice "meet" operation for
    197   /// finding dominators.  Given two basic blocks, it walks up the dominator
    198   /// tree until it finds a common dominator of both.  It uses the postorder
    199   /// number of the blocks to determine how to do that.
    200   BBInfo *IntersectDominators(BBInfo *Blk1, BBInfo *Blk2) {
    201     while (Blk1 != Blk2) {
    202       while (Blk1->BlkNum < Blk2->BlkNum) {
    203         Blk1 = Blk1->IDom;
    204         if (!Blk1)
    205           return Blk2;
    206       }
    207       while (Blk2->BlkNum < Blk1->BlkNum) {
    208         Blk2 = Blk2->IDom;
    209         if (!Blk2)
    210           return Blk1;
    211       }
    212     }
    213     return Blk1;
    214   }
    215 
    216   /// FindDominators - Calculate the dominator tree for the subset of the CFG
    217   /// corresponding to the basic blocks on the BlockList.  This uses the
    218   /// algorithm from: "A Simple, Fast Dominance Algorithm" by Cooper, Harvey
    219   /// and Kennedy, published in Software--Practice and Experience, 2001,
    220   /// 4:1-10.  Because the CFG subset does not include any edges leading into
    221   /// blocks that define the value, the results are not the usual dominator
    222   /// tree.  The CFG subset has a single pseudo-entry node with edges to a set
    223   /// of root nodes for blocks that define the value.  The dominators for this
    224   /// subset CFG are not the standard dominators but they are adequate for
    225   /// placing PHIs within the subset CFG.
    226   void FindDominators(BlockListTy *BlockList, BBInfo *PseudoEntry) {
    227     bool Changed;
    228     do {
    229       Changed = false;
    230       // Iterate over the list in reverse order, i.e., forward on CFG edges.
    231       for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
    232              E = BlockList->rend(); I != E; ++I) {
    233         BBInfo *Info = *I;
    234         BBInfo *NewIDom = 0;
    235 
    236         // Iterate through the block's predecessors.
    237         for (unsigned p = 0; p != Info->NumPreds; ++p) {
    238           BBInfo *Pred = Info->Preds[p];
    239 
    240           // Treat an unreachable predecessor as a definition with 'undef'.
    241           if (Pred->BlkNum == 0) {
    242             Pred->AvailableVal = Traits::GetUndefVal(Pred->BB, Updater);
    243             (*AvailableVals)[Pred->BB] = Pred->AvailableVal;
    244             Pred->DefBB = Pred;
    245             Pred->BlkNum = PseudoEntry->BlkNum;
    246             PseudoEntry->BlkNum++;
    247           }
    248 
    249           if (!NewIDom)
    250             NewIDom = Pred;
    251           else
    252             NewIDom = IntersectDominators(NewIDom, Pred);
    253         }
    254 
    255         // Check if the IDom value has changed.
    256         if (NewIDom && NewIDom != Info->IDom) {
    257           Info->IDom = NewIDom;
    258           Changed = true;
    259         }
    260       }
    261     } while (Changed);
    262   }
    263 
    264   /// IsDefInDomFrontier - Search up the dominator tree from Pred to IDom for
    265   /// any blocks containing definitions of the value.  If one is found, then
    266   /// the successor of Pred is in the dominance frontier for the definition,
    267   /// and this function returns true.
    268   bool IsDefInDomFrontier(const BBInfo *Pred, const BBInfo *IDom) {
    269     for (; Pred != IDom; Pred = Pred->IDom) {
    270       if (Pred->DefBB == Pred)
    271         return true;
    272     }
    273     return false;
    274   }
    275 
    276   /// FindPHIPlacement - PHIs are needed in the iterated dominance frontiers
    277   /// of the known definitions.  Iteratively add PHIs in the dom frontiers
    278   /// until nothing changes.  Along the way, keep track of the nearest
    279   /// dominating definitions for non-PHI blocks.
    280   void FindPHIPlacement(BlockListTy *BlockList) {
    281     bool Changed;
    282     do {
    283       Changed = false;
    284       // Iterate over the list in reverse order, i.e., forward on CFG edges.
    285       for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
    286              E = BlockList->rend(); I != E; ++I) {
    287         BBInfo *Info = *I;
    288 
    289         // If this block already needs a PHI, there is nothing to do here.
    290         if (Info->DefBB == Info)
    291           continue;
    292 
    293         // Default to use the same def as the immediate dominator.
    294         BBInfo *NewDefBB = Info->IDom->DefBB;
    295         for (unsigned p = 0; p != Info->NumPreds; ++p) {
    296           if (IsDefInDomFrontier(Info->Preds[p], Info->IDom)) {
    297             // Need a PHI here.
    298             NewDefBB = Info;
    299             break;
    300           }
    301         }
    302 
    303         // Check if anything changed.
    304         if (NewDefBB != Info->DefBB) {
    305           Info->DefBB = NewDefBB;
    306           Changed = true;
    307         }
    308       }
    309     } while (Changed);
    310   }
    311 
    312   /// FindAvailableVal - If this block requires a PHI, first check if an
    313   /// existing PHI matches the PHI placement and reaching definitions computed
    314   /// earlier, and if not, create a new PHI.  Visit all the block's
    315   /// predecessors to calculate the available value for each one and fill in
    316   /// the incoming values for a new PHI.
    317   void FindAvailableVals(BlockListTy *BlockList) {
    318     // Go through the worklist in forward order (i.e., backward through the CFG)
    319     // and check if existing PHIs can be used.  If not, create empty PHIs where
    320     // they are needed.
    321     for (typename BlockListTy::iterator I = BlockList->begin(),
    322            E = BlockList->end(); I != E; ++I) {
    323       BBInfo *Info = *I;
    324       // Check if there needs to be a PHI in BB.
    325       if (Info->DefBB != Info)
    326         continue;
    327 
    328       // Look for an existing PHI.
    329       FindExistingPHI(Info->BB, BlockList);
    330       if (Info->AvailableVal)
    331         continue;
    332 
    333       ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
    334       Info->AvailableVal = PHI;
    335       (*AvailableVals)[Info->BB] = PHI;
    336     }
    337 
    338     // Now go back through the worklist in reverse order to fill in the
    339     // arguments for any new PHIs added in the forward traversal.
    340     for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
    341            E = BlockList->rend(); I != E; ++I) {
    342       BBInfo *Info = *I;
    343 
    344       if (Info->DefBB != Info) {
    345         // Record the available value at join nodes to speed up subsequent
    346         // uses of this SSAUpdater for the same value.
    347         if (Info->NumPreds > 1)
    348           (*AvailableVals)[Info->BB] = Info->DefBB->AvailableVal;
    349         continue;
    350       }
    351 
    352       // Check if this block contains a newly added PHI.
    353       PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
    354       if (!PHI)
    355         continue;
    356 
    357       // Iterate through the block's predecessors.
    358       for (unsigned p = 0; p != Info->NumPreds; ++p) {
    359         BBInfo *PredInfo = Info->Preds[p];
    360         BlkT *Pred = PredInfo->BB;
    361         // Skip to the nearest preceding definition.
    362         if (PredInfo->DefBB != PredInfo)
    363           PredInfo = PredInfo->DefBB;
    364         Traits::AddPHIOperand(PHI, PredInfo->AvailableVal, Pred);
    365       }
    366 
    367       DEBUG(dbgs() << "  Inserted PHI: " << *PHI << "\n");
    368 
    369       // If the client wants to know about all new instructions, tell it.
    370       if (InsertedPHIs) InsertedPHIs->push_back(PHI);
    371     }
    372   }
    373 
    374   /// FindExistingPHI - Look through the PHI nodes in a block to see if any of
    375   /// them match what is needed.
    376   void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
    377     for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
    378          BBI != BBE; ++BBI) {
    379       PhiT *SomePHI = Traits::InstrIsPHI(BBI);
    380       if (!SomePHI)
    381         break;
    382       if (CheckIfPHIMatches(SomePHI)) {
    383         RecordMatchingPHIs(BlockList);
    384         break;
    385       }
    386       // Match failed: clear all the PHITag values.
    387       for (typename BlockListTy::iterator I = BlockList->begin(),
    388              E = BlockList->end(); I != E; ++I)
    389         (*I)->PHITag = 0;
    390     }
    391   }
    392 
    393   /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
    394   /// in the BBMap.
    395   bool CheckIfPHIMatches(PhiT *PHI) {
    396     SmallVector<PhiT*, 20> WorkList;
    397     WorkList.push_back(PHI);
    398 
    399     // Mark that the block containing this PHI has been visited.
    400     BBMap[PHI->getParent()]->PHITag = PHI;
    401 
    402     while (!WorkList.empty()) {
    403       PHI = WorkList.pop_back_val();
    404 
    405       // Iterate through the PHI's incoming values.
    406       for (typename Traits::PHI_iterator I = Traits::PHI_begin(PHI),
    407              E = Traits::PHI_end(PHI); I != E; ++I) {
    408         ValT IncomingVal = I.getIncomingValue();
    409         BBInfo *PredInfo = BBMap[I.getIncomingBlock()];
    410         // Skip to the nearest preceding definition.
    411         if (PredInfo->DefBB != PredInfo)
    412           PredInfo = PredInfo->DefBB;
    413 
    414         // Check if it matches the expected value.
    415         if (PredInfo->AvailableVal) {
    416           if (IncomingVal == PredInfo->AvailableVal)
    417             continue;
    418           return false;
    419         }
    420 
    421         // Check if the value is a PHI in the correct block.
    422         PhiT *IncomingPHIVal = Traits::ValueIsPHI(IncomingVal, Updater);
    423         if (!IncomingPHIVal || IncomingPHIVal->getParent() != PredInfo->BB)
    424           return false;
    425 
    426         // If this block has already been visited, check if this PHI matches.
    427         if (PredInfo->PHITag) {
    428           if (IncomingPHIVal == PredInfo->PHITag)
    429             continue;
    430           return false;
    431         }
    432         PredInfo->PHITag = IncomingPHIVal;
    433 
    434         WorkList.push_back(IncomingPHIVal);
    435       }
    436     }
    437     return true;
    438   }
    439 
    440   /// RecordMatchingPHIs - For each PHI node that matches, record it in both
    441   /// the BBMap and the AvailableVals mapping.
    442   void RecordMatchingPHIs(BlockListTy *BlockList) {
    443     for (typename BlockListTy::iterator I = BlockList->begin(),
    444            E = BlockList->end(); I != E; ++I)
    445       if (PhiT *PHI = (*I)->PHITag) {
    446         BlkT *BB = PHI->getParent();
    447         ValT PHIVal = Traits::GetPHIValue(PHI);
    448         (*AvailableVals)[BB] = PHIVal;
    449         BBMap[BB]->AvailableVal = PHIVal;
    450       }
    451   }
    452 };
    453 
    454 } // End llvm namespace
    455 
    456 #endif
    457