1 //===-- SSAUpdaterImpl.h - SSA Updater Implementation -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides a template that implements the core algorithm for the
11 // SSAUpdater and MachineSSAUpdater.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
16 #define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
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"
28 template<typename T> class SSAUpdaterTraits;
30 template<typename UpdaterT>
31 class SSAUpdaterImpl {
35 typedef SSAUpdaterTraits<UpdaterT> Traits;
36 typedef typename Traits::BlkT BlkT;
37 typedef typename Traits::ValT ValT;
38 typedef typename Traits::PhiT PhiT;
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.
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.
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) { }
59 typedef DenseMap<BlkT*, ValT> AvailableValsTy;
60 AvailableValsTy *AvailableVals;
62 SmallVectorImpl<PhiT*> *InsertedPHIs;
64 typedef SmallVectorImpl<BBInfo*> BlockListTy;
65 typedef DenseMap<BlkT*, BBInfo*> BBMapTy;
67 BumpPtrAllocator Allocator;
70 explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A,
71 SmallVectorImpl<PhiT*> *Ins) :
72 Updater(U), AvailableVals(A), InsertedPHIs(Ins) { }
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
78 ValT GetValue(BlkT *BB) {
79 SmallVector<BBInfo*, 100> BlockList;
80 BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList);
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;
89 FindDominators(&BlockList, PseudoEntry);
90 FindPHIPlacement(&BlockList);
91 FindAvailableVals(&BlockList);
93 return BBMap[BB]->DefBB->AvailableVal;
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
100 BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) {
101 SmallVector<BBInfo*, 10> RootList;
102 SmallVector<BBInfo*, 64> WorkList;
104 BBInfo *Info = new (Allocator) BBInfo(BB, 0);
106 WorkList.push_back(Info);
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();
115 Traits::FindPredecessorBlocks(Info->BB, &Preds);
116 Info->NumPreds = Preds.size();
117 if (Info->NumPreds == 0)
120 Info->Preds = static_cast<BBInfo**>
121 (Allocator.Allocate(Info->NumPreds * sizeof(BBInfo*),
122 AlignOf<BBInfo*>::Alignment));
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;
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;
140 if (PredInfo->AvailableVal) {
141 RootList.push_back(PredInfo);
144 WorkList.push_back(PredInfo);
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
151 BBInfo *PseudoEntry = new (Allocator) BBInfo(0, 0);
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;
159 WorkList.push_back(Info);
162 while (!WorkList.empty()) {
163 Info = WorkList.back();
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);
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
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)
188 SuccInfo->BlkNum = -1;
189 WorkList.push_back(SuccInfo);
192 PseudoEntry->BlkNum = BlkNum;
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) {
207 while (Blk2->BlkNum < Blk1->BlkNum) {
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) {
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) {
236 // Iterate through the block's predecessors.
237 for (unsigned p = 0; p != Info->NumPreds; ++p) {
238 BBInfo *Pred = Info->Preds[p];
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;
245 Pred->BlkNum = PseudoEntry->BlkNum;
246 PseudoEntry->BlkNum++;
252 NewIDom = IntersectDominators(NewIDom, Pred);
255 // Check if the IDom value has changed.
256 if (NewIDom && NewIDom != Info->IDom) {
257 Info->IDom = NewIDom;
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)
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) {
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) {
289 // If this block already needs a PHI, there is nothing to do here.
290 if (Info->DefBB == Info)
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)) {
303 // Check if anything changed.
304 if (NewDefBB != Info->DefBB) {
305 Info->DefBB = NewDefBB;
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
321 for (typename BlockListTy::iterator I = BlockList->begin(),
322 E = BlockList->end(); I != E; ++I) {
324 // Check if there needs to be a PHI in BB.
325 if (Info->DefBB != Info)
328 // Look for an existing PHI.
329 FindExistingPHI(Info->BB, BlockList);
330 if (Info->AvailableVal)
333 ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
334 Info->AvailableVal = PHI;
335 (*AvailableVals)[Info->BB] = PHI;
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) {
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;
352 // Check if this block contains a newly added PHI.
353 PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
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);
367 DEBUG(dbgs() << " Inserted PHI: " << *PHI << "\n");
369 // If the client wants to know about all new instructions, tell it.
370 if (InsertedPHIs) InsertedPHIs->push_back(PHI);
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();
379 PhiT *SomePHI = Traits::InstrIsPHI(BBI);
382 if (CheckIfPHIMatches(SomePHI)) {
383 RecordMatchingPHIs(BlockList);
386 // Match failed: clear all the PHITag values.
387 for (typename BlockListTy::iterator I = BlockList->begin(),
388 E = BlockList->end(); I != E; ++I)
393 /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
395 bool CheckIfPHIMatches(PhiT *PHI) {
396 SmallVector<PhiT*, 20> WorkList;
397 WorkList.push_back(PHI);
399 // Mark that the block containing this PHI has been visited.
400 BBMap[PHI->getParent()]->PHITag = PHI;
402 while (!WorkList.empty()) {
403 PHI = WorkList.pop_back_val();
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;
414 // Check if it matches the expected value.
415 if (PredInfo->AvailableVal) {
416 if (IncomingVal == PredInfo->AvailableVal)
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)
426 // If this block has already been visited, check if this PHI matches.
427 if (PredInfo->PHITag) {
428 if (IncomingPHIVal == PredInfo->PHITag)
432 PredInfo->PHITag = IncomingPHIVal;
434 WorkList.push_back(IncomingPHIVal);
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;
454 } // End llvm namespace