SSAUpdater.cpp revision 45305d4ff6bff8dfe62228c68b3cb61bb2d7254f
1//===- SSAUpdater.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 SSAUpdater class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/SSAUpdater.h"
15#include "llvm/Instructions.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/Support/CFG.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/ValueHandle.h"
20#include "llvm/Support/raw_ostream.h"
21using namespace llvm;
22
23typedef DenseMap<BasicBlock*, TrackingVH<Value> > AvailableValsTy;
24typedef std::vector<std::pair<BasicBlock*, TrackingVH<Value> > >
25                IncomingPredInfoTy;
26
27static AvailableValsTy &getAvailableVals(void *AV) {
28  return *static_cast<AvailableValsTy*>(AV);
29}
30
31static IncomingPredInfoTy &getIncomingPredInfo(void *IPI) {
32  return *static_cast<IncomingPredInfoTy*>(IPI);
33}
34
35
36SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
37  : AV(0), PrototypeValue(0), IPI(0), InsertedPHIs(NewPHI) {}
38
39SSAUpdater::~SSAUpdater() {
40  delete &getAvailableVals(AV);
41  delete &getIncomingPredInfo(IPI);
42}
43
44/// Initialize - Reset this object to get ready for a new set of SSA
45/// updates.  ProtoValue is the value used to name PHI nodes.
46void SSAUpdater::Initialize(Value *ProtoValue) {
47  if (AV == 0)
48    AV = new AvailableValsTy();
49  else
50    getAvailableVals(AV).clear();
51
52  if (IPI == 0)
53    IPI = new IncomingPredInfoTy();
54  else
55    getIncomingPredInfo(IPI).clear();
56  PrototypeValue = ProtoValue;
57}
58
59/// HasValueForBlock - Return true if the SSAUpdater already has a value for
60/// the specified block.
61bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
62  return getAvailableVals(AV).count(BB);
63}
64
65/// AddAvailableValue - Indicate that a rewritten value is available in the
66/// specified block with the specified value.
67void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
68  assert(PrototypeValue != 0 && "Need to initialize SSAUpdater");
69  assert(PrototypeValue->getType() == V->getType() &&
70         "All rewritten values must have the same type");
71  getAvailableVals(AV)[BB] = V;
72}
73
74/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
75/// live at the end of the specified block.
76Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
77  assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
78  Value *Res = GetValueAtEndOfBlockInternal(BB);
79  assert(getIncomingPredInfo(IPI).empty() && "Unexpected Internal State");
80  return Res;
81}
82
83/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
84/// is live in the middle of the specified block.
85///
86/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
87/// important case: if there is a definition of the rewritten value after the
88/// 'use' in BB.  Consider code like this:
89///
90///      X1 = ...
91///   SomeBB:
92///      use(X)
93///      X2 = ...
94///      br Cond, SomeBB, OutBB
95///
96/// In this case, there are two values (X1 and X2) added to the AvailableVals
97/// set by the client of the rewriter, and those values are both live out of
98/// their respective blocks.  However, the use of X happens in the *middle* of
99/// a block.  Because of this, we need to insert a new PHI node in SomeBB to
100/// merge the appropriate values, and this value isn't live out of the block.
101///
102Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
103  // If there is no definition of the renamed variable in this block, just use
104  // GetValueAtEndOfBlock to do our work.
105  if (!getAvailableVals(AV).count(BB))
106    return GetValueAtEndOfBlock(BB);
107
108  // Otherwise, we have the hard case.  Get the live-in values for each
109  // predecessor.
110  SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
111  Value *SingularValue = 0;
112
113  // We can get our predecessor info by walking the pred_iterator list, but it
114  // is relatively slow.  If we already have PHI nodes in this block, walk one
115  // of them to get the predecessor list instead.
116  if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
117    for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
118      BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
119      Value *PredVal = GetValueAtEndOfBlock(PredBB);
120      PredValues.push_back(std::make_pair(PredBB, PredVal));
121
122      // Compute SingularValue.
123      if (i == 0)
124        SingularValue = PredVal;
125      else if (PredVal != SingularValue)
126        SingularValue = 0;
127    }
128  } else {
129    bool isFirstPred = true;
130    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
131      BasicBlock *PredBB = *PI;
132      Value *PredVal = GetValueAtEndOfBlock(PredBB);
133      PredValues.push_back(std::make_pair(PredBB, PredVal));
134
135      // Compute SingularValue.
136      if (isFirstPred) {
137        SingularValue = PredVal;
138        isFirstPred = false;
139      } else if (PredVal != SingularValue)
140        SingularValue = 0;
141    }
142  }
143
144  // If there are no predecessors, just return undef.
145  if (PredValues.empty())
146    return UndefValue::get(PrototypeValue->getType());
147
148  // Otherwise, if all the merged values are the same, just use it.
149  if (SingularValue != 0)
150    return SingularValue;
151
152  // Otherwise, we do need a PHI: insert one now.
153  PHINode *InsertedPHI = PHINode::Create(PrototypeValue->getType(),
154                                         PrototypeValue->getName(),
155                                         &BB->front());
156  InsertedPHI->reserveOperandSpace(PredValues.size());
157
158  // Fill in all the predecessors of the PHI.
159  for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
160    InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
161
162  // See if the PHI node can be merged to a single value.  This can happen in
163  // loop cases when we get a PHI of itself and one other value.
164  if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
165    InsertedPHI->eraseFromParent();
166    return ConstVal;
167  }
168
169  // If the client wants to know about all new instructions, tell it.
170  if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
171
172  DEBUG(errs() << "  Inserted PHI: " << *InsertedPHI << "\n");
173  return InsertedPHI;
174}
175
176/// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI nodes,
177/// which use their value in the corresponding predecessor.
178void SSAUpdater::RewriteUse(Use &U) {
179  Instruction *User = cast<Instruction>(U.getUser());
180
181  Value *V;
182  if (PHINode *UserPN = dyn_cast<PHINode>(User))
183    V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
184  else
185    V = GetValueInMiddleOfBlock(User->getParent());
186
187  U.set(V);
188}
189
190
191/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
192/// for the specified BB and if so, return it.  If not, construct SSA form by
193/// walking predecessors inserting PHI nodes as needed until we get to a block
194/// where the value is available.
195///
196Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
197  AvailableValsTy &AvailableVals = getAvailableVals(AV);
198
199  // Query AvailableVals by doing an insertion of null.
200  std::pair<AvailableValsTy::iterator, bool> InsertRes =
201  AvailableVals.insert(std::make_pair(BB, WeakVH()));
202
203  // Handle the case when the insertion fails because we have already seen BB.
204  if (!InsertRes.second) {
205    // If the insertion failed, there are two cases.  The first case is that the
206    // value is already available for the specified block.  If we get this, just
207    // return the value.
208    if (InsertRes.first->second != 0)
209      return InsertRes.first->second;
210
211    // Otherwise, if the value we find is null, then this is the value is not
212    // known but it is being computed elsewhere in our recursion.  This means
213    // that we have a cycle.  Handle this by inserting a PHI node and returning
214    // it.  When we get back to the first instance of the recursion we will fill
215    // in the PHI node.
216    return InsertRes.first->second =
217    PHINode::Create(PrototypeValue->getType(), PrototypeValue->getName(),
218                    &BB->front());
219  }
220
221  // Okay, the value isn't in the map and we just inserted a null in the entry
222  // to indicate that we're processing the block.  Since we have no idea what
223  // value is in this block, we have to recurse through our predecessors.
224  //
225  // While we're walking our predecessors, we keep track of them in a vector,
226  // then insert a PHI node in the end if we actually need one.  We could use a
227  // smallvector here, but that would take a lot of stack space for every level
228  // of the recursion, just use IncomingPredInfo as an explicit stack.
229  IncomingPredInfoTy &IncomingPredInfo = getIncomingPredInfo(IPI);
230  unsigned FirstPredInfoEntry = IncomingPredInfo.size();
231
232  // As we're walking the predecessors, keep track of whether they are all
233  // producing the same value.  If so, this value will capture it, if not, it
234  // will get reset to null.  We distinguish the no-predecessor case explicitly
235  // below.
236  TrackingVH<Value> SingularValue;
237
238  // We can get our predecessor info by walking the pred_iterator list, but it
239  // is relatively slow.  If we already have PHI nodes in this block, walk one
240  // of them to get the predecessor list instead.
241  if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
242    for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
243      BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
244      Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
245      IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
246
247      // Compute SingularValue.
248      if (i == 0)
249        SingularValue = PredVal;
250      else if (PredVal != SingularValue)
251        SingularValue = 0;
252    }
253  } else {
254    bool isFirstPred = true;
255    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
256      BasicBlock *PredBB = *PI;
257      Value *PredVal = GetValueAtEndOfBlockInternal(PredBB);
258      IncomingPredInfo.push_back(std::make_pair(PredBB, PredVal));
259
260      // Compute SingularValue.
261      if (isFirstPred) {
262        SingularValue = PredVal;
263        isFirstPred = false;
264      } else if (PredVal != SingularValue)
265        SingularValue = 0;
266    }
267  }
268
269  // If there are no predecessors, then we must have found an unreachable block
270  // just return 'undef'.  Since there are no predecessors, InsertRes must not
271  // be invalidated.
272  if (IncomingPredInfo.size() == FirstPredInfoEntry)
273    return InsertRes.first->second = UndefValue::get(PrototypeValue->getType());
274
275  /// Look up BB's entry in AvailableVals.  'InsertRes' may be invalidated.  If
276  /// this block is involved in a loop, a no-entry PHI node will have been
277  /// inserted as InsertedVal.  Otherwise, we'll still have the null we inserted
278  /// above.
279  TrackingVH<Value> &InsertedVal = AvailableVals[BB];
280
281  // If all the predecessor values are the same then we don't need to insert a
282  // PHI.  This is the simple and common case.
283  if (SingularValue) {
284    // If a PHI node got inserted, replace it with the singlar value and delete
285    // it.
286    if (InsertedVal) {
287      PHINode *OldVal = cast<PHINode>(InsertedVal);
288      // Be careful about dead loops.  These RAUW's also update InsertedVal.
289      if (InsertedVal != SingularValue)
290        OldVal->replaceAllUsesWith(SingularValue);
291      else
292        OldVal->replaceAllUsesWith(UndefValue::get(InsertedVal->getType()));
293      OldVal->eraseFromParent();
294    } else {
295      InsertedVal = SingularValue;
296    }
297
298    // Either path through the 'if' should have set insertedVal -> SingularVal.
299    assert((InsertedVal == SingularValue || isa<UndefValue>(InsertedVal)) &&
300           "RAUW didn't change InsertedVal to be SingularVal");
301
302    // Drop the entries we added in IncomingPredInfo to restore the stack.
303    IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
304                           IncomingPredInfo.end());
305    return SingularValue;
306  }
307
308  // Otherwise, we do need a PHI: insert one now if we don't already have one.
309  if (InsertedVal == 0)
310    InsertedVal = PHINode::Create(PrototypeValue->getType(),
311                                  PrototypeValue->getName(), &BB->front());
312
313  PHINode *InsertedPHI = cast<PHINode>(InsertedVal);
314  InsertedPHI->reserveOperandSpace(IncomingPredInfo.size()-FirstPredInfoEntry);
315
316  // Fill in all the predecessors of the PHI.
317  for (IncomingPredInfoTy::iterator I =
318         IncomingPredInfo.begin()+FirstPredInfoEntry,
319       E = IncomingPredInfo.end(); I != E; ++I)
320    InsertedPHI->addIncoming(I->second, I->first);
321
322  // Drop the entries we added in IncomingPredInfo to restore the stack.
323  IncomingPredInfo.erase(IncomingPredInfo.begin()+FirstPredInfoEntry,
324                         IncomingPredInfo.end());
325
326  // See if the PHI node can be merged to a single value.  This can happen in
327  // loop cases when we get a PHI of itself and one other value.
328  if (Value *ConstVal = InsertedPHI->hasConstantValue()) {
329    InsertedPHI->replaceAllUsesWith(ConstVal);
330    InsertedPHI->eraseFromParent();
331    InsertedVal = ConstVal;
332  } else {
333    DEBUG(errs() << "  Inserted PHI: " << *InsertedPHI << "\n");
334
335    // If the client wants to know about all new instructions, tell it.
336    if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
337  }
338
339  return InsertedVal;
340}
341