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