[C++11] Add predecessors(BasicBlock *) / successors(BasicBlock *) iterator ranges.
[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/ADT/DenseMap.h"
16 #include "llvm/ADT/TinyPtrVector.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
27
28 using namespace llvm;
29
30 #define DEBUG_TYPE "ssaupdater"
31
32 typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
33 static AvailableValsTy &getAvailableVals(void *AV) {
34   return *static_cast<AvailableValsTy*>(AV);
35 }
36
37 SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
38   : AV(nullptr), ProtoType(nullptr), ProtoName(), InsertedPHIs(NewPHI) {}
39
40 SSAUpdater::~SSAUpdater() {
41   delete static_cast<AvailableValsTy*>(AV);
42 }
43
44 void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
45   if (!AV)
46     AV = new AvailableValsTy();
47   else
48     getAvailableVals(AV).clear();
49   ProtoType = Ty;
50   ProtoName = Name;
51 }
52
53 bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
54   return getAvailableVals(AV).count(BB);
55 }
56
57 void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
58   assert(ProtoType && "Need to initialize SSAUpdater");
59   assert(ProtoType == V->getType() &&
60          "All rewritten values must have the same type");
61   getAvailableVals(AV)[BB] = V;
62 }
63
64 static bool IsEquivalentPHI(PHINode *PHI,
65                           SmallDenseMap<BasicBlock*, Value*, 8> &ValueMapping) {
66   unsigned PHINumValues = PHI->getNumIncomingValues();
67   if (PHINumValues != ValueMapping.size())
68     return false;
69
70   // Scan the phi to see if it matches.
71   for (unsigned i = 0, e = PHINumValues; i != e; ++i)
72     if (ValueMapping[PHI->getIncomingBlock(i)] !=
73         PHI->getIncomingValue(i)) {
74       return false;
75     }
76
77   return true;
78 }
79
80 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
81   Value *Res = GetValueAtEndOfBlockInternal(BB);
82   return Res;
83 }
84
85 Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
86   // If there is no definition of the renamed variable in this block, just use
87   // GetValueAtEndOfBlock to do our work.
88   if (!HasValueForBlock(BB))
89     return GetValueAtEndOfBlock(BB);
90
91   // Otherwise, we have the hard case.  Get the live-in values for each
92   // predecessor.
93   SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
94   Value *SingularValue = nullptr;
95
96   // We can get our predecessor info by walking the pred_iterator list, but it
97   // is relatively slow.  If we already have PHI nodes in this block, walk one
98   // of them to get the predecessor list instead.
99   if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
100     for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
101       BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
102       Value *PredVal = GetValueAtEndOfBlock(PredBB);
103       PredValues.push_back(std::make_pair(PredBB, PredVal));
104
105       // Compute SingularValue.
106       if (i == 0)
107         SingularValue = PredVal;
108       else if (PredVal != SingularValue)
109         SingularValue = nullptr;
110     }
111   } else {
112     bool isFirstPred = true;
113     for (BasicBlock *PredBB : predecessors(BB)) {
114       Value *PredVal = GetValueAtEndOfBlock(PredBB);
115       PredValues.push_back(std::make_pair(PredBB, PredVal));
116
117       // Compute SingularValue.
118       if (isFirstPred) {
119         SingularValue = PredVal;
120         isFirstPred = false;
121       } else if (PredVal != SingularValue)
122         SingularValue = nullptr;
123     }
124   }
125
126   // If there are no predecessors, just return undef.
127   if (PredValues.empty())
128     return UndefValue::get(ProtoType);
129
130   // Otherwise, if all the merged values are the same, just use it.
131   if (SingularValue)
132     return SingularValue;
133
134   // Otherwise, we do need a PHI: check to see if we already have one available
135   // in this block that produces the right value.
136   if (isa<PHINode>(BB->begin())) {
137     SmallDenseMap<BasicBlock*, Value*, 8> ValueMapping(PredValues.begin(),
138                                                        PredValues.end());
139     PHINode *SomePHI;
140     for (BasicBlock::iterator It = BB->begin();
141          (SomePHI = dyn_cast<PHINode>(It)); ++It) {
142       if (IsEquivalentPHI(SomePHI, ValueMapping))
143         return SomePHI;
144     }
145   }
146
147   // Ok, we have no way out, insert a new one now.
148   PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
149                                          ProtoName, &BB->front());
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 *V = SimplifyInstruction(InsertedPHI)) {
158     InsertedPHI->eraseFromParent();
159     return V;
160   }
161
162   // Set the DebugLoc of the inserted PHI, if available.
163   DebugLoc DL;
164   if (const Instruction *I = BB->getFirstNonPHI())
165       DL = I->getDebugLoc();
166   InsertedPHI->setDebugLoc(DL);
167
168   // If the client wants to know about all new instructions, tell it.
169   if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
170
171   DEBUG(dbgs() << "  Inserted PHI: " << *InsertedPHI << "\n");
172   return InsertedPHI;
173 }
174
175 void SSAUpdater::RewriteUse(Use &U) {
176   Instruction *User = cast<Instruction>(U.getUser());
177
178   Value *V;
179   if (PHINode *UserPN = dyn_cast<PHINode>(User))
180     V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
181   else
182     V = GetValueInMiddleOfBlock(User->getParent());
183
184   // Notify that users of the existing value that it is being replaced.
185   Value *OldVal = U.get();
186   if (OldVal != V && OldVal->hasValueHandle())
187     ValueHandleBase::ValueIsRAUWd(OldVal, V);
188
189   U.set(V);
190 }
191
192 void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
193   Instruction *User = cast<Instruction>(U.getUser());
194   
195   Value *V;
196   if (PHINode *UserPN = dyn_cast<PHINode>(User))
197     V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
198   else
199     V = GetValueAtEndOfBlock(User->getParent());
200   
201   U.set(V);
202 }
203
204 namespace llvm {
205 template<>
206 class SSAUpdaterTraits<SSAUpdater> {
207 public:
208   typedef BasicBlock BlkT;
209   typedef Value *ValT;
210   typedef PHINode PhiT;
211
212   typedef succ_iterator BlkSucc_iterator;
213   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
214   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
215
216   class PHI_iterator {
217   private:
218     PHINode *PHI;
219     unsigned idx;
220
221   public:
222     explicit PHI_iterator(PHINode *P) // begin iterator
223       : PHI(P), idx(0) {}
224     PHI_iterator(PHINode *P, bool) // end iterator
225       : PHI(P), idx(PHI->getNumIncomingValues()) {}
226
227     PHI_iterator &operator++() { ++idx; return *this; } 
228     bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
229     bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
230     Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
231     BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
232   };
233
234   static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
235   static PHI_iterator PHI_end(PhiT *PHI) {
236     return PHI_iterator(PHI, true);
237   }
238
239   /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
240   /// vector, set Info->NumPreds, and allocate space in Info->Preds.
241   static void FindPredecessorBlocks(BasicBlock *BB,
242                                     SmallVectorImpl<BasicBlock*> *Preds) {
243     // We can get our predecessor info by walking the pred_iterator list,
244     // but it is relatively slow.  If we already have PHI nodes in this
245     // block, walk one of them to get the predecessor list instead.
246     if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
247       for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI)
248         Preds->push_back(SomePhi->getIncomingBlock(PI));
249     } else {
250       Preds->insert(Preds->end(), pred_begin(BB), pred_end(BB));
251     }
252   }
253
254   /// GetUndefVal - Get an undefined value of the same type as the value
255   /// being handled.
256   static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
257     return UndefValue::get(Updater->ProtoType);
258   }
259
260   /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
261   /// Reserve space for the operands but do not fill them in yet.
262   static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
263                                SSAUpdater *Updater) {
264     PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
265                                    Updater->ProtoName, &BB->front());
266     return PHI;
267   }
268
269   /// AddPHIOperand - Add the specified value as an operand of the PHI for
270   /// the specified predecessor block.
271   static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
272     PHI->addIncoming(Val, Pred);
273   }
274
275   /// InstrIsPHI - Check if an instruction is a PHI.
276   ///
277   static PHINode *InstrIsPHI(Instruction *I) {
278     return dyn_cast<PHINode>(I);
279   }
280
281   /// ValueIsPHI - Check if a value is a PHI.
282   ///
283   static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
284     return dyn_cast<PHINode>(Val);
285   }
286
287   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
288   /// operands, i.e., it was just added.
289   static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
290     PHINode *PHI = ValueIsPHI(Val, Updater);
291     if (PHI && PHI->getNumIncomingValues() == 0)
292       return PHI;
293     return nullptr;
294   }
295
296   /// GetPHIValue - For the specified PHI instruction, return the value
297   /// that it defines.
298   static Value *GetPHIValue(PHINode *PHI) {
299     return PHI;
300   }
301 };
302
303 } // End llvm namespace
304
305 /// Check to see if AvailableVals has an entry for the specified BB and if so,
306 /// return it.  If not, construct SSA form by first calculating the required
307 /// placement of PHIs and then inserting new PHIs where needed.
308 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
309   AvailableValsTy &AvailableVals = getAvailableVals(AV);
310   if (Value *V = AvailableVals[BB])
311     return V;
312
313   SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
314   return Impl.GetValue(BB);
315 }
316
317 //===----------------------------------------------------------------------===//
318 // LoadAndStorePromoter Implementation
319 //===----------------------------------------------------------------------===//
320
321 LoadAndStorePromoter::
322 LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts,
323                      SSAUpdater &S, StringRef BaseName) : SSA(S) {
324   if (Insts.empty()) return;
325   
326   Value *SomeVal;
327   if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
328     SomeVal = LI;
329   else
330     SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
331
332   if (BaseName.empty())
333     BaseName = SomeVal->getName();
334   SSA.Initialize(SomeVal->getType(), BaseName);
335 }
336
337
338 void LoadAndStorePromoter::
339 run(const SmallVectorImpl<Instruction*> &Insts) const {
340   
341   // First step: bucket up uses of the alloca by the block they occur in.
342   // This is important because we have to handle multiple defs/uses in a block
343   // ourselves: SSAUpdater is purely for cross-block references.
344   DenseMap<BasicBlock*, TinyPtrVector<Instruction*> > UsesByBlock;
345   
346   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
347     Instruction *User = Insts[i];
348     UsesByBlock[User->getParent()].push_back(User);
349   }
350   
351   // Okay, now we can iterate over all the blocks in the function with uses,
352   // processing them.  Keep track of which loads are loading a live-in value.
353   // Walk the uses in the use-list order to be determinstic.
354   SmallVector<LoadInst*, 32> LiveInLoads;
355   DenseMap<Value*, Value*> ReplacedLoads;
356   
357   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
358     Instruction *User = Insts[i];
359     BasicBlock *BB = User->getParent();
360     TinyPtrVector<Instruction*> &BlockUses = UsesByBlock[BB];
361     
362     // If this block has already been processed, ignore this repeat use.
363     if (BlockUses.empty()) continue;
364     
365     // Okay, this is the first use in the block.  If this block just has a
366     // single user in it, we can rewrite it trivially.
367     if (BlockUses.size() == 1) {
368       // If it is a store, it is a trivial def of the value in the block.
369       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
370         updateDebugInfo(SI);
371         SSA.AddAvailableValue(BB, SI->getOperand(0));
372       } else 
373         // Otherwise it is a load, queue it to rewrite as a live-in load.
374         LiveInLoads.push_back(cast<LoadInst>(User));
375       BlockUses.clear();
376       continue;
377     }
378     
379     // Otherwise, check to see if this block is all loads.
380     bool HasStore = false;
381     for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
382       if (isa<StoreInst>(BlockUses[i])) {
383         HasStore = true;
384         break;
385       }
386     }
387     
388     // If so, we can queue them all as live in loads.  We don't have an
389     // efficient way to tell which on is first in the block and don't want to
390     // scan large blocks, so just add all loads as live ins.
391     if (!HasStore) {
392       for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
393         LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
394       BlockUses.clear();
395       continue;
396     }
397     
398     // Otherwise, we have mixed loads and stores (or just a bunch of stores).
399     // Since SSAUpdater is purely for cross-block values, we need to determine
400     // the order of these instructions in the block.  If the first use in the
401     // block is a load, then it uses the live in value.  The last store defines
402     // the live out value.  We handle this by doing a linear scan of the block.
403     Value *StoredValue = nullptr;
404     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
405       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
406         // If this is a load from an unrelated pointer, ignore it.
407         if (!isInstInList(L, Insts)) continue;
408         
409         // If we haven't seen a store yet, this is a live in use, otherwise
410         // use the stored value.
411         if (StoredValue) {
412           replaceLoadWithValue(L, StoredValue);
413           L->replaceAllUsesWith(StoredValue);
414           ReplacedLoads[L] = StoredValue;
415         } else {
416           LiveInLoads.push_back(L);
417         }
418         continue;
419       }
420       
421       if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
422         // If this is a store to an unrelated pointer, ignore it.
423         if (!isInstInList(SI, Insts)) continue;
424         updateDebugInfo(SI);
425
426         // Remember that this is the active value in the block.
427         StoredValue = SI->getOperand(0);
428       }
429     }
430     
431     // The last stored value that happened is the live-out for the block.
432     assert(StoredValue && "Already checked that there is a store in block");
433     SSA.AddAvailableValue(BB, StoredValue);
434     BlockUses.clear();
435   }
436   
437   // Okay, now we rewrite all loads that use live-in values in the loop,
438   // inserting PHI nodes as necessary.
439   for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
440     LoadInst *ALoad = LiveInLoads[i];
441     Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
442     replaceLoadWithValue(ALoad, NewVal);
443
444     // Avoid assertions in unreachable code.
445     if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
446     ALoad->replaceAllUsesWith(NewVal);
447     ReplacedLoads[ALoad] = NewVal;
448   }
449   
450   // Allow the client to do stuff before we start nuking things.
451   doExtraRewritesBeforeFinalDeletion();
452   
453   // Now that everything is rewritten, delete the old instructions from the
454   // function.  They should all be dead now.
455   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
456     Instruction *User = Insts[i];
457     
458     // If this is a load that still has uses, then the load must have been added
459     // as a live value in the SSAUpdate data structure for a block (e.g. because
460     // the loaded value was stored later).  In this case, we need to recursively
461     // propagate the updates until we get to the real value.
462     if (!User->use_empty()) {
463       Value *NewVal = ReplacedLoads[User];
464       assert(NewVal && "not a replaced load?");
465       
466       // Propagate down to the ultimate replacee.  The intermediately loads
467       // could theoretically already have been deleted, so we don't want to
468       // dereference the Value*'s.
469       DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
470       while (RLI != ReplacedLoads.end()) {
471         NewVal = RLI->second;
472         RLI = ReplacedLoads.find(NewVal);
473       }
474       
475       replaceLoadWithValue(cast<LoadInst>(User), NewVal);
476       User->replaceAllUsesWith(NewVal);
477     }
478     
479     instructionDeleted(User);
480     User->eraseFromParent();
481   }
482 }
483
484 bool
485 LoadAndStorePromoter::isInstInList(Instruction *I,
486                                    const SmallVectorImpl<Instruction*> &Insts)
487                                    const {
488   return std::find(Insts.begin(), Insts.end(), I) != Insts.end();
489 }