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