LLVM  8.0.1
SSAUpdaterBulk.cpp
Go to the documentation of this file.
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 
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.
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.
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.
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.
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.
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
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.
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 
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 
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())
186  LLVM_DEBUG(dbgs() << "SSAUpdater: replacing " << *OldVal << " with " << *V
187  << "\n");
188  U->set(V);
189  }
190  }
191 }
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void push_back(const T &Elt)
Definition: SmallVector.h:218
bool hasValueHandle() const
Return true if there is a value handle associated with this value.
Definition: Value.h:486
This defines the Use class.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:300
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:344
ArrayRef< BasicBlock * > get(BasicBlock *BB)
unsigned AddVariable(StringRef Name, Type *Ty)
Add a new variable to the SSA rewriter.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
void setDefiningBlocks(const SmallPtrSetImpl< BasicBlock *> &Blocks)
Give the IDF calculator the set of blocks in which the value is defined.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:743
void AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries...
static void ValueIsRAUWd(Value *Old, Value *New)
Definition: Value.cpp:885
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:145
NodeT * getBlock() const
#define P(N)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
static void ComputeLiveInBlocks(const SmallPtrSetImpl< BasicBlock *> &UsingBlocks, const SmallPtrSetImpl< BasicBlock *> &DefBlocks, SmallPtrSetImpl< BasicBlock *> &LiveInBlocks, PredIteratorCache &PredCache)
Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
DomTreeNodeBase * getIDom() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
void resetLiveInBlocks()
Reset the live-in block set to be empty, and tell the IDF calculator to not use liveness anymore...
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1415
void AddUse(unsigned Var, Use *U)
Record a use of the symbolic value.
size_t size() const
Definition: SmallVector.h:53
Compute iterated dominance frontiers using a linear time algorithm.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void setLiveInBlocks(const SmallPtrSetImpl< BasicBlock *> &Blocks)
Give the IDF calculator the set of blocks in which the value is live on entry to the block...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
void calculate(SmallVectorImpl< BasicBlock *> &IDFBlocks)
Calculate iterated dominance frontiers.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
void RewriteAllUses(DominatorTree *DT, SmallVectorImpl< PHINode *> *InsertedPHIs=nullptr)
Perform all the necessary updates, including new PHI-nodes insertion and the requested uses update...
iterator begin() const
Definition: SmallPtrSet.h:397
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
iterator end() const
Definition: SmallPtrSet.h:402
Determine the iterated dominance frontier, given a set of defining blocks, and optionally, a set of live-in blocks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
#define LLVM_DEBUG(X)
Definition: Debug.h:123
bool HasValueForBlock(unsigned Var, BasicBlock *BB)
Return true if the SSAUpdater already has a value for the specified variable in the specified block...
static BasicBlock * getUserBB(Use *U)
Helper function for finding a block which should have a value for the given user. ...