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