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