1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file promote memory references to be register references. It promotes
11 // alloca instructions which only have loads and stores as uses (or that have
12 // PHI nodes which are only loaded from). An alloca is transformed by using
13 // dominator frontiers to place PHI nodes, then traversing the function in
14 // depth-first order to rewrite loads and stores as appropriate. This is just
15 // the standard SSA construction algorithm to construct "pruned" SSA form.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Constant.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"
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... of if there
34 /// is a PHI node using the address which can be trivially transformed.
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.
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)) {
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 if (const PHINode *PN = dyn_cast<PHINode>(*UI)) {
49 // We only support PHI nodes in a few simple cases. The PHI node is only
50 // allowed to have one use, which must be a load instruction, and can only
51 // use alloca instructions (no random pointers). Also, there cannot be
52 // any accesses to AI between the PHI node and the use of the PHI.
53 if (!PN->hasOneUse()) return false;
55 // Our transformation causes the unconditional loading of all pointer
56 // operands to the PHI node. Because this could cause a fault if there is
57 // a critical edge in the CFG and if one of the pointers is illegal, we
58 // refuse to promote PHI nodes unless they are obviously safe. For now,
59 // obviously safe means that all of the operands are allocas.
61 // If we wanted to extend this code to break critical edges, this
62 // restriction could be relaxed, and we could even handle uses of the PHI
63 // node that are volatile loads or stores.
65 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
66 if (!isa<AllocaInst>(PN->getIncomingValue(i)))
69 // Now make sure the one user instruction is in the same basic block as
70 // the PHI, and that there are no loads or stores between the PHI node and
72 BasicBlock::const_iterator UI = cast<Instruction>(PN->use_back());
73 if (!isa<LoadInst>(UI) || cast<LoadInst>(UI)->isVolatile()) return false;
75 // Scan looking for memory accesses.
76 // FIXME: this should REALLY use alias analysis.
77 for (--UI; !isa<PHINode>(UI); --UI)
78 if (isa<LoadInst>(UI) || isa<StoreInst>(UI) || isa<CallInst>(UI))
81 // If we got this far, we can promote the PHI use.
82 } else if (const SelectInst *SI = dyn_cast<SelectInst>(*UI)) {
83 // We only support selects in a few simple cases. The select is only
84 // allowed to have one use, which must be a load instruction, and can only
85 // use alloca instructions (no random pointers). Also, there cannot be
86 // any accesses to AI between the PHI node and the use of the PHI.
87 if (!SI->hasOneUse()) return false;
89 // Our transformation causes the unconditional loading of all pointer
90 // operands of the select. Because this could cause a fault if there is a
91 // critical edge in the CFG and if one of the pointers is illegal, we
92 // refuse to promote the select unless it is obviously safe. For now,
93 // obviously safe means that all of the operands are allocas.
95 if (!isa<AllocaInst>(SI->getOperand(1)) ||
96 !isa<AllocaInst>(SI->getOperand(2)))
99 // Now make sure the one user instruction is in the same basic block as
100 // the PHI, and that there are no loads or stores between the PHI node and
102 BasicBlock::const_iterator UI = cast<Instruction>(SI->use_back());
103 if (!isa<LoadInst>(UI) || cast<LoadInst>(UI)->isVolatile()) return false;
105 // Scan looking for memory accesses.
106 // FIXME: this should REALLY use alias analysis.
107 for (--UI; &*UI != SI; --UI)
108 if (isa<LoadInst>(UI) || isa<StoreInst>(UI) || isa<CallInst>(UI))
111 // If we got this far, we can promote the select use.
113 return false; // Not a load, store, or promotable PHI?
120 struct PromoteMem2Reg {
121 /// Allocas - The alloca instructions being promoted.
123 std::vector<AllocaInst*> Allocas;
125 DominanceFrontier &DF;
126 const TargetData &TD;
128 /// AST - An AliasSetTracker object to update. If null, don't update it.
130 AliasSetTracker *AST;
132 /// AllocaLookup - Reverse mapping of Allocas.
134 std::map<AllocaInst*, unsigned> AllocaLookup;
136 /// NewPhiNodes - The PhiNodes we're adding.
138 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
140 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
141 /// each alloca that is of pointer type, we keep track of what to copyValue
142 /// to the inserted PHI nodes here.
144 std::vector<Value*> PointerAllocaValues;
146 /// Visited - The set of basic blocks the renamer has already visited.
148 std::set<BasicBlock*> Visited;
150 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
151 /// non-determinstic behavior.
152 StableBasicBlockNumbering BBNumbers;
155 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
156 DominanceFrontier &df, const TargetData &td,
157 AliasSetTracker *ast)
158 : Allocas(A), DT(dt), DF(df), TD(td), AST(ast) {}
163 void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
164 std::set<PHINode*> &DeadPHINodes);
165 void PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
166 void PromoteLocallyUsedAllocas(BasicBlock *BB,
167 const std::vector<AllocaInst*> &AIs);
169 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
170 std::vector<Value*> &IncVals);
171 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
172 std::set<PHINode*> &InsertedPHINodes);
174 } // end of anonymous namespace
176 void PromoteMem2Reg::run() {
177 Function &F = *DF.getRoot()->getParent();
179 // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
180 // only used in a single basic block. These instructions can be efficiently
181 // promoted by performing a single linear scan over that one block. Since
182 // individual basic blocks are sometimes large, we group together all allocas
183 // that are live in a single basic block by the basic block they are live in.
184 std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
186 if (AST) PointerAllocaValues.resize(Allocas.size());
188 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
189 AllocaInst *AI = Allocas[AllocaNum];
191 assert(isAllocaPromotable(AI, TD) &&
192 "Cannot promote non-promotable alloca!");
193 assert(AI->getParent()->getParent() == &F &&
194 "All allocas should be in the same function, which is same as DF!");
196 if (AI->use_empty()) {
197 // If there are no uses of the alloca, just delete it now.
198 if (AST) AST->deleteValue(AI);
199 AI->getParent()->getInstList().erase(AI);
201 // Remove the alloca from the Allocas list, since it has been processed
202 Allocas[AllocaNum] = Allocas.back();
208 // Calculate the set of read and write-locations for each alloca. This is
209 // analogous to finding the 'uses' and 'definitions' of each variable.
210 std::vector<BasicBlock*> DefiningBlocks;
211 std::vector<BasicBlock*> UsingBlocks;
213 BasicBlock *OnlyBlock = 0;
214 bool OnlyUsedInOneBlock = true;
216 // As we scan the uses of the alloca instruction, keep track of stores, and
217 // decide whether all of the loads and stores to the alloca are within the
220 Value *AllocaPointerVal = 0;
221 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
222 Instruction *User = cast<Instruction>(*U);
223 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
224 // Remember the basic blocks which define new values for the alloca
225 DefiningBlocks.push_back(SI->getParent());
226 AllocaPointerVal = SI->getOperand(0);
227 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
228 // Otherwise it must be a load instruction, keep track of variable reads
229 UsingBlocks.push_back(LI->getParent());
230 AllocaPointerVal = LI;
231 } else if (SelectInst *SI = dyn_cast<SelectInst>(User)) {
232 // Because of the restrictions we placed on Select instruction uses
233 // above things are very simple. Transform the select of addresses into
234 // a select of loaded values.
235 LoadInst *Load = cast<LoadInst>(SI->use_back());
236 std::string LoadName = Load->getName(); Load->setName("");
238 Value *TrueVal = new LoadInst(SI->getOperand(1),
239 SI->getOperand(1)->getName()+".val", SI);
240 Value *FalseVal = new LoadInst(SI->getOperand(2),
241 SI->getOperand(2)->getName()+".val", SI);
243 Value *NewSI = new SelectInst(SI->getOperand(0), TrueVal,
244 FalseVal, Load->getName(), SI);
245 if (AST && isa<PointerType>(Load->getType())) {
246 AST->copyValue(Load, TrueVal);
247 AST->copyValue(Load, FalseVal);
248 AST->copyValue(Load, NewSI);
249 AST->deleteValue(Load);
252 Load->replaceAllUsesWith(NewSI);
253 Load->getParent()->getInstList().erase(Load);
254 SI->getParent()->getInstList().erase(SI);
256 // Restart our scan of uses...
257 DefiningBlocks.clear();
261 // Because of the restrictions we placed on PHI node uses above, the PHI
262 // node reads the block in any using predecessors. Transform the PHI of
263 // addresses into a PHI of loaded values.
264 PHINode *PN = cast<PHINode>(User);
265 assert(PN->hasOneUse() && "Cannot handle PHI Node with != 1 use!");
266 LoadInst *PNUser = cast<LoadInst>(PN->use_back());
267 std::string PNUserName = PNUser->getName(); PNUser->setName("");
269 // Create the new PHI node and insert load instructions as appropriate.
270 PHINode *NewPN = new PHINode(AI->getAllocatedType(), PNUserName, PN);
271 std::map<BasicBlock*, LoadInst*> NewLoads;
272 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
273 BasicBlock *Pred = PN->getIncomingBlock(i);
274 LoadInst *&NewLoad = NewLoads[Pred];
275 if (NewLoad == 0) // Insert the new load in the predecessor
276 NewLoad = new LoadInst(PN->getIncomingValue(i),
277 PN->getIncomingValue(i)->getName()+".val",
278 Pred->getTerminator());
279 NewPN->addIncoming(NewLoad, Pred);
282 if (AST && isa<PointerType>(NewPN->getType())) {
283 for (std::map<BasicBlock*, LoadInst*>::iterator I = NewLoads.begin(),
284 E = NewLoads.end(); I != E; ++I)
285 AST->copyValue(PNUser, I->second);
286 AST->copyValue(PNUser, NewPN);
287 AST->deleteValue(PNUser);
288 AST->deleteValue(PN);
291 // Remove the old load.
292 PNUser->replaceAllUsesWith(NewPN);
293 PNUser->getParent()->getInstList().erase(PNUser);
295 // Remove the old PHI node.
296 PN->getParent()->getInstList().erase(PN);
298 // Restart our scan of uses...
299 DefiningBlocks.clear();
304 if (OnlyUsedInOneBlock) {
306 OnlyBlock = User->getParent();
307 else if (OnlyBlock != User->getParent())
308 OnlyUsedInOneBlock = false;
312 // If the alloca is only read and written in one basic block, just perform a
313 // linear sweep over the block to eliminate it.
314 if (OnlyUsedInOneBlock) {
315 LocallyUsedAllocas[OnlyBlock].push_back(AI);
317 // Remove the alloca from the Allocas list, since it will be processed.
318 Allocas[AllocaNum] = Allocas.back();
325 PointerAllocaValues[AllocaNum] = AllocaPointerVal;
327 // If we haven't computed a numbering for the BB's in the function, do so
329 BBNumbers.compute(F);
331 // Compute the locations where PhiNodes need to be inserted. Look at the
332 // dominance frontier of EACH basic-block we have a write in.
334 unsigned CurrentVersion = 0;
335 std::set<PHINode*> InsertedPHINodes;
336 std::vector<unsigned> DFBlocks;
337 while (!DefiningBlocks.empty()) {
338 BasicBlock *BB = DefiningBlocks.back();
339 DefiningBlocks.pop_back();
341 // Look up the DF for this write, add it to PhiNodes
342 DominanceFrontier::const_iterator it = DF.find(BB);
343 if (it != DF.end()) {
344 const DominanceFrontier::DomSetType &S = it->second;
346 // In theory we don't need the indirection through the DFBlocks vector.
347 // In practice, the order of calling QueuePhiNode would depend on the
348 // (unspecified) ordering of basic blocks in the dominance frontier,
349 // which would give PHI nodes non-determinstic subscripts. Fix this by
350 // processing blocks in order of the occurance in the function.
351 for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
353 DFBlocks.push_back(BBNumbers.getNumber(*P));
355 // Sort by which the block ordering in the function.
356 std::sort(DFBlocks.begin(), DFBlocks.end());
358 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
359 BasicBlock *BB = BBNumbers.getBlock(DFBlocks[i]);
360 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
361 DefiningBlocks.push_back(BB);
367 // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
368 // of the writes to the variable, scan through the reads of the variable,
369 // marking PHI nodes which are actually necessary as alive (by removing them
370 // from the InsertedPHINodes set). This is not perfect: there may PHI
371 // marked alive because of loads which are dominated by stores, but there
372 // will be no unmarked PHI nodes which are actually used.
374 for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
375 MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
378 // If there are any PHI nodes which are now known to be dead, remove them!
379 for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
380 E = InsertedPHINodes.end(); I != E; ++I) {
382 std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
383 BBPNs[AllocaNum] = 0;
385 // Check to see if we just removed the last inserted PHI node from this
386 // basic block. If so, remove the entry for the basic block.
387 bool HasOtherPHIs = false;
388 for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
394 NewPhiNodes.erase(PN->getParent());
396 if (AST && isa<PointerType>(PN->getType()))
397 AST->deleteValue(PN);
398 PN->getParent()->getInstList().erase(PN);
401 // Keep the reverse mapping of the 'Allocas' array.
402 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
405 // Process all allocas which are only used in a single basic block.
406 for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
407 LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
408 const std::vector<AllocaInst*> &Allocas = I->second;
409 assert(!Allocas.empty() && "empty alloca list??");
411 // It's common for there to only be one alloca in the list. Handle it
413 if (Allocas.size() == 1)
414 PromoteLocallyUsedAlloca(I->first, Allocas[0]);
416 PromoteLocallyUsedAllocas(I->first, Allocas);
420 return; // All of the allocas must have been trivial!
422 // Set the incoming values for the basic block to be null values for all of
423 // the alloca's. We do this in case there is a load of a value that has not
424 // been stored yet. In this case, it will get this null value.
426 std::vector<Value *> Values(Allocas.size());
427 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
428 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
430 // Walks all basic blocks in the function performing the SSA rename algorithm
431 // and inserting the phi nodes we marked as necessary
433 RenamePass(F.begin(), 0, Values);
435 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
438 // Remove the allocas themselves from the function...
439 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
440 Instruction *A = Allocas[i];
442 // If there are any uses of the alloca instructions left, they must be in
443 // sections of dead code that were not processed on the dominance frontier.
444 // Just delete the users now.
447 A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
448 if (AST) AST->deleteValue(A);
449 A->getParent()->getInstList().erase(A);
452 // At this point, the renamer has added entries to PHI nodes for all reachable
453 // code. Unfortunately, there may be blocks which are not reachable, which
454 // the renamer hasn't traversed. If this is the case, the PHI nodes may not
455 // have incoming values for all predecessors. Loop over all PHI nodes we have
456 // created, inserting null constants if they are missing any incoming values.
458 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
459 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
461 std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
462 std::vector<PHINode*> &PNs = I->second;
463 assert(!PNs.empty() && "Empty PHI node list??");
465 // Only do work here if there the PHI nodes are missing incoming values. We
466 // know that all PHI nodes that were inserted in a block will have the same
467 // number of incoming values, so we can just check any PHI node.
469 for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
472 if (Preds.size() != FirstPHI->getNumIncomingValues()) {
473 // Ok, now we know that all of the PHI nodes are missing entries for some
474 // basic blocks. Start by sorting the incoming predecessors for efficient
476 std::sort(Preds.begin(), Preds.end());
478 // Now we loop through all BB's which have entries in FirstPHI and remove
479 // them from the Preds list.
480 for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
481 // Do a log(n) search of the Preds list for the entry we want.
482 std::vector<BasicBlock*>::iterator EntIt =
483 std::lower_bound(Preds.begin(), Preds.end(),
484 FirstPHI->getIncomingBlock(i));
485 assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
486 "PHI node has entry for a block which is not a predecessor!");
492 // At this point, the blocks left in the preds list must have dummy
493 // entries inserted into every PHI nodes for the block.
494 for (unsigned i = 0, e = PNs.size(); i != e; ++i)
495 if (PHINode *PN = PNs[i]) {
496 Value *NullVal = Constant::getNullValue(PN->getType());
497 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
498 PN->addIncoming(NullVal, Preds[pred]);
504 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
505 // "minimal" SSA form. To do this, it inserts all of the PHI nodes on the IDF
506 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
507 // each read of the variable. For each block that reads the variable, this
508 // function is called, which removes used PHI nodes from the DeadPHINodes set.
509 // After all of the reads have been processed, any PHI nodes left in the
510 // DeadPHINodes set are removed.
512 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
513 std::set<PHINode*> &DeadPHINodes) {
514 // Scan the immediate dominators of this block looking for a block which has a
515 // PHI node for Alloca num. If we find it, mark the PHI node as being alive!
516 for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
517 BasicBlock *DomBB = N->getBlock();
518 std::map<BasicBlock*, std::vector<PHINode*> >::iterator
519 I = NewPhiNodes.find(DomBB);
520 if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
521 // Ok, we found an inserted PHI node which dominates this value.
522 PHINode *DominatingPHI = I->second[AllocaNum];
524 // Find out if we previously thought it was dead.
525 std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
526 if (DPNI != DeadPHINodes.end()) {
527 // Ok, until now, we thought this PHI node was dead. Mark it as being
529 DeadPHINodes.erase(DPNI);
531 // Now that we have marked the PHI node alive, also mark any PHI nodes
532 // which it might use as being alive as well.
533 for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
535 MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
541 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
542 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
543 /// potentially useless PHI nodes by just performing a single linear pass over
544 /// the basic block using the Alloca.
546 void PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
547 assert(!AI->use_empty() && "There are no uses of the alloca!");
549 // Handle degenerate cases quickly.
550 if (AI->hasOneUse()) {
551 Instruction *U = cast<Instruction>(AI->use_back());
552 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
553 // Must be a load of uninitialized value.
554 LI->replaceAllUsesWith(Constant::getNullValue(AI->getAllocatedType()));
555 if (AST && isa<PointerType>(LI->getType()))
556 AST->deleteValue(LI);
558 // Otherwise it must be a store which is never read.
559 assert(isa<StoreInst>(U));
561 BB->getInstList().erase(U);
563 // Uses of the uninitialized memory location shall get zero...
564 Value *CurVal = Constant::getNullValue(AI->getAllocatedType());
566 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
567 Instruction *Inst = I++;
568 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
569 if (LI->getOperand(0) == AI) {
570 // Loads just returns the "current value"...
571 LI->replaceAllUsesWith(CurVal);
572 if (AST && isa<PointerType>(LI->getType()))
573 AST->deleteValue(LI);
574 BB->getInstList().erase(LI);
576 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
577 if (SI->getOperand(1) == AI) {
578 // Store updates the "current value"...
579 CurVal = SI->getOperand(0);
580 BB->getInstList().erase(SI);
586 // After traversing the basic block, there should be no more uses of the
587 // alloca, remove it now.
588 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
589 if (AST) AST->deleteValue(AI);
590 AI->getParent()->getInstList().erase(AI);
593 /// PromoteLocallyUsedAllocas - This method is just like
594 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
595 /// instructions in parallel. This is important in cases where we have large
596 /// basic blocks, as we don't want to rescan the entire basic block for each
597 /// alloca which is locally used in it (which might be a lot).
598 void PromoteMem2Reg::
599 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
600 std::map<AllocaInst*, Value*> CurValues;
601 for (unsigned i = 0, e = AIs.size(); i != e; ++i)
602 CurValues[AIs[i]] = 0; // Insert with null value
604 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
605 Instruction *Inst = I++;
606 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
607 // Is this a load of an alloca we are tracking?
608 if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
609 std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
610 if (AIt != CurValues.end()) {
611 // Loads just returns the "current value"...
612 if (AIt->second == 0) // Uninitialized value??
613 AIt->second =Constant::getNullValue(AIt->first->getAllocatedType());
614 LI->replaceAllUsesWith(AIt->second);
615 if (AST && isa<PointerType>(LI->getType()))
616 AST->deleteValue(LI);
617 BB->getInstList().erase(LI);
620 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
621 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
622 std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
623 if (AIt != CurValues.end()) {
624 // Store updates the "current value"...
625 AIt->second = SI->getOperand(0);
626 BB->getInstList().erase(SI);
635 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
636 // Alloca returns true if there wasn't already a phi-node for that variable
638 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
640 std::set<PHINode*> &InsertedPHINodes) {
641 // Look up the basic-block in question.
642 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
643 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
645 // If the BB already has a phi node added for the i'th alloca then we're done!
646 if (BBPNs[AllocaNo]) return false;
648 // Create a PhiNode using the dereferenced type... and add the phi-node to the
650 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
651 Allocas[AllocaNo]->getName() + "." +
652 utostr(Version++), BB->begin());
653 BBPNs[AllocaNo] = PN;
654 InsertedPHINodes.insert(PN);
656 if (AST && isa<PointerType>(PN->getType()))
657 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
663 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
664 // stores to the allocas which we are promoting. IncomingVals indicates what
665 // value each Alloca contains on exit from the predecessor block Pred.
667 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
668 std::vector<Value*> &IncomingVals) {
670 // If this BB needs a PHI node, update the PHI node for each variable we need
672 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
673 BBPNI = NewPhiNodes.find(BB);
674 if (BBPNI != NewPhiNodes.end()) {
675 std::vector<PHINode *> &BBPNs = BBPNI->second;
676 for (unsigned k = 0; k != BBPNs.size(); ++k)
677 if (PHINode *PN = BBPNs[k]) {
678 // Add this incoming value to the PHI node.
679 PN->addIncoming(IncomingVals[k], Pred);
681 // The currently active variable for this block is now the PHI.
682 IncomingVals[k] = PN;
686 // don't revisit nodes
687 if (Visited.count(BB)) return;
692 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
693 Instruction *I = II++; // get the instruction, increment iterator
695 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
696 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
697 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
698 if (AI != AllocaLookup.end()) {
699 Value *V = IncomingVals[AI->second];
701 // walk the use list of this load and replace all uses with r
702 LI->replaceAllUsesWith(V);
703 if (AST && isa<PointerType>(LI->getType()))
704 AST->deleteValue(LI);
705 BB->getInstList().erase(LI);
708 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
709 // Delete this instruction and mark the name as the current holder of the
711 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
712 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
713 if (ai != AllocaLookup.end()) {
714 // what value were we writing?
715 IncomingVals[ai->second] = SI->getOperand(0);
716 BB->getInstList().erase(SI);
722 // Recurse to our successors.
723 TerminatorInst *TI = BB->getTerminator();
724 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
725 std::vector<Value*> OutgoingVals(IncomingVals);
726 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
730 /// PromoteMemToReg - Promote the specified list of alloca instructions into
731 /// scalar registers, inserting PHI nodes as appropriate. This function makes
732 /// use of DominanceFrontier information. This function does not modify the CFG
733 /// of the function at all. All allocas must be from the same function.
735 /// If AST is specified, the specified tracker is updated to reflect changes
738 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
739 DominatorTree &DT, DominanceFrontier &DF,
740 const TargetData &TD, AliasSetTracker *AST) {
741 // If there is nothing to do, bail out...
742 if (Allocas.empty()) return;
743 PromoteMem2Reg(Allocas, DT, DF, TD, AST).run();