1 //===- SSAUpdaterBulk.cpp - Unstructured SSA Update Tool ------------------===//
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 implements the SSAUpdaterBulk class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
15 #include "llvm/Analysis/IteratedDominanceFrontier.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Use.h"
21 #include "llvm/IR/Value.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "ssaupdaterbulk"
26 
27 /// Helper function for finding a block which should have a value for the given
28 /// user. For PHI-nodes this block is the corresponding predecessor, for other
29 /// instructions it's their parent block.
getUserBB(Use * U)30 static BasicBlock *getUserBB(Use *U) {
31   auto *User = cast<Instruction>(U->getUser());
32 
33   if (auto *UserPN = dyn_cast<PHINode>(User))
34     return UserPN->getIncomingBlock(*U);
35   else
36     return User->getParent();
37 }
38 
39 /// Add a new variable to the SSA rewriter. This needs to be called before
40 /// AddAvailableValue or AddUse calls.
AddVariable(StringRef Name,Type * Ty)41 unsigned SSAUpdaterBulk::AddVariable(StringRef Name, Type *Ty) {
42   unsigned Var = Rewrites.size();
43   LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": initialized with Ty = "
44                     << *Ty << ", Name = " << Name << "\n");
45   RewriteInfo RI(Name, Ty);
46   Rewrites.push_back(RI);
47   return Var;
48 }
49 
50 /// Indicate that a rewritten value is available in the specified block with the
51 /// specified value.
AddAvailableValue(unsigned Var,BasicBlock * BB,Value * V)52 void SSAUpdaterBulk::AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V) {
53   assert(Var < Rewrites.size() && "Variable not found!");
54   LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var
55                     << ": added new available value" << *V << " in "
56                     << BB->getName() << "\n");
57   Rewrites[Var].Defines[BB] = V;
58 }
59 
60 /// Record a use of the symbolic value. This use will be updated with a
61 /// rewritten value when RewriteAllUses is called.
AddUse(unsigned Var,Use * U)62 void SSAUpdaterBulk::AddUse(unsigned Var, Use *U) {
63   assert(Var < Rewrites.size() && "Variable not found!");
64   LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": added a use" << *U->get()
65                     << " in " << getUserBB(U)->getName() << "\n");
66   Rewrites[Var].Uses.push_back(U);
67 }
68 
69 /// Return true if the SSAUpdater already has a value for the specified variable
70 /// in the specified block.
HasValueForBlock(unsigned Var,BasicBlock * BB)71 bool SSAUpdaterBulk::HasValueForBlock(unsigned Var, BasicBlock *BB) {
72   return (Var < Rewrites.size()) ? Rewrites[Var].Defines.count(BB) : false;
73 }
74 
75 // Compute value at the given block BB. We either should already know it, or we
76 // should be able to recursively reach it going up dominator tree.
computeValueAt(BasicBlock * BB,RewriteInfo & R,DominatorTree * DT)77 Value *SSAUpdaterBulk::computeValueAt(BasicBlock *BB, RewriteInfo &R,
78                                       DominatorTree *DT) {
79   if (!R.Defines.count(BB)) {
80     if (DT->isReachableFromEntry(BB) && PredCache.get(BB).size()) {
81       BasicBlock *IDom = DT->getNode(BB)->getIDom()->getBlock();
82       Value *V = computeValueAt(IDom, R, DT);
83       R.Defines[BB] = V;
84     } else
85       R.Defines[BB] = UndefValue::get(R.Ty);
86   }
87   return R.Defines[BB];
88 }
89 
90 /// Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
91 /// This is basically a subgraph limited by DefBlocks and UsingBlocks.
92 static void
ComputeLiveInBlocks(const SmallPtrSetImpl<BasicBlock * > & UsingBlocks,const SmallPtrSetImpl<BasicBlock * > & DefBlocks,SmallPtrSetImpl<BasicBlock * > & LiveInBlocks,PredIteratorCache & PredCache)93 ComputeLiveInBlocks(const SmallPtrSetImpl<BasicBlock *> &UsingBlocks,
94                     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
95                     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks,
96                     PredIteratorCache &PredCache) {
97   // To determine liveness, we must iterate through the predecessors of blocks
98   // where the def is live.  Blocks are added to the worklist if we need to
99   // check their predecessors.  Start with all the using blocks.
100   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(UsingBlocks.begin(),
101                                                     UsingBlocks.end());
102 
103   // Now that we have a set of blocks where the phi is live-in, recursively add
104   // their predecessors until we find the full region the value is live.
105   while (!LiveInBlockWorklist.empty()) {
106     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
107 
108     // The block really is live in here, insert it into the set.  If already in
109     // the set, then it has already been processed.
110     if (!LiveInBlocks.insert(BB).second)
111       continue;
112 
113     // Since the value is live into BB, it is either defined in a predecessor or
114     // live into it to.  Add the preds to the worklist unless they are a
115     // defining block.
116     for (BasicBlock *P : PredCache.get(BB)) {
117       // The value is not live into a predecessor if it defines the value.
118       if (DefBlocks.count(P))
119         continue;
120 
121       // Otherwise it is, add to the worklist.
122       LiveInBlockWorklist.push_back(P);
123     }
124   }
125 }
126 
127 /// Perform all the necessary updates, including new PHI-nodes insertion and the
128 /// requested uses update.
RewriteAllUses(DominatorTree * DT,SmallVectorImpl<PHINode * > * InsertedPHIs)129 void SSAUpdaterBulk::RewriteAllUses(DominatorTree *DT,
130                                     SmallVectorImpl<PHINode *> *InsertedPHIs) {
131   for (auto &R : Rewrites) {
132     // Compute locations for new phi-nodes.
133     // For that we need to initialize DefBlocks from definitions in R.Defines,
134     // UsingBlocks from uses in R.Uses, then compute LiveInBlocks, and then use
135     // this set for computing iterated dominance frontier (IDF).
136     // The IDF blocks are the blocks where we need to insert new phi-nodes.
137     ForwardIDFCalculator IDF(*DT);
138     LLVM_DEBUG(dbgs() << "SSAUpdater: rewriting " << R.Uses.size()
139                       << " use(s)\n");
140 
141     SmallPtrSet<BasicBlock *, 2> DefBlocks;
142     for (auto &Def : R.Defines)
143       DefBlocks.insert(Def.first);
144     IDF.setDefiningBlocks(DefBlocks);
145 
146     SmallPtrSet<BasicBlock *, 2> UsingBlocks;
147     for (Use *U : R.Uses)
148       UsingBlocks.insert(getUserBB(U));
149 
150     SmallVector<BasicBlock *, 32> IDFBlocks;
151     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
152     ComputeLiveInBlocks(UsingBlocks, DefBlocks, LiveInBlocks, PredCache);
153     IDF.resetLiveInBlocks();
154     IDF.setLiveInBlocks(LiveInBlocks);
155     IDF.calculate(IDFBlocks);
156 
157     // We've computed IDF, now insert new phi-nodes there.
158     SmallVector<PHINode *, 4> InsertedPHIsForVar;
159     for (auto *FrontierBB : IDFBlocks) {
160       IRBuilder<> B(FrontierBB, FrontierBB->begin());
161       PHINode *PN = B.CreatePHI(R.Ty, 0, R.Name);
162       R.Defines[FrontierBB] = PN;
163       InsertedPHIsForVar.push_back(PN);
164       if (InsertedPHIs)
165         InsertedPHIs->push_back(PN);
166     }
167 
168     // Fill in arguments of the inserted PHIs.
169     for (auto *PN : InsertedPHIsForVar) {
170       BasicBlock *PBB = PN->getParent();
171       for (BasicBlock *Pred : PredCache.get(PBB))
172         PN->addIncoming(computeValueAt(Pred, R, DT), Pred);
173     }
174 
175     // Rewrite actual uses with the inserted definitions.
176     SmallPtrSet<Use *, 4> ProcessedUses;
177     for (Use *U : R.Uses) {
178       if (!ProcessedUses.insert(U).second)
179         continue;
180       Value *V = computeValueAt(getUserBB(U), R, DT);
181       Value *OldVal = U->get();
182       assert(OldVal && "Invalid use!");
183       // Notify that users of the existing value that it is being replaced.
184       if (OldVal != V && OldVal->hasValueHandle())
185         ValueHandleBase::ValueIsRAUWd(OldVal, V);
186       LLVM_DEBUG(dbgs() << "SSAUpdater: replacing " << *OldVal << " with " << *V
187                         << "\n");
188       U->set(V);
189     }
190   }
191 }
192