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