1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file promotes 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"
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "mem2reg"
20 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
37 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
38 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
39 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
40 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
44 struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
45 typedef std::pair<BasicBlock*, unsigned> EltTy;
46 static inline EltTy getEmptyKey() {
47 return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
49 static inline EltTy getTombstoneKey() {
50 return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
52 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
53 return DenseMapInfo<void*>::getHashValue(Val.first) + Val.second*2;
55 static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
61 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
62 /// This is true if there are only loads and stores to the alloca.
64 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
65 // FIXME: If the memory unit is of pointer or integer type, we can permit
66 // assignments to subsections of the memory unit.
68 // Only allow direct and non-volatile loads and stores...
69 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
70 UI != UE; ++UI) // Loop over all of the uses of the alloca
71 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
74 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
75 if (SI->getOperand(0) == AI)
76 return false; // Don't allow a store OF the AI, only INTO the AI.
89 // Data package used by RenamePass()
90 class RenamePassData {
92 typedef std::vector<Value *> ValVector;
94 RenamePassData() : BB(NULL), Pred(NULL), Values() {}
95 RenamePassData(BasicBlock *B, BasicBlock *P,
96 const ValVector &V) : BB(B), Pred(P), Values(V) {}
101 void swap(RenamePassData &RHS) {
102 std::swap(BB, RHS.BB);
103 std::swap(Pred, RHS.Pred);
104 Values.swap(RHS.Values);
108 /// LargeBlockInfo - This assigns and keeps a per-bb relative ordering of
109 /// load/store instructions in the block that directly load or store an alloca.
111 /// This functionality is important because it avoids scanning large basic
112 /// blocks multiple times when promoting many allocas in the same block.
113 class LargeBlockInfo {
114 /// InstNumbers - For each instruction that we track, keep the index of the
115 /// instruction. The index starts out as the number of the instruction from
116 /// the start of the block.
117 DenseMap<const Instruction *, unsigned> InstNumbers;
120 /// isInterestingInstruction - This code only looks at accesses to allocas.
121 static bool isInterestingInstruction(const Instruction *I) {
122 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
123 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
126 /// getInstructionIndex - Get or calculate the index of the specified
128 unsigned getInstructionIndex(const Instruction *I) {
129 assert(isInterestingInstruction(I) &&
130 "Not a load/store to/from an alloca?");
132 // If we already have this instruction number, return it.
133 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
134 if (It != InstNumbers.end()) return It->second;
136 // Scan the whole block to get the instruction. This accumulates
137 // information for every interesting instruction in the block, in order to
138 // avoid gratuitus rescans.
139 const BasicBlock *BB = I->getParent();
141 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end();
143 if (isInterestingInstruction(BBI))
144 InstNumbers[BBI] = InstNo++;
145 It = InstNumbers.find(I);
147 assert(It != InstNumbers.end() && "Didn't insert instruction?");
151 void deleteValue(const Instruction *I) {
152 InstNumbers.erase(I);
160 struct PromoteMem2Reg {
161 /// Allocas - The alloca instructions being promoted.
163 std::vector<AllocaInst*> Allocas;
165 DominanceFrontier &DF;
167 /// AST - An AliasSetTracker object to update. If null, don't update it.
169 AliasSetTracker *AST;
171 /// AllocaLookup - Reverse mapping of Allocas.
173 std::map<AllocaInst*, unsigned> AllocaLookup;
175 /// NewPhiNodes - The PhiNodes we're adding.
177 DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
179 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
180 /// it corresponds to.
181 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
183 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
184 /// each alloca that is of pointer type, we keep track of what to copyValue
185 /// to the inserted PHI nodes here.
187 std::vector<Value*> PointerAllocaValues;
189 /// Visited - The set of basic blocks the renamer has already visited.
191 SmallPtrSet<BasicBlock*, 16> Visited;
193 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
194 /// non-determinstic behavior.
195 DenseMap<BasicBlock*, unsigned> BBNumbers;
197 /// BBNumPreds - Lazily compute the number of predecessors a block has.
198 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
200 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
201 DominanceFrontier &df, AliasSetTracker *ast)
202 : Allocas(A), DT(dt), DF(df), AST(ast) {}
206 /// properlyDominates - Return true if I1 properly dominates I2.
208 bool properlyDominates(Instruction *I1, Instruction *I2) const {
209 if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
210 I1 = II->getNormalDest()->begin();
211 return DT.properlyDominates(I1->getParent(), I2->getParent());
214 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
216 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
217 return DT.dominates(BB1, BB2);
221 void RemoveFromAllocasList(unsigned &AllocaIdx) {
222 Allocas[AllocaIdx] = Allocas.back();
227 unsigned getNumPreds(const BasicBlock *BB) {
228 unsigned &NP = BBNumPreds[BB];
230 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
234 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
236 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
237 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
238 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
240 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
241 LargeBlockInfo &LBI);
242 void PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
243 LargeBlockInfo &LBI);
246 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
247 RenamePassData::ValVector &IncVals,
248 std::vector<RenamePassData> &Worklist);
249 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
250 SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
254 std::vector<BasicBlock*> DefiningBlocks;
255 std::vector<BasicBlock*> UsingBlocks;
257 StoreInst *OnlyStore;
258 BasicBlock *OnlyBlock;
259 bool OnlyUsedInOneBlock;
261 Value *AllocaPointerVal;
264 DefiningBlocks.clear();
268 OnlyUsedInOneBlock = true;
269 AllocaPointerVal = 0;
272 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
274 void AnalyzeAlloca(AllocaInst *AI) {
277 // As we scan the uses of the alloca instruction, keep track of stores,
278 // and decide whether all of the loads and stores to the alloca are within
279 // the same basic block.
280 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
282 Instruction *User = cast<Instruction>(*UI++);
284 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
285 // Remember the basic blocks which define new values for the alloca
286 DefiningBlocks.push_back(SI->getParent());
287 AllocaPointerVal = SI->getOperand(0);
290 LoadInst *LI = cast<LoadInst>(User);
291 // Otherwise it must be a load instruction, keep track of variable
293 UsingBlocks.push_back(LI->getParent());
294 AllocaPointerVal = LI;
297 if (OnlyUsedInOneBlock) {
299 OnlyBlock = User->getParent();
300 else if (OnlyBlock != User->getParent())
301 OnlyUsedInOneBlock = false;
306 } // end of anonymous namespace
309 void PromoteMem2Reg::run() {
310 Function &F = *DF.getRoot()->getParent();
312 if (AST) PointerAllocaValues.resize(Allocas.size());
317 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
318 AllocaInst *AI = Allocas[AllocaNum];
320 assert(isAllocaPromotable(AI) &&
321 "Cannot promote non-promotable alloca!");
322 assert(AI->getParent()->getParent() == &F &&
323 "All allocas should be in the same function, which is same as DF!");
325 if (AI->use_empty()) {
326 // If there are no uses of the alloca, just delete it now.
327 if (AST) AST->deleteValue(AI);
328 AI->eraseFromParent();
330 // Remove the alloca from the Allocas list, since it has been processed
331 RemoveFromAllocasList(AllocaNum);
336 // Calculate the set of read and write-locations for each alloca. This is
337 // analogous to finding the 'uses' and 'definitions' of each variable.
338 Info.AnalyzeAlloca(AI);
340 // If there is only a single store to this value, replace any loads of
341 // it that are directly dominated by the definition with the value stored.
342 if (Info.DefiningBlocks.size() == 1) {
343 RewriteSingleStoreAlloca(AI, Info, LBI);
345 // Finally, after the scan, check to see if the store is all that is left.
346 if (Info.UsingBlocks.empty()) {
347 // Remove the (now dead) store and alloca.
348 Info.OnlyStore->eraseFromParent();
349 LBI.deleteValue(Info.OnlyStore);
351 if (AST) AST->deleteValue(AI);
352 AI->eraseFromParent();
355 // The alloca has been processed, move on.
356 RemoveFromAllocasList(AllocaNum);
363 // If the alloca is only read and written in one basic block, just perform a
364 // linear sweep over the block to eliminate it.
365 if (Info.OnlyUsedInOneBlock) {
366 PromoteSingleBlockAlloca(AI, Info, LBI);
368 // Finally, after the scan, check to see if the stores are all that is
370 if (Info.UsingBlocks.empty()) {
372 // Remove the (now dead) stores and alloca.
373 while (!AI->use_empty()) {
374 StoreInst *SI = cast<StoreInst>(AI->use_back());
375 SI->eraseFromParent();
379 if (AST) AST->deleteValue(AI);
380 AI->eraseFromParent();
383 // The alloca has been processed, move on.
384 RemoveFromAllocasList(AllocaNum);
391 // If we haven't computed a numbering for the BB's in the function, do so
393 if (BBNumbers.empty()) {
395 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
399 // If we have an AST to keep updated, remember some pointer value that is
400 // stored into the alloca.
402 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
404 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
405 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
407 // At this point, we're committed to promoting the alloca using IDF's, and
408 // the standard SSA construction algorithm. Determine which blocks need PHI
409 // nodes and see if we can optimize out some work by avoiding insertion of
411 DetermineInsertionPoint(AI, AllocaNum, Info);
415 return; // All of the allocas must have been trivial!
420 // Set the incoming values for the basic block to be null values for all of
421 // the alloca's. We do this in case there is a load of a value that has not
422 // been stored yet. In this case, it will get this null value.
424 RenamePassData::ValVector Values(Allocas.size());
425 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
426 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
428 // Walks all basic blocks in the function performing the SSA rename algorithm
429 // and inserting the phi nodes we marked as necessary
431 std::vector<RenamePassData> RenamePassWorkList;
432 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
435 RPD.swap(RenamePassWorkList.back());
436 RenamePassWorkList.pop_back();
437 // RenamePass may add new worklist entries.
438 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
439 } while (!RenamePassWorkList.empty());
441 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
444 // Remove the allocas themselves from the function.
445 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
446 Instruction *A = Allocas[i];
448 // If there are any uses of the alloca instructions left, they must be in
449 // sections of dead code that were not processed on the dominance frontier.
450 // Just delete the users now.
453 A->replaceAllUsesWith(UndefValue::get(A->getType()));
454 if (AST) AST->deleteValue(A);
455 A->eraseFromParent();
459 // Loop over all of the PHI nodes and see if there are any that we can get
460 // rid of because they merge all of the same incoming values. This can
461 // happen due to undef values coming into the PHI nodes. This process is
462 // iterative, because eliminating one PHI node can cause others to be removed.
463 bool EliminatedAPHI = true;
464 while (EliminatedAPHI) {
465 EliminatedAPHI = false;
467 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
468 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
469 PHINode *PN = I->second;
471 // If this PHI node merges one value and/or undefs, get the value.
472 if (Value *V = PN->hasConstantValue(&DT)) {
473 if (AST && isa<PointerType>(PN->getType()))
474 AST->deleteValue(PN);
475 PN->replaceAllUsesWith(V);
476 PN->eraseFromParent();
477 NewPhiNodes.erase(I++);
478 EliminatedAPHI = true;
485 // At this point, the renamer has added entries to PHI nodes for all reachable
486 // code. Unfortunately, there may be unreachable blocks which the renamer
487 // hasn't traversed. If this is the case, the PHI nodes may not
488 // have incoming values for all predecessors. Loop over all PHI nodes we have
489 // created, inserting undef values if they are missing any incoming values.
491 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
492 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
493 // We want to do this once per basic block. As such, only process a block
494 // when we find the PHI that is the first entry in the block.
495 PHINode *SomePHI = I->second;
496 BasicBlock *BB = SomePHI->getParent();
497 if (&BB->front() != SomePHI)
500 // Only do work here if there the PHI nodes are missing incoming values. We
501 // know that all PHI nodes that were inserted in a block will have the same
502 // number of incoming values, so we can just check any of them.
503 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
506 // Get the preds for BB.
507 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
509 // Ok, now we know that all of the PHI nodes are missing entries for some
510 // basic blocks. Start by sorting the incoming predecessors for efficient
512 std::sort(Preds.begin(), Preds.end());
514 // Now we loop through all BB's which have entries in SomePHI and remove
515 // them from the Preds list.
516 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
517 // Do a log(n) search of the Preds list for the entry we want.
518 SmallVector<BasicBlock*, 16>::iterator EntIt =
519 std::lower_bound(Preds.begin(), Preds.end(),
520 SomePHI->getIncomingBlock(i));
521 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
522 "PHI node has entry for a block which is not a predecessor!");
528 // At this point, the blocks left in the preds list must have dummy
529 // entries inserted into every PHI nodes for the block. Update all the phi
530 // nodes in this block that we are inserting (there could be phis before
532 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
533 BasicBlock::iterator BBI = BB->begin();
534 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
535 SomePHI->getNumIncomingValues() == NumBadPreds) {
536 Value *UndefVal = UndefValue::get(SomePHI->getType());
537 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
538 SomePHI->addIncoming(UndefVal, Preds[pred]);
546 /// ComputeLiveInBlocks - Determine which blocks the value is live in. These
547 /// are blocks which lead to uses. Knowing this allows us to avoid inserting
548 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
550 void PromoteMem2Reg::
551 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
552 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
553 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
555 // To determine liveness, we must iterate through the predecessors of blocks
556 // where the def is live. Blocks are added to the worklist if we need to
557 // check their predecessors. Start with all the using blocks.
558 SmallVector<BasicBlock*, 64> LiveInBlockWorklist;
559 LiveInBlockWorklist.insert(LiveInBlockWorklist.end(),
560 Info.UsingBlocks.begin(), Info.UsingBlocks.end());
562 // If any of the using blocks is also a definition block, check to see if the
563 // definition occurs before or after the use. If it happens before the use,
564 // the value isn't really live-in.
565 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
566 BasicBlock *BB = LiveInBlockWorklist[i];
567 if (!DefBlocks.count(BB)) continue;
569 // Okay, this is a block that both uses and defines the value. If the first
570 // reference to the alloca is a def (store), then we know it isn't live-in.
571 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
572 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
573 if (SI->getOperand(1) != AI) continue;
575 // We found a store to the alloca before a load. The alloca is not
576 // actually live-in here.
577 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
578 LiveInBlockWorklist.pop_back();
583 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
584 if (LI->getOperand(0) != AI) continue;
586 // Okay, we found a load before a store to the alloca. It is actually
587 // live into this block.
593 // Now that we have a set of blocks where the phi is live-in, recursively add
594 // their predecessors until we find the full region the value is live.
595 while (!LiveInBlockWorklist.empty()) {
596 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
598 // The block really is live in here, insert it into the set. If already in
599 // the set, then it has already been processed.
600 if (!LiveInBlocks.insert(BB))
603 // Since the value is live into BB, it is either defined in a predecessor or
604 // live into it to. Add the preds to the worklist unless they are a
606 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
609 // The value is not live into a predecessor if it defines the value.
610 if (DefBlocks.count(P))
613 // Otherwise it is, add to the worklist.
614 LiveInBlockWorklist.push_back(P);
619 /// DetermineInsertionPoint - At this point, we're committed to promoting the
620 /// alloca using IDF's, and the standard SSA construction algorithm. Determine
621 /// which blocks need phi nodes and see if we can optimize out some work by
622 /// avoiding insertion of dead phi nodes.
623 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
626 // Unique the set of defining blocks for efficient lookup.
627 SmallPtrSet<BasicBlock*, 32> DefBlocks;
628 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
630 // Determine which blocks the value is live in. These are blocks which lead
632 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
633 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
635 // Compute the locations where PhiNodes need to be inserted. Look at the
636 // dominance frontier of EACH basic-block we have a write in.
637 unsigned CurrentVersion = 0;
638 SmallPtrSet<PHINode*, 16> InsertedPHINodes;
639 std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
640 while (!Info.DefiningBlocks.empty()) {
641 BasicBlock *BB = Info.DefiningBlocks.back();
642 Info.DefiningBlocks.pop_back();
644 // Look up the DF for this write, add it to defining blocks.
645 DominanceFrontier::const_iterator it = DF.find(BB);
646 if (it == DF.end()) continue;
648 const DominanceFrontier::DomSetType &S = it->second;
650 // In theory we don't need the indirection through the DFBlocks vector.
651 // In practice, the order of calling QueuePhiNode would depend on the
652 // (unspecified) ordering of basic blocks in the dominance frontier,
653 // which would give PHI nodes non-determinstic subscripts. Fix this by
654 // processing blocks in order of the occurance in the function.
655 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
656 PE = S.end(); P != PE; ++P) {
657 // If the frontier block is not in the live-in set for the alloca, don't
658 // bother processing it.
659 if (!LiveInBlocks.count(*P))
662 DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
665 // Sort by which the block ordering in the function.
666 if (DFBlocks.size() > 1)
667 std::sort(DFBlocks.begin(), DFBlocks.end());
669 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
670 BasicBlock *BB = DFBlocks[i].second;
671 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
672 Info.DefiningBlocks.push_back(BB);
678 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
679 /// replace any loads of it that are directly dominated by the definition with
680 /// the value stored.
681 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
683 LargeBlockInfo &LBI) {
684 StoreInst *OnlyStore = Info.OnlyStore;
685 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
686 BasicBlock *StoreBB = OnlyStore->getParent();
689 // Clear out UsingBlocks. We will reconstruct it here if needed.
690 Info.UsingBlocks.clear();
692 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
693 Instruction *UserInst = cast<Instruction>(*UI++);
694 if (!isa<LoadInst>(UserInst)) {
695 assert(UserInst == OnlyStore && "Should only have load/stores");
698 LoadInst *LI = cast<LoadInst>(UserInst);
700 // Okay, if we have a load from the alloca, we want to replace it with the
701 // only value stored to the alloca. We can do this if the value is
702 // dominated by the store. If not, we use the rest of the mem2reg machinery
703 // to insert the phi nodes as needed.
704 if (!StoringGlobalVal) { // Non-instructions are always dominated.
705 if (LI->getParent() == StoreBB) {
706 // If we have a use that is in the same block as the store, compare the
707 // indices of the two instructions to see which one came first. If the
708 // load came before the store, we can't handle it.
709 if (StoreIndex == -1)
710 StoreIndex = LBI.getInstructionIndex(OnlyStore);
712 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
713 // Can't handle this load, bail out.
714 Info.UsingBlocks.push_back(StoreBB);
718 } else if (LI->getParent() != StoreBB &&
719 !dominates(StoreBB, LI->getParent())) {
720 // If the load and store are in different blocks, use BB dominance to
721 // check their relationships. If the store doesn't dom the use, bail
723 Info.UsingBlocks.push_back(LI->getParent());
728 // Otherwise, we *can* safely rewrite this load.
729 Value *ReplVal = OnlyStore->getOperand(0);
730 // If the replacement value is the load, this must occur in unreachable
733 ReplVal = UndefValue::get(LI->getType());
734 LI->replaceAllUsesWith(ReplVal);
735 if (AST && isa<PointerType>(LI->getType()))
736 AST->deleteValue(LI);
737 LI->eraseFromParent();
744 /// StoreIndexSearchPredicate - This is a helper predicate used to search by the
745 /// first element of a pair.
746 struct StoreIndexSearchPredicate {
747 bool operator()(const std::pair<unsigned, StoreInst*> &LHS,
748 const std::pair<unsigned, StoreInst*> &RHS) {
749 return LHS.first < RHS.first;
755 /// PromoteSingleBlockAlloca - Many allocas are only used within a single basic
756 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
757 /// potentially useless PHI nodes by just performing a single linear pass over
758 /// the basic block using the Alloca.
760 /// If we cannot promote this alloca (because it is read before it is written),
761 /// return true. This is necessary in cases where, due to control flow, the
762 /// alloca is potentially undefined on some control flow paths. e.g. code like
763 /// this is potentially correct:
765 /// for (...) { if (c) { A = undef; undef = B; } }
767 /// ... so long as A is not used before undef is set.
769 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
770 LargeBlockInfo &LBI) {
771 // The trickiest case to handle is when we have large blocks. Because of this,
772 // this code is optimized assuming that large blocks happen. This does not
773 // significantly pessimize the small block case. This uses LargeBlockInfo to
774 // make it efficient to get the index of various operations in the block.
776 // Clear out UsingBlocks. We will reconstruct it here if needed.
777 Info.UsingBlocks.clear();
779 // Walk the use-def list of the alloca, getting the locations of all stores.
780 typedef SmallVector<std::pair<unsigned, StoreInst*>, 64> StoresByIndexTy;
781 StoresByIndexTy StoresByIndex;
783 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
785 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
786 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
788 // If there are no stores to the alloca, just replace any loads with undef.
789 if (StoresByIndex.empty()) {
790 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
791 if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
792 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
793 if (AST && isa<PointerType>(LI->getType()))
794 AST->deleteValue(LI);
796 LI->eraseFromParent();
801 // Sort the stores by their index, making it efficient to do a lookup with a
803 std::sort(StoresByIndex.begin(), StoresByIndex.end());
805 // Walk all of the loads from this alloca, replacing them with the nearest
806 // store above them, if any.
807 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
808 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
811 unsigned LoadIdx = LBI.getInstructionIndex(LI);
813 // Find the nearest store that has a lower than this load.
814 StoresByIndexTy::iterator I =
815 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
816 std::pair<unsigned, StoreInst*>(LoadIdx, 0),
817 StoreIndexSearchPredicate());
819 // If there is no store before this load, then we can't promote this load.
820 if (I == StoresByIndex.begin()) {
821 // Can't handle this load, bail out.
822 Info.UsingBlocks.push_back(LI->getParent());
826 // Otherwise, there was a store before this load, the load takes its value.
828 LI->replaceAllUsesWith(I->second->getOperand(0));
829 if (AST && isa<PointerType>(LI->getType()))
830 AST->deleteValue(LI);
831 LI->eraseFromParent();
837 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
838 // Alloca returns true if there wasn't already a phi-node for that variable
840 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
842 SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
843 // Look up the basic-block in question.
844 PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
846 // If the BB already has a phi node added for the i'th alloca then we're done!
847 if (PN) return false;
849 // Create a PhiNode using the dereferenced type... and add the phi-node to the
851 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(),
852 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
855 PhiToAllocaMap[PN] = AllocaNo;
856 PN->reserveOperandSpace(getNumPreds(BB));
858 InsertedPHINodes.insert(PN);
860 if (AST && isa<PointerType>(PN->getType()))
861 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
866 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
867 // stores to the allocas which we are promoting. IncomingVals indicates what
868 // value each Alloca contains on exit from the predecessor block Pred.
870 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
871 RenamePassData::ValVector &IncomingVals,
872 std::vector<RenamePassData> &Worklist) {
874 // If we are inserting any phi nodes into this BB, they will already be in the
876 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
877 // If we have PHI nodes to update, compute the number of edges from Pred to
879 if (PhiToAllocaMap.count(APN)) {
880 // We want to be able to distinguish between PHI nodes being inserted by
881 // this invocation of mem2reg from those phi nodes that already existed in
882 // the IR before mem2reg was run. We determine that APN is being inserted
883 // because it is missing incoming edges. All other PHI nodes being
884 // inserted by this pass of mem2reg will have the same number of incoming
885 // operands so far. Remember this count.
886 unsigned NewPHINumOperands = APN->getNumOperands();
888 unsigned NumEdges = 0;
889 for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
892 assert(NumEdges && "Must be at least one edge from Pred to BB!");
894 // Add entries for all the phis.
895 BasicBlock::iterator PNI = BB->begin();
897 unsigned AllocaNo = PhiToAllocaMap[APN];
899 // Add N incoming values to the PHI node.
900 for (unsigned i = 0; i != NumEdges; ++i)
901 APN->addIncoming(IncomingVals[AllocaNo], Pred);
903 // The currently active variable for this block is now the PHI.
904 IncomingVals[AllocaNo] = APN;
906 // Get the next phi node.
908 APN = dyn_cast<PHINode>(PNI);
911 // Verify that it is missing entries. If not, it is not being inserted
912 // by this mem2reg invocation so we want to ignore it.
913 } while (APN->getNumOperands() == NewPHINumOperands);
917 // Don't revisit blocks.
918 if (!Visited.insert(BB)) return;
920 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
921 Instruction *I = II++; // get the instruction, increment iterator
923 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
924 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
927 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
928 if (AI == AllocaLookup.end()) continue;
930 Value *V = IncomingVals[AI->second];
932 // Anything using the load now uses the current value.
933 LI->replaceAllUsesWith(V);
934 if (AST && isa<PointerType>(LI->getType()))
935 AST->deleteValue(LI);
936 BB->getInstList().erase(LI);
937 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
938 // Delete this instruction and mark the name as the current holder of the
940 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
943 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
944 if (ai == AllocaLookup.end())
947 // what value were we writing?
948 IncomingVals[ai->second] = SI->getOperand(0);
949 BB->getInstList().erase(SI);
953 // 'Recurse' to our successors.
954 succ_iterator I = succ_begin(BB), E = succ_end(BB);
957 // Keep track of the successors so we don't visit the same successor twice
958 SmallPtrSet<BasicBlock*, 8> VisitedSuccs;
960 // Handle the first successor without using the worklist.
961 VisitedSuccs.insert(*I);
967 if (VisitedSuccs.insert(*I))
968 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
973 /// PromoteMemToReg - Promote the specified list of alloca instructions into
974 /// scalar registers, inserting PHI nodes as appropriate. This function makes
975 /// use of DominanceFrontier information. This function does not modify the CFG
976 /// of the function at all. All allocas must be from the same function.
978 /// If AST is specified, the specified tracker is updated to reflect changes
981 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
982 DominatorTree &DT, DominanceFrontier &DF,
983 AliasSetTracker *AST) {
984 // If there is nothing to do, bail out...
985 if (Allocas.empty()) return;
987 PromoteMem2Reg(Allocas, DT, DF, AST).run();