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