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/LLVMContext.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/Analysis/AliasSetTracker.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
38 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
39 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
40 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
41 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
45 struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
46 typedef std::pair<BasicBlock*, unsigned> EltTy;
47 static inline EltTy getEmptyKey() {
48 return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
50 static inline EltTy getTombstoneKey() {
51 return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
53 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
54 return DenseMapInfo<void*>::getHashValue(Val.first) + Val.second*2;
56 static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
59 static bool isPod() { return true; }
63 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
64 /// This is true if there are only loads and stores to the alloca.
66 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
67 // FIXME: If the memory unit is of pointer or integer type, we can permit
68 // assignments to subsections of the memory unit.
70 // Only allow direct and non-volatile loads and stores...
71 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
72 UI != UE; ++UI) // Loop over all of the uses of the alloca
73 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
76 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
77 if (SI->getOperand(0) == AI)
78 return false; // Don't allow a store OF the AI, only INTO the AI.
81 } else if (const BitCastInst *BC = dyn_cast<BitCastInst>(*UI)) {
82 // A bitcast that does not feed into debug info inhibits promotion.
83 if (!BC->hasOneUse() || !isa<DbgInfoIntrinsic>(*BC->use_begin()))
85 // If the only use is by debug info, this alloca will not exist in
86 // non-debug code, so don't try to promote; this ensures the same
87 // codegen with debug info. Otherwise, debug info should not
88 // inhibit promotion (but we must examine other uses).
101 // Data package used by RenamePass()
102 class RenamePassData {
104 typedef std::vector<Value *> ValVector;
107 RenamePassData(BasicBlock *B, BasicBlock *P,
108 const ValVector &V) : BB(B), Pred(P), Values(V) {}
113 void swap(RenamePassData &RHS) {
114 std::swap(BB, RHS.BB);
115 std::swap(Pred, RHS.Pred);
116 Values.swap(RHS.Values);
120 /// LargeBlockInfo - This assigns and keeps a per-bb relative ordering of
121 /// load/store instructions in the block that directly load or store an alloca.
123 /// This functionality is important because it avoids scanning large basic
124 /// blocks multiple times when promoting many allocas in the same block.
125 class LargeBlockInfo {
126 /// InstNumbers - For each instruction that we track, keep the index of the
127 /// instruction. The index starts out as the number of the instruction from
128 /// the start of the block.
129 DenseMap<const Instruction *, unsigned> InstNumbers;
132 /// isInterestingInstruction - This code only looks at accesses to allocas.
133 static bool isInterestingInstruction(const Instruction *I) {
134 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
135 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
138 /// getInstructionIndex - Get or calculate the index of the specified
140 unsigned getInstructionIndex(const Instruction *I) {
141 assert(isInterestingInstruction(I) &&
142 "Not a load/store to/from an alloca?");
144 // If we already have this instruction number, return it.
145 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
146 if (It != InstNumbers.end()) return It->second;
148 // Scan the whole block to get the instruction. This accumulates
149 // information for every interesting instruction in the block, in order to
150 // avoid gratuitus rescans.
151 const BasicBlock *BB = I->getParent();
153 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end();
155 if (isInterestingInstruction(BBI))
156 InstNumbers[BBI] = InstNo++;
157 It = InstNumbers.find(I);
159 assert(It != InstNumbers.end() && "Didn't insert instruction?");
163 void deleteValue(const Instruction *I) {
164 InstNumbers.erase(I);
172 struct PromoteMem2Reg {
173 /// Allocas - The alloca instructions being promoted.
175 std::vector<AllocaInst*> Allocas;
177 DominanceFrontier &DF;
179 /// AST - An AliasSetTracker object to update. If null, don't update it.
181 AliasSetTracker *AST;
183 LLVMContext &Context;
185 /// AllocaLookup - Reverse mapping of Allocas.
187 std::map<AllocaInst*, unsigned> AllocaLookup;
189 /// NewPhiNodes - The PhiNodes we're adding.
191 DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*> NewPhiNodes;
193 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
194 /// it corresponds to.
195 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
197 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
198 /// each alloca that is of pointer type, we keep track of what to copyValue
199 /// to the inserted PHI nodes here.
201 std::vector<Value*> PointerAllocaValues;
203 /// Visited - The set of basic blocks the renamer has already visited.
205 SmallPtrSet<BasicBlock*, 16> Visited;
207 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
208 /// non-determinstic behavior.
209 DenseMap<BasicBlock*, unsigned> BBNumbers;
211 /// BBNumPreds - Lazily compute the number of predecessors a block has.
212 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
214 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
215 DominanceFrontier &df, AliasSetTracker *ast,
217 : Allocas(A), DT(dt), DF(df), AST(ast), Context(C) {}
221 /// properlyDominates - Return true if I1 properly dominates I2.
223 bool properlyDominates(Instruction *I1, Instruction *I2) const {
224 if (InvokeInst *II = dyn_cast<InvokeInst>(I1))
225 I1 = II->getNormalDest()->begin();
226 return DT.properlyDominates(I1->getParent(), I2->getParent());
229 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
231 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
232 return DT.dominates(BB1, BB2);
236 void RemoveFromAllocasList(unsigned &AllocaIdx) {
237 Allocas[AllocaIdx] = Allocas.back();
242 unsigned getNumPreds(const BasicBlock *BB) {
243 unsigned &NP = BBNumPreds[BB];
245 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
249 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
251 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
252 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
253 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
255 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
256 LargeBlockInfo &LBI);
257 void PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
258 LargeBlockInfo &LBI);
261 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
262 RenamePassData::ValVector &IncVals,
263 std::vector<RenamePassData> &Worklist);
264 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
265 SmallPtrSet<PHINode*, 16> &InsertedPHINodes);
269 std::vector<BasicBlock*> DefiningBlocks;
270 std::vector<BasicBlock*> UsingBlocks;
272 StoreInst *OnlyStore;
273 BasicBlock *OnlyBlock;
274 bool OnlyUsedInOneBlock;
276 Value *AllocaPointerVal;
279 DefiningBlocks.clear();
283 OnlyUsedInOneBlock = true;
284 AllocaPointerVal = 0;
287 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
289 void AnalyzeAlloca(AllocaInst *AI) {
292 // As we scan the uses of the alloca instruction, keep track of stores,
293 // and decide whether all of the loads and stores to the alloca are within
294 // the same basic block.
295 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
297 Instruction *User = cast<Instruction>(*UI++);
298 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
299 // Remove any uses of this alloca in DbgInfoInstrinsics.
300 assert(BC->hasOneUse() && "Unexpected alloca uses!");
301 DbgInfoIntrinsic *DI = cast<DbgInfoIntrinsic>(*BC->use_begin());
302 DI->eraseFromParent();
303 BC->eraseFromParent();
307 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
308 // Remember the basic blocks which define new values for the alloca
309 DefiningBlocks.push_back(SI->getParent());
310 AllocaPointerVal = SI->getOperand(0);
313 LoadInst *LI = cast<LoadInst>(User);
314 // Otherwise it must be a load instruction, keep track of variable
316 UsingBlocks.push_back(LI->getParent());
317 AllocaPointerVal = LI;
320 if (OnlyUsedInOneBlock) {
322 OnlyBlock = User->getParent();
323 else if (OnlyBlock != User->getParent())
324 OnlyUsedInOneBlock = false;
329 } // end of anonymous namespace
332 void PromoteMem2Reg::run() {
333 Function &F = *DF.getRoot()->getParent();
335 if (AST) PointerAllocaValues.resize(Allocas.size());
340 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
341 AllocaInst *AI = Allocas[AllocaNum];
343 assert(isAllocaPromotable(AI) &&
344 "Cannot promote non-promotable alloca!");
345 assert(AI->getParent()->getParent() == &F &&
346 "All allocas should be in the same function, which is same as DF!");
348 if (AI->use_empty()) {
349 // If there are no uses of the alloca, just delete it now.
350 if (AST) AST->deleteValue(AI);
351 AI->eraseFromParent();
353 // Remove the alloca from the Allocas list, since it has been processed
354 RemoveFromAllocasList(AllocaNum);
359 // Calculate the set of read and write-locations for each alloca. This is
360 // analogous to finding the 'uses' and 'definitions' of each variable.
361 Info.AnalyzeAlloca(AI);
363 // If there is only a single store to this value, replace any loads of
364 // it that are directly dominated by the definition with the value stored.
365 if (Info.DefiningBlocks.size() == 1) {
366 RewriteSingleStoreAlloca(AI, Info, LBI);
368 // Finally, after the scan, check to see if the store is all that is left.
369 if (Info.UsingBlocks.empty()) {
370 // Remove the (now dead) store and alloca.
371 Info.OnlyStore->eraseFromParent();
372 LBI.deleteValue(Info.OnlyStore);
374 if (AST) AST->deleteValue(AI);
375 AI->eraseFromParent();
378 // The alloca has been processed, move on.
379 RemoveFromAllocasList(AllocaNum);
386 // If the alloca is only read and written in one basic block, just perform a
387 // linear sweep over the block to eliminate it.
388 if (Info.OnlyUsedInOneBlock) {
389 PromoteSingleBlockAlloca(AI, Info, LBI);
391 // Finally, after the scan, check to see if the stores are all that is
393 if (Info.UsingBlocks.empty()) {
395 // Remove the (now dead) stores and alloca.
396 while (!AI->use_empty()) {
397 StoreInst *SI = cast<StoreInst>(AI->use_back());
398 SI->eraseFromParent();
402 if (AST) AST->deleteValue(AI);
403 AI->eraseFromParent();
406 // The alloca has been processed, move on.
407 RemoveFromAllocasList(AllocaNum);
414 // If we haven't computed a numbering for the BB's in the function, do so
416 if (BBNumbers.empty()) {
418 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
422 // If we have an AST to keep updated, remember some pointer value that is
423 // stored into the alloca.
425 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
427 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
428 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
430 // At this point, we're committed to promoting the alloca using IDF's, and
431 // the standard SSA construction algorithm. Determine which blocks need PHI
432 // nodes and see if we can optimize out some work by avoiding insertion of
434 DetermineInsertionPoint(AI, AllocaNum, Info);
438 return; // All of the allocas must have been trivial!
443 // Set the incoming values for the basic block to be null values for all of
444 // the alloca's. We do this in case there is a load of a value that has not
445 // been stored yet. In this case, it will get this null value.
447 RenamePassData::ValVector Values(Allocas.size());
448 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
449 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
451 // Walks all basic blocks in the function performing the SSA rename algorithm
452 // and inserting the phi nodes we marked as necessary
454 std::vector<RenamePassData> RenamePassWorkList;
455 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
456 while (!RenamePassWorkList.empty()) {
458 RPD.swap(RenamePassWorkList.back());
459 RenamePassWorkList.pop_back();
460 // RenamePass may add new worklist entries.
461 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
464 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
467 // Remove the allocas themselves from the function.
468 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
469 Instruction *A = Allocas[i];
471 // If there are any uses of the alloca instructions left, they must be in
472 // sections of dead code that were not processed on the dominance frontier.
473 // Just delete the users now.
476 A->replaceAllUsesWith(UndefValue::get(A->getType()));
477 if (AST) AST->deleteValue(A);
478 A->eraseFromParent();
482 // Loop over all of the PHI nodes and see if there are any that we can get
483 // rid of because they merge all of the same incoming values. This can
484 // happen due to undef values coming into the PHI nodes. This process is
485 // iterative, because eliminating one PHI node can cause others to be removed.
486 bool EliminatedAPHI = true;
487 while (EliminatedAPHI) {
488 EliminatedAPHI = false;
490 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
491 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
492 PHINode *PN = I->second;
494 // If this PHI node merges one value and/or undefs, get the value.
495 if (Value *V = PN->hasConstantValue(&DT)) {
496 if (AST && isa<PointerType>(PN->getType()))
497 AST->deleteValue(PN);
498 PN->replaceAllUsesWith(V);
499 PN->eraseFromParent();
500 NewPhiNodes.erase(I++);
501 EliminatedAPHI = true;
508 // At this point, the renamer has added entries to PHI nodes for all reachable
509 // code. Unfortunately, there may be unreachable blocks which the renamer
510 // hasn't traversed. If this is the case, the PHI nodes may not
511 // have incoming values for all predecessors. Loop over all PHI nodes we have
512 // created, inserting undef values if they are missing any incoming values.
514 for (DenseMap<std::pair<BasicBlock*, unsigned>, PHINode*>::iterator I =
515 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
516 // We want to do this once per basic block. As such, only process a block
517 // when we find the PHI that is the first entry in the block.
518 PHINode *SomePHI = I->second;
519 BasicBlock *BB = SomePHI->getParent();
520 if (&BB->front() != SomePHI)
523 // Only do work here if there the PHI nodes are missing incoming values. We
524 // know that all PHI nodes that were inserted in a block will have the same
525 // number of incoming values, so we can just check any of them.
526 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
529 // Get the preds for BB.
530 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
532 // Ok, now we know that all of the PHI nodes are missing entries for some
533 // basic blocks. Start by sorting the incoming predecessors for efficient
535 std::sort(Preds.begin(), Preds.end());
537 // Now we loop through all BB's which have entries in SomePHI and remove
538 // them from the Preds list.
539 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
540 // Do a log(n) search of the Preds list for the entry we want.
541 SmallVector<BasicBlock*, 16>::iterator EntIt =
542 std::lower_bound(Preds.begin(), Preds.end(),
543 SomePHI->getIncomingBlock(i));
544 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
545 "PHI node has entry for a block which is not a predecessor!");
551 // At this point, the blocks left in the preds list must have dummy
552 // entries inserted into every PHI nodes for the block. Update all the phi
553 // nodes in this block that we are inserting (there could be phis before
555 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
556 BasicBlock::iterator BBI = BB->begin();
557 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
558 SomePHI->getNumIncomingValues() == NumBadPreds) {
559 Value *UndefVal = UndefValue::get(SomePHI->getType());
560 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
561 SomePHI->addIncoming(UndefVal, Preds[pred]);
569 /// ComputeLiveInBlocks - Determine which blocks the value is live in. These
570 /// are blocks which lead to uses. Knowing this allows us to avoid inserting
571 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
573 void PromoteMem2Reg::
574 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
575 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
576 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
578 // To determine liveness, we must iterate through the predecessors of blocks
579 // where the def is live. Blocks are added to the worklist if we need to
580 // check their predecessors. Start with all the using blocks.
581 SmallVector<BasicBlock*, 64> LiveInBlockWorklist;
582 LiveInBlockWorklist.insert(LiveInBlockWorklist.end(),
583 Info.UsingBlocks.begin(), Info.UsingBlocks.end());
585 // If any of the using blocks is also a definition block, check to see if the
586 // definition occurs before or after the use. If it happens before the use,
587 // the value isn't really live-in.
588 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
589 BasicBlock *BB = LiveInBlockWorklist[i];
590 if (!DefBlocks.count(BB)) continue;
592 // Okay, this is a block that both uses and defines the value. If the first
593 // reference to the alloca is a def (store), then we know it isn't live-in.
594 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
595 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
596 if (SI->getOperand(1) != AI) continue;
598 // We found a store to the alloca before a load. The alloca is not
599 // actually live-in here.
600 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
601 LiveInBlockWorklist.pop_back();
606 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
607 if (LI->getOperand(0) != AI) continue;
609 // Okay, we found a load before a store to the alloca. It is actually
610 // live into this block.
616 // Now that we have a set of blocks where the phi is live-in, recursively add
617 // their predecessors until we find the full region the value is live.
618 while (!LiveInBlockWorklist.empty()) {
619 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
621 // The block really is live in here, insert it into the set. If already in
622 // the set, then it has already been processed.
623 if (!LiveInBlocks.insert(BB))
626 // Since the value is live into BB, it is either defined in a predecessor or
627 // live into it to. Add the preds to the worklist unless they are a
629 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
632 // The value is not live into a predecessor if it defines the value.
633 if (DefBlocks.count(P))
636 // Otherwise it is, add to the worklist.
637 LiveInBlockWorklist.push_back(P);
642 /// DetermineInsertionPoint - At this point, we're committed to promoting the
643 /// alloca using IDF's, and the standard SSA construction algorithm. Determine
644 /// which blocks need phi nodes and see if we can optimize out some work by
645 /// avoiding insertion of dead phi nodes.
646 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
649 // Unique the set of defining blocks for efficient lookup.
650 SmallPtrSet<BasicBlock*, 32> DefBlocks;
651 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
653 // Determine which blocks the value is live in. These are blocks which lead
655 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
656 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
658 // Compute the locations where PhiNodes need to be inserted. Look at the
659 // dominance frontier of EACH basic-block we have a write in.
660 unsigned CurrentVersion = 0;
661 SmallPtrSet<PHINode*, 16> InsertedPHINodes;
662 std::vector<std::pair<unsigned, BasicBlock*> > DFBlocks;
663 while (!Info.DefiningBlocks.empty()) {
664 BasicBlock *BB = Info.DefiningBlocks.back();
665 Info.DefiningBlocks.pop_back();
667 // Look up the DF for this write, add it to defining blocks.
668 DominanceFrontier::const_iterator it = DF.find(BB);
669 if (it == DF.end()) continue;
671 const DominanceFrontier::DomSetType &S = it->second;
673 // In theory we don't need the indirection through the DFBlocks vector.
674 // In practice, the order of calling QueuePhiNode would depend on the
675 // (unspecified) ordering of basic blocks in the dominance frontier,
676 // which would give PHI nodes non-determinstic subscripts. Fix this by
677 // processing blocks in order of the occurance in the function.
678 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
679 PE = S.end(); P != PE; ++P) {
680 // If the frontier block is not in the live-in set for the alloca, don't
681 // bother processing it.
682 if (!LiveInBlocks.count(*P))
685 DFBlocks.push_back(std::make_pair(BBNumbers[*P], *P));
688 // Sort by which the block ordering in the function.
689 if (DFBlocks.size() > 1)
690 std::sort(DFBlocks.begin(), DFBlocks.end());
692 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
693 BasicBlock *BB = DFBlocks[i].second;
694 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
695 Info.DefiningBlocks.push_back(BB);
701 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
702 /// replace any loads of it that are directly dominated by the definition with
703 /// the value stored.
704 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
706 LargeBlockInfo &LBI) {
707 StoreInst *OnlyStore = Info.OnlyStore;
708 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
709 BasicBlock *StoreBB = OnlyStore->getParent();
712 // Clear out UsingBlocks. We will reconstruct it here if needed.
713 Info.UsingBlocks.clear();
715 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
716 Instruction *UserInst = cast<Instruction>(*UI++);
717 if (!isa<LoadInst>(UserInst)) {
718 assert(UserInst == OnlyStore && "Should only have load/stores");
721 LoadInst *LI = cast<LoadInst>(UserInst);
723 // Okay, if we have a load from the alloca, we want to replace it with the
724 // only value stored to the alloca. We can do this if the value is
725 // dominated by the store. If not, we use the rest of the mem2reg machinery
726 // to insert the phi nodes as needed.
727 if (!StoringGlobalVal) { // Non-instructions are always dominated.
728 if (LI->getParent() == StoreBB) {
729 // If we have a use that is in the same block as the store, compare the
730 // indices of the two instructions to see which one came first. If the
731 // load came before the store, we can't handle it.
732 if (StoreIndex == -1)
733 StoreIndex = LBI.getInstructionIndex(OnlyStore);
735 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
736 // Can't handle this load, bail out.
737 Info.UsingBlocks.push_back(StoreBB);
741 } else if (LI->getParent() != StoreBB &&
742 !dominates(StoreBB, LI->getParent())) {
743 // If the load and store are in different blocks, use BB dominance to
744 // check their relationships. If the store doesn't dom the use, bail
746 Info.UsingBlocks.push_back(LI->getParent());
751 // Otherwise, we *can* safely rewrite this load.
752 Value *ReplVal = OnlyStore->getOperand(0);
753 // If the replacement value is the load, this must occur in unreachable
756 ReplVal = UndefValue::get(LI->getType());
757 LI->replaceAllUsesWith(ReplVal);
758 if (AST && isa<PointerType>(LI->getType()))
759 AST->deleteValue(LI);
760 LI->eraseFromParent();
767 /// StoreIndexSearchPredicate - This is a helper predicate used to search by the
768 /// first element of a pair.
769 struct StoreIndexSearchPredicate {
770 bool operator()(const std::pair<unsigned, StoreInst*> &LHS,
771 const std::pair<unsigned, StoreInst*> &RHS) {
772 return LHS.first < RHS.first;
778 /// PromoteSingleBlockAlloca - Many allocas are only used within a single basic
779 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
780 /// potentially useless PHI nodes by just performing a single linear pass over
781 /// the basic block using the Alloca.
783 /// If we cannot promote this alloca (because it is read before it is written),
784 /// return true. This is necessary in cases where, due to control flow, the
785 /// alloca is potentially undefined on some control flow paths. e.g. code like
786 /// this is potentially correct:
788 /// for (...) { if (c) { A = undef; undef = B; } }
790 /// ... so long as A is not used before undef is set.
792 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
793 LargeBlockInfo &LBI) {
794 // The trickiest case to handle is when we have large blocks. Because of this,
795 // this code is optimized assuming that large blocks happen. This does not
796 // significantly pessimize the small block case. This uses LargeBlockInfo to
797 // make it efficient to get the index of various operations in the block.
799 // Clear out UsingBlocks. We will reconstruct it here if needed.
800 Info.UsingBlocks.clear();
802 // Walk the use-def list of the alloca, getting the locations of all stores.
803 typedef SmallVector<std::pair<unsigned, StoreInst*>, 64> StoresByIndexTy;
804 StoresByIndexTy StoresByIndex;
806 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
808 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
809 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
811 // If there are no stores to the alloca, just replace any loads with undef.
812 if (StoresByIndex.empty()) {
813 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
814 if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
815 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
816 if (AST && isa<PointerType>(LI->getType()))
817 AST->deleteValue(LI);
819 LI->eraseFromParent();
824 // Sort the stores by their index, making it efficient to do a lookup with a
826 std::sort(StoresByIndex.begin(), StoresByIndex.end());
828 // Walk all of the loads from this alloca, replacing them with the nearest
829 // store above them, if any.
830 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
831 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
834 unsigned LoadIdx = LBI.getInstructionIndex(LI);
836 // Find the nearest store that has a lower than this load.
837 StoresByIndexTy::iterator I =
838 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
839 std::pair<unsigned, StoreInst*>(LoadIdx, 0),
840 StoreIndexSearchPredicate());
842 // If there is no store before this load, then we can't promote this load.
843 if (I == StoresByIndex.begin()) {
844 // Can't handle this load, bail out.
845 Info.UsingBlocks.push_back(LI->getParent());
849 // Otherwise, there was a store before this load, the load takes its value.
851 LI->replaceAllUsesWith(I->second->getOperand(0));
852 if (AST && isa<PointerType>(LI->getType()))
853 AST->deleteValue(LI);
854 LI->eraseFromParent();
860 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
861 // Alloca returns true if there wasn't already a phi-node for that variable
863 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
865 SmallPtrSet<PHINode*, 16> &InsertedPHINodes) {
866 // Look up the basic-block in question.
867 PHINode *&PN = NewPhiNodes[std::make_pair(BB, AllocaNo)];
869 // If the BB already has a phi node added for the i'th alloca then we're done!
870 if (PN) return false;
872 // Create a PhiNode using the dereferenced type... and add the phi-node to the
874 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(),
875 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
878 PhiToAllocaMap[PN] = AllocaNo;
879 PN->reserveOperandSpace(getNumPreds(BB));
881 InsertedPHINodes.insert(PN);
883 if (AST && isa<PointerType>(PN->getType()))
884 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
889 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
890 // stores to the allocas which we are promoting. IncomingVals indicates what
891 // value each Alloca contains on exit from the predecessor block Pred.
893 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
894 RenamePassData::ValVector &IncomingVals,
895 std::vector<RenamePassData> &Worklist) {
897 // If we are inserting any phi nodes into this BB, they will already be in the
899 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
900 // If we have PHI nodes to update, compute the number of edges from Pred to
902 if (PhiToAllocaMap.count(APN)) {
903 // We want to be able to distinguish between PHI nodes being inserted by
904 // this invocation of mem2reg from those phi nodes that already existed in
905 // the IR before mem2reg was run. We determine that APN is being inserted
906 // because it is missing incoming edges. All other PHI nodes being
907 // inserted by this pass of mem2reg will have the same number of incoming
908 // operands so far. Remember this count.
909 unsigned NewPHINumOperands = APN->getNumOperands();
911 unsigned NumEdges = 0;
912 for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
915 assert(NumEdges && "Must be at least one edge from Pred to BB!");
917 // Add entries for all the phis.
918 BasicBlock::iterator PNI = BB->begin();
920 unsigned AllocaNo = PhiToAllocaMap[APN];
922 // Add N incoming values to the PHI node.
923 for (unsigned i = 0; i != NumEdges; ++i)
924 APN->addIncoming(IncomingVals[AllocaNo], Pred);
926 // The currently active variable for this block is now the PHI.
927 IncomingVals[AllocaNo] = APN;
929 // Get the next phi node.
931 APN = dyn_cast<PHINode>(PNI);
934 // Verify that it is missing entries. If not, it is not being inserted
935 // by this mem2reg invocation so we want to ignore it.
936 } while (APN->getNumOperands() == NewPHINumOperands);
940 // Don't revisit blocks.
941 if (!Visited.insert(BB)) return;
943 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
944 Instruction *I = II++; // get the instruction, increment iterator
946 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
947 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
950 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
951 if (AI == AllocaLookup.end()) continue;
953 Value *V = IncomingVals[AI->second];
955 // Anything using the load now uses the current value.
956 LI->replaceAllUsesWith(V);
957 if (AST && isa<PointerType>(LI->getType()))
958 AST->deleteValue(LI);
959 BB->getInstList().erase(LI);
960 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
961 // Delete this instruction and mark the name as the current holder of the
963 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
966 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
967 if (ai == AllocaLookup.end())
970 // what value were we writing?
971 IncomingVals[ai->second] = SI->getOperand(0);
972 BB->getInstList().erase(SI);
976 // 'Recurse' to our successors.
977 succ_iterator I = succ_begin(BB), E = succ_end(BB);
980 // Keep track of the successors so we don't visit the same successor twice
981 SmallPtrSet<BasicBlock*, 8> VisitedSuccs;
983 // Handle the first successor without using the worklist.
984 VisitedSuccs.insert(*I);
990 if (VisitedSuccs.insert(*I))
991 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
996 /// PromoteMemToReg - Promote the specified list of alloca instructions into
997 /// scalar registers, inserting PHI nodes as appropriate. This function makes
998 /// use of DominanceFrontier information. This function does not modify the CFG
999 /// of the function at all. All allocas must be from the same function.
1001 /// If AST is specified, the specified tracker is updated to reflect changes
1004 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
1005 DominatorTree &DT, DominanceFrontier &DF,
1006 LLVMContext &Context, AliasSetTracker *AST) {
1007 // If there is nothing to do, bail out...
1008 if (Allocas.empty()) return;
1010 PromoteMem2Reg(Allocas, DT, DF, AST, Context).run();