Mem2Reg does not need TargetData.
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file promote memory references to be register references.  It promotes
11 // alloca instructions which only have loads and stores as uses.  An alloca is
12 // transformed by using dominator frontiers to place PHI nodes, then traversing
13 // the function in depth-first order to rewrite loads and stores as appropriate.
14 // This is just the standard SSA construction algorithm to construct "pruned"
15 // SSA form.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Compiler.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 // Provide DenseMapKeyInfo for all pointers.
36 namespace llvm {
37 template<>
38 struct DenseMapKeyInfo<std::pair<BasicBlock*, unsigned> > {
39   static inline std::pair<BasicBlock*, unsigned> getEmptyKey() {
40     return std::make_pair((BasicBlock*)-1, ~0U);
41   }
42   static inline std::pair<BasicBlock*, unsigned> getTombstoneKey() {
43     return std::make_pair((BasicBlock*)-2, 0U);
44   }
45   static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
46     return DenseMapKeyInfo<void*>::getHashValue(Val.first) + Val.second*2;
47   }
48   static bool isPod() { return true; }
49 };
50 }
51
52 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
53 /// This is true if there are only loads and stores to the alloca.
54 ///
55 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
56   // FIXME: If the memory unit is of pointer or integer type, we can permit
57   // assignments to subsections of the memory unit.
58
59   // Only allow direct loads and stores...
60   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
61        UI != UE; ++UI)     // Loop over all of the uses of the alloca
62     if (isa<LoadInst>(*UI)) {
63       // noop
64     } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
65       if (SI->getOperand(0) == AI)
66         return false;   // Don't allow a store OF the AI, only INTO the AI.
67     } else {
68       return false;   // Not a load or store.
69     }
70
71   return true;
72 }
73
74 namespace {
75
76   // Data package used by RenamePass()
77   class VISIBILITY_HIDDEN RenamePassData {
78   public:
79     RenamePassData(BasicBlock *B, BasicBlock *P,
80                    const std::vector<Value *> &V) : BB(B), Pred(P), Values(V) {}
81     BasicBlock *BB;
82     BasicBlock *Pred;
83     std::vector<Value *> Values;
84   };
85
86   struct VISIBILITY_HIDDEN PromoteMem2Reg {
87     /// Allocas - The alloca instructions being promoted.
88     ///
89     std::vector<AllocaInst*> Allocas;
90     SmallVector<AllocaInst*, 16> &RetryList;
91     ETForest &ET;
92     DominanceFrontier &DF;
93
94     /// AST - An AliasSetTracker object to update.  If null, don't update it.
95     ///
96     AliasSetTracker *AST;
97
98     /// AllocaLookup - Reverse mapping of Allocas.
99     ///
100     std::map<AllocaInst*, unsigned>  AllocaLookup;
101
102     /// NewPhiNodes - The PhiNodes we're adding.
103     ///
104     DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
105     
106     /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
107     /// it corresponds to.
108     DenseMap<PHINode*, unsigned> PhiToAllocaMap;
109     
110     /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
111     /// each alloca that is of pointer type, we keep track of what to copyValue
112     /// to the inserted PHI nodes here.
113     ///
114     std::vector<Value*> PointerAllocaValues;
115
116     /// Visited - The set of basic blocks the renamer has already visited.
117     ///
118     SmallPtrSet<BasicBlock*, 16> Visited;
119
120     /// BBNumbers - Contains a stable numbering of basic blocks to avoid
121     /// non-determinstic behavior.
122     DenseMap<BasicBlock*, unsigned> BBNumbers;
123
124     /// RenamePassWorkList - Worklist used by RenamePass()
125     std::vector<RenamePassData> RenamePassWorkList;
126
127   public:
128     PromoteMem2Reg(const std::vector<AllocaInst*> &A,
129                    SmallVector<AllocaInst*, 16> &Retry, ETForest &et,
130                    DominanceFrontier &df, AliasSetTracker *ast)
131       : Allocas(A), RetryList(Retry), ET(et), DF(df), AST(ast) {}
132
133     void run();
134
135     /// properlyDominates - Return true if I1 properly dominates I2.
136     ///
137     bool properlyDominates(Instruction *I1, Instruction *I2) const {
138       if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
139         I1 = II->getNormalDest()->begin();
140       return ET.properlyDominates(I1->getParent(), I2->getParent());
141     }
142     
143     /// dominates - Return true if BB1 dominates BB2 using the ETForest.
144     ///
145     bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
146       return ET.dominates(BB1, BB2);
147     }
148
149   private:
150     void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
151                                SmallPtrSet<PHINode*, 16> &DeadPHINodes);
152     bool PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
153     void PromoteLocallyUsedAllocas(BasicBlock *BB,
154                                    const std::vector<AllocaInst*> &AIs);
155
156     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
157                     std::vector<Value*> &IncVals);
158     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
159                       SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
160   };
161
162 }  // end of anonymous namespace
163
164 void PromoteMem2Reg::run() {
165   Function &F = *DF.getRoot()->getParent();
166
167   // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
168   // only used in a single basic block.  These instructions can be efficiently
169   // promoted by performing a single linear scan over that one block.  Since
170   // individual basic blocks are sometimes large, we group together all allocas
171   // that are live in a single basic block by the basic block they are live in.
172   std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
173
174   if (AST) PointerAllocaValues.resize(Allocas.size());
175
176   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
177     AllocaInst *AI = Allocas[AllocaNum];
178
179     assert(isAllocaPromotable(AI) &&
180            "Cannot promote non-promotable alloca!");
181     assert(AI->getParent()->getParent() == &F &&
182            "All allocas should be in the same function, which is same as DF!");
183
184     if (AI->use_empty()) {
185       // If there are no uses of the alloca, just delete it now.
186       if (AST) AST->deleteValue(AI);
187       AI->eraseFromParent();
188
189       // Remove the alloca from the Allocas list, since it has been processed
190       Allocas[AllocaNum] = Allocas.back();
191       Allocas.pop_back();
192       --AllocaNum;
193       continue;
194     }
195
196     // Calculate the set of read and write-locations for each alloca.  This is
197     // analogous to finding the 'uses' and 'definitions' of each variable.
198     std::vector<BasicBlock*> DefiningBlocks;
199     std::vector<BasicBlock*> UsingBlocks;
200
201     StoreInst  *OnlyStore = 0;
202     BasicBlock *OnlyBlock = 0;
203     bool OnlyUsedInOneBlock = true;
204
205     // As we scan the uses of the alloca instruction, keep track of stores, and
206     // decide whether all of the loads and stores to the alloca are within the
207     // same basic block.
208     Value *AllocaPointerVal = 0;
209     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
210       Instruction *User = cast<Instruction>(*U);
211       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
212         // Remember the basic blocks which define new values for the alloca
213         DefiningBlocks.push_back(SI->getParent());
214         AllocaPointerVal = SI->getOperand(0);
215         OnlyStore = SI;
216       } else {
217         LoadInst *LI = cast<LoadInst>(User);
218         // Otherwise it must be a load instruction, keep track of variable reads
219         UsingBlocks.push_back(LI->getParent());
220         AllocaPointerVal = LI;
221       }
222
223       if (OnlyUsedInOneBlock) {
224         if (OnlyBlock == 0)
225           OnlyBlock = User->getParent();
226         else if (OnlyBlock != User->getParent())
227           OnlyUsedInOneBlock = false;
228       }
229     }
230
231     // If the alloca is only read and written in one basic block, just perform a
232     // linear sweep over the block to eliminate it.
233     if (OnlyUsedInOneBlock) {
234       LocallyUsedAllocas[OnlyBlock].push_back(AI);
235
236       // Remove the alloca from the Allocas list, since it will be processed.
237       Allocas[AllocaNum] = Allocas.back();
238       Allocas.pop_back();
239       --AllocaNum;
240       continue;
241     }
242
243     // If there is only a single store to this value, replace any loads of
244     // it that are directly dominated by the definition with the value stored.
245     if (DefiningBlocks.size() == 1) {
246       // Be aware of loads before the store.
247       std::set<BasicBlock*> ProcessedBlocks;
248       for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
249         // If the store dominates the block and if we haven't processed it yet,
250         // do so now.
251         if (dominates(OnlyStore->getParent(), UsingBlocks[i]))
252           if (ProcessedBlocks.insert(UsingBlocks[i]).second) {
253             BasicBlock *UseBlock = UsingBlocks[i];
254             
255             // If the use and store are in the same block, do a quick scan to
256             // verify that there are no uses before the store.
257             if (UseBlock == OnlyStore->getParent()) {
258               BasicBlock::iterator I = UseBlock->begin();
259               for (; &*I != OnlyStore; ++I) { // scan block for store.
260                 if (isa<LoadInst>(I) && I->getOperand(0) == AI)
261                   break;
262               }
263               if (&*I != OnlyStore) break;  // Do not handle this case.
264             }
265         
266             // Otherwise, if this is a different block or if all uses happen
267             // after the store, do a simple linear scan to replace loads with
268             // the stored value.
269             for (BasicBlock::iterator I = UseBlock->begin(),E = UseBlock->end();
270                  I != E; ) {
271               if (LoadInst *LI = dyn_cast<LoadInst>(I++)) {
272                 if (LI->getOperand(0) == AI) {
273                   LI->replaceAllUsesWith(OnlyStore->getOperand(0));
274                   if (AST && isa<PointerType>(LI->getType()))
275                     AST->deleteValue(LI);
276                   LI->eraseFromParent();
277                 }
278               }
279             }
280             
281             // Finally, remove this block from the UsingBlock set.
282             UsingBlocks[i] = UsingBlocks.back();
283             --i; --e;
284           }
285
286       // Finally, after the scan, check to see if the store is all that is left.
287       if (UsingBlocks.empty()) {
288         // The alloca has been processed, move on.
289         Allocas[AllocaNum] = Allocas.back();
290         Allocas.pop_back();
291         --AllocaNum;
292         continue;
293       }
294     }
295     
296     
297     if (AST)
298       PointerAllocaValues[AllocaNum] = AllocaPointerVal;
299
300     // If we haven't computed a numbering for the BB's in the function, do so
301     // now.
302     if (BBNumbers.empty()) {
303       unsigned ID = 0;
304       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
305         BBNumbers[I] = ID++;
306     }
307
308     // Compute the locations where PhiNodes need to be inserted.  Look at the
309     // dominance frontier of EACH basic-block we have a write in.
310     //
311     unsigned CurrentVersion = 0;
312     SmallPtrSet<PHINode*, 16> InsertedPHINodes;
313     std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
314     while (!DefiningBlocks.empty()) {
315       BasicBlock *BB = DefiningBlocks.back();
316       DefiningBlocks.pop_back();
317
318       // Look up the DF for this write, add it to PhiNodes
319       DominanceFrontier::const_iterator it = DF.find(BB);
320       if (it != DF.end()) {
321         const DominanceFrontier::DomSetType &S = it->second;
322
323         // In theory we don't need the indirection through the DFBlocks vector.
324         // In practice, the order of calling QueuePhiNode would depend on the
325         // (unspecified) ordering of basic blocks in the dominance frontier,
326         // which would give PHI nodes non-determinstic subscripts.  Fix this by
327         // processing blocks in order of the occurance in the function.
328         for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
329              PE = S.end(); P != PE; ++P)
330           DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
331
332         // Sort by which the block ordering in the function.
333         std::sort(DFBlocks.begin(), DFBlocks.end());
334
335         for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
336           BasicBlock *BB = DFBlocks[i].second;
337           if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
338             DefiningBlocks.push_back(BB);
339         }
340         DFBlocks.clear();
341       }
342     }
343
344     // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
345     // of the writes to the variable, scan through the reads of the variable,
346     // marking PHI nodes which are actually necessary as alive (by removing them
347     // from the InsertedPHINodes set).  This is not perfect: there may PHI
348     // marked alive because of loads which are dominated by stores, but there
349     // will be no unmarked PHI nodes which are actually used.
350     //
351     for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
352       MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
353     UsingBlocks.clear();
354
355     // If there are any PHI nodes which are now known to be dead, remove them!
356     for (SmallPtrSet<PHINode*, 16>::iterator I = InsertedPHINodes.begin(),
357            E = InsertedPHINodes.end(); I != E; ++I) {
358       PHINode *PN = *I;
359       bool Erased=NewPhiNodes.erase(std::make_pair(PN->getParent(), AllocaNum));
360       Erased=Erased;
361       assert(Erased && "PHI already removed?");
362       
363       if (AST && isa<PointerType>(PN->getType()))
364         AST->deleteValue(PN);
365       PN->eraseFromParent();
366       PhiToAllocaMap.erase(PN);
367     }
368
369     // Keep the reverse mapping of the 'Allocas' array.
370     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
371   }
372
373   // Process all allocas which are only used in a single basic block.
374   for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
375          LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
376     const std::vector<AllocaInst*> &LocAllocas = I->second;
377     assert(!LocAllocas.empty() && "empty alloca list??");
378
379     // It's common for there to only be one alloca in the list.  Handle it
380     // efficiently.
381     if (LocAllocas.size() == 1) {
382       // If we can do the quick promotion pass, do so now.
383       if (PromoteLocallyUsedAlloca(I->first, LocAllocas[0]))
384         RetryList.push_back(LocAllocas[0]);  // Failed, retry later.
385     } else {
386       // Locally promote anything possible.  Note that if this is unable to
387       // promote a particular alloca, it puts the alloca onto the Allocas vector
388       // for global processing.
389       PromoteLocallyUsedAllocas(I->first, LocAllocas);
390     }
391   }
392
393   if (Allocas.empty())
394     return; // All of the allocas must have been trivial!
395
396   // Set the incoming values for the basic block to be null values for all of
397   // the alloca's.  We do this in case there is a load of a value that has not
398   // been stored yet.  In this case, it will get this null value.
399   //
400   std::vector<Value *> Values(Allocas.size());
401   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
402     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
403
404   // Walks all basic blocks in the function performing the SSA rename algorithm
405   // and inserting the phi nodes we marked as necessary
406   //
407   RenamePassWorkList.clear();
408   RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
409   while(!RenamePassWorkList.empty()) {
410     RenamePassData RPD = RenamePassWorkList.back(); 
411     RenamePassWorkList.pop_back();
412     // RenamePass may add new worklist entries.
413     RenamePass(RPD.BB, RPD.Pred, RPD.Values);
414   }
415   
416   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
417   Visited.clear();
418
419   // Remove the allocas themselves from the function.
420   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
421     Instruction *A = Allocas[i];
422
423     // If there are any uses of the alloca instructions left, they must be in
424     // sections of dead code that were not processed on the dominance frontier.
425     // Just delete the users now.
426     //
427     if (!A->use_empty())
428       A->replaceAllUsesWith(UndefValue::get(A->getType()));
429     if (AST) AST->deleteValue(A);
430     A->eraseFromParent();
431   }
432
433   
434   // Loop over all of the PHI nodes and see if there are any that we can get
435   // rid of because they merge all of the same incoming values.  This can
436   // happen due to undef values coming into the PHI nodes.  This process is
437   // iterative, because eliminating one PHI node can cause others to be removed.
438   bool EliminatedAPHI = true;
439   while (EliminatedAPHI) {
440     EliminatedAPHI = false;
441     
442     for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
443            NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
444       PHINode *PN = I->second;
445       
446       // If this PHI node merges one value and/or undefs, get the value.
447       if (Value *V = PN->hasConstantValue(true)) {
448         if (!isa<Instruction>(V) ||
449             properlyDominates(cast<Instruction>(V), PN)) {
450           if (AST && isa<PointerType>(PN->getType()))
451             AST->deleteValue(PN);
452           PN->replaceAllUsesWith(V);
453           PN->eraseFromParent();
454           NewPhiNodes.erase(I++);
455           EliminatedAPHI = true;
456           continue;
457         }
458       }
459       ++I;
460     }
461   }
462   
463   // At this point, the renamer has added entries to PHI nodes for all reachable
464   // code.  Unfortunately, there may be unreachable blocks which the renamer
465   // hasn't traversed.  If this is the case, the PHI nodes may not
466   // have incoming values for all predecessors.  Loop over all PHI nodes we have
467   // created, inserting undef values if they are missing any incoming values.
468   //
469   for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
470          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
471     // We want to do this once per basic block.  As such, only process a block
472     // when we find the PHI that is the first entry in the block.
473     PHINode *SomePHI = I->second;
474     BasicBlock *BB = SomePHI->getParent();
475     if (&BB->front() != SomePHI)
476       continue;
477
478     // Count the number of preds for BB.
479     SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
480
481     // Only do work here if there the PHI nodes are missing incoming values.  We
482     // know that all PHI nodes that were inserted in a block will have the same
483     // number of incoming values, so we can just check any of them.
484     if (SomePHI->getNumIncomingValues() == Preds.size())
485       continue;
486     
487     // Ok, now we know that all of the PHI nodes are missing entries for some
488     // basic blocks.  Start by sorting the incoming predecessors for efficient
489     // access.
490     std::sort(Preds.begin(), Preds.end());
491     
492     // Now we loop through all BB's which have entries in SomePHI and remove
493     // them from the Preds list.
494     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
495       // Do a log(n) search of the Preds list for the entry we want.
496       SmallVector<BasicBlock*, 16>::iterator EntIt =
497         std::lower_bound(Preds.begin(), Preds.end(),
498                          SomePHI->getIncomingBlock(i));
499       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
500              "PHI node has entry for a block which is not a predecessor!");
501
502       // Remove the entry
503       Preds.erase(EntIt);
504     }
505
506     // At this point, the blocks left in the preds list must have dummy
507     // entries inserted into every PHI nodes for the block.  Update all the phi
508     // nodes in this block that we are inserting (there could be phis before
509     // mem2reg runs).
510     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
511     BasicBlock::iterator BBI = BB->begin();
512     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
513            SomePHI->getNumIncomingValues() == NumBadPreds) {
514       Value *UndefVal = UndefValue::get(SomePHI->getType());
515       for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
516         SomePHI->addIncoming(UndefVal, Preds[pred]);
517     }
518   }
519         
520   NewPhiNodes.clear();
521 }
522
523 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
524 // "minimal" SSA form.  To do this, it inserts all of the PHI nodes on the IDF
525 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
526 // each read of the variable.  For each block that reads the variable, this
527 // function is called, which removes used PHI nodes from the DeadPHINodes set.
528 // After all of the reads have been processed, any PHI nodes left in the
529 // DeadPHINodes set are removed.
530 //
531 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
532                                       SmallPtrSet<PHINode*, 16> &DeadPHINodes) {
533   // Scan the immediate dominators of this block looking for a block which has a
534   // PHI node for Alloca num.  If we find it, mark the PHI node as being alive!
535   for (BasicBlock* DomBB = BB; DomBB; DomBB = ET.getIDom(DomBB)) {
536     DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator
537       I = NewPhiNodes.find(std::make_pair(DomBB, AllocaNum));
538     if (I != NewPhiNodes.end()) {
539       // Ok, we found an inserted PHI node which dominates this value.
540       PHINode *DominatingPHI = I->second;
541
542       // Find out if we previously thought it was dead.  If so, mark it as being
543       // live by removing it from the DeadPHINodes set.
544       if (DeadPHINodes.erase(DominatingPHI)) {
545         // Now that we have marked the PHI node alive, also mark any PHI nodes
546         // which it might use as being alive as well.
547         for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
548              PI != PE; ++PI)
549           MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
550       }
551     }
552   }
553 }
554
555 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
556 /// block.  If this is the case, avoid traversing the CFG and inserting a lot of
557 /// potentially useless PHI nodes by just performing a single linear pass over
558 /// the basic block using the Alloca.
559 ///
560 /// If we cannot promote this alloca (because it is read before it is written),
561 /// return true.  This is necessary in cases where, due to control flow, the
562 /// alloca is potentially undefined on some control flow paths.  e.g. code like
563 /// this is potentially correct:
564 ///
565 ///   for (...) { if (c) { A = undef; undef = B; } }
566 ///
567 /// ... so long as A is not used before undef is set.
568 ///
569 bool PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
570   assert(!AI->use_empty() && "There are no uses of the alloca!");
571
572   // Handle degenerate cases quickly.
573   if (AI->hasOneUse()) {
574     Instruction *U = cast<Instruction>(AI->use_back());
575     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
576       // Must be a load of uninitialized value.
577       LI->replaceAllUsesWith(UndefValue::get(AI->getAllocatedType()));
578       if (AST && isa<PointerType>(LI->getType()))
579         AST->deleteValue(LI);
580     } else {
581       // Otherwise it must be a store which is never read.
582       assert(isa<StoreInst>(U));
583     }
584     BB->getInstList().erase(U);
585   } else {
586     // Uses of the uninitialized memory location shall get undef.
587     Value *CurVal = 0;
588
589     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
590       Instruction *Inst = I++;
591       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
592         if (LI->getOperand(0) == AI) {
593           if (!CurVal) return true;  // Could not locally promote!
594
595           // Loads just returns the "current value"...
596           LI->replaceAllUsesWith(CurVal);
597           if (AST && isa<PointerType>(LI->getType()))
598             AST->deleteValue(LI);
599           BB->getInstList().erase(LI);
600         }
601       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
602         if (SI->getOperand(1) == AI) {
603           // Store updates the "current value"...
604           CurVal = SI->getOperand(0);
605           BB->getInstList().erase(SI);
606         }
607       }
608     }
609   }
610
611   // After traversing the basic block, there should be no more uses of the
612   // alloca, remove it now.
613   assert(AI->use_empty() && "Uses of alloca from more than one BB??");
614   if (AST) AST->deleteValue(AI);
615   AI->getParent()->getInstList().erase(AI);
616   return false;
617 }
618
619 /// PromoteLocallyUsedAllocas - This method is just like
620 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
621 /// instructions in parallel.  This is important in cases where we have large
622 /// basic blocks, as we don't want to rescan the entire basic block for each
623 /// alloca which is locally used in it (which might be a lot).
624 void PromoteMem2Reg::
625 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
626   std::map<AllocaInst*, Value*> CurValues;
627   for (unsigned i = 0, e = AIs.size(); i != e; ++i)
628     CurValues[AIs[i]] = 0; // Insert with null value
629
630   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
631     Instruction *Inst = I++;
632     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
633       // Is this a load of an alloca we are tracking?
634       if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
635         std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
636         if (AIt != CurValues.end()) {
637           // If loading an uninitialized value, allow the inter-block case to
638           // handle it.  Due to control flow, this might actually be ok.
639           if (AIt->second == 0) {  // Use of locally uninitialized value??
640             RetryList.push_back(AI);   // Retry elsewhere.
641             CurValues.erase(AIt);   // Stop tracking this here.
642             if (CurValues.empty()) return;
643           } else {
644             // Loads just returns the "current value"...
645             LI->replaceAllUsesWith(AIt->second);
646             if (AST && isa<PointerType>(LI->getType()))
647               AST->deleteValue(LI);
648             BB->getInstList().erase(LI);
649           }
650         }
651       }
652     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
653       if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
654         std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
655         if (AIt != CurValues.end()) {
656           // Store updates the "current value"...
657           AIt->second = SI->getOperand(0);
658           BB->getInstList().erase(SI);
659         }
660       }
661     }
662   }
663 }
664
665
666
667 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
668 // Alloca returns true if there wasn't already a phi-node for that variable
669 //
670 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
671                                   unsigned &Version,
672                                   SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
673   // Look up the basic-block in question.
674   PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
675
676   // If the BB already has a phi node added for the i'th alloca then we're done!
677   if (PN) return false;
678
679   // Create a PhiNode using the dereferenced type... and add the phi-node to the
680   // BasicBlock.
681   PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
682                    Allocas[AllocaNo]->getName() + "." +
683                    utostr(Version++), BB->begin());
684   PhiToAllocaMap[PN] = AllocaNo;
685   
686   InsertedPHINodes.insert(PN);
687
688   if (AST && isa<PointerType>(PN->getType()))
689     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
690
691   return true;
692 }
693
694
695 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
696 // stores to the allocas which we are promoting.  IncomingVals indicates what
697 // value each Alloca contains on exit from the predecessor block Pred.
698 //
699 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
700                                 std::vector<Value*> &IncomingVals) {
701   // If we are inserting any phi nodes into this BB, they will already be in the
702   // block.
703   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
704     // Pred may have multiple edges to BB.  If so, we want to add N incoming
705     // values to each PHI we are inserting on the first time we see the edge.
706     // Check to see if APN already has incoming values from Pred.  This also
707     // prevents us from modifying PHI nodes that are not currently being
708     // inserted.
709     bool HasPredEntries = false;
710     for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
711       if (APN->getIncomingBlock(i) == Pred) {
712         HasPredEntries = true;
713         break;
714       }
715     }
716     
717     // If we have PHI nodes to update, compute the number of edges from Pred to
718     // BB.
719     if (!HasPredEntries) {
720       TerminatorInst *PredTerm = Pred->getTerminator();
721       unsigned NumEdges = 0;
722       for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
723         if (PredTerm->getSuccessor(i) == BB)
724           ++NumEdges;
725       }
726       assert(NumEdges && "Must be at least one edge from Pred to BB!");
727       
728       // Add entries for all the phis.
729       BasicBlock::iterator PNI = BB->begin();
730       do {
731         unsigned AllocaNo = PhiToAllocaMap[APN];
732         
733         // Add N incoming values to the PHI node.
734         for (unsigned i = 0; i != NumEdges; ++i)
735           APN->addIncoming(IncomingVals[AllocaNo], Pred);
736         
737         // The currently active variable for this block is now the PHI.
738         IncomingVals[AllocaNo] = APN;
739         
740         // Get the next phi node.
741         ++PNI;
742         APN = dyn_cast<PHINode>(PNI);
743         if (APN == 0) break;
744         
745         // Verify it doesn't already have entries for Pred.  If it does, it is
746         // not being inserted by this mem2reg invocation.
747         HasPredEntries = false;
748         for (unsigned i = 0, e = APN->getNumIncomingValues(); i != e; ++i) {
749           if (APN->getIncomingBlock(i) == Pred) {
750             HasPredEntries = true;
751             break;
752           }
753         }
754       } while (!HasPredEntries);
755     }
756   }
757   
758   // Don't revisit blocks.
759   if (!Visited.insert(BB)) return;
760
761   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
762     Instruction *I = II++; // get the instruction, increment iterator
763
764     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
765       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
766         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
767         if (AI != AllocaLookup.end()) {
768           Value *V = IncomingVals[AI->second];
769
770           // walk the use list of this load and replace all uses with r
771           LI->replaceAllUsesWith(V);
772           if (AST && isa<PointerType>(LI->getType()))
773             AST->deleteValue(LI);
774           BB->getInstList().erase(LI);
775         }
776       }
777     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
778       // Delete this instruction and mark the name as the current holder of the
779       // value
780       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
781         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
782         if (ai != AllocaLookup.end()) {
783           // what value were we writing?
784           IncomingVals[ai->second] = SI->getOperand(0);
785           BB->getInstList().erase(SI);
786         }
787       }
788     }
789   }
790
791   // Recurse to our successors.
792   TerminatorInst *TI = BB->getTerminator();
793   for (unsigned i = 0; i != TI->getNumSuccessors(); i++)
794     RenamePassWorkList.push_back(RenamePassData(TI->getSuccessor(i), BB, IncomingVals));
795 }
796
797 /// PromoteMemToReg - Promote the specified list of alloca instructions into
798 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
799 /// use of DominanceFrontier information.  This function does not modify the CFG
800 /// of the function at all.  All allocas must be from the same function.
801 ///
802 /// If AST is specified, the specified tracker is updated to reflect changes
803 /// made to the IR.
804 ///
805 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
806                            ETForest &ET, DominanceFrontier &DF,
807                            AliasSetTracker *AST) {
808   // If there is nothing to do, bail out...
809   if (Allocas.empty()) return;
810
811   SmallVector<AllocaInst*, 16> RetryList;
812   PromoteMem2Reg(Allocas, RetryList, ET, DF, AST).run();
813
814   // PromoteMem2Reg may not have been able to promote all of the allocas in one
815   // pass, run it again if needed.
816   std::vector<AllocaInst*> NewAllocas;
817   while (!RetryList.empty()) {
818     // If we need to retry some allocas, this is due to there being no store
819     // before a read in a local block.  To counteract this, insert a store of
820     // undef into the alloca right after the alloca itself.
821     for (unsigned i = 0, e = RetryList.size(); i != e; ++i) {
822       BasicBlock::iterator BBI = RetryList[i];
823
824       new StoreInst(UndefValue::get(RetryList[i]->getAllocatedType()),
825                     RetryList[i], ++BBI);
826     }
827
828     NewAllocas.assign(RetryList.begin(), RetryList.end());
829     RetryList.clear();
830     PromoteMem2Reg(NewAllocas, RetryList, ET, DF, AST).run();
831     NewAllocas.clear();
832   }
833 }