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 iterated dominator frontiers to place PHI nodes, then
13 // traversing the function in depth-first order to rewrite loads and stores as
16 // The algorithm used here is based on:
18 // Sreedhar and Gao. A linear time algorithm for placing phi-nodes.
19 // In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of
20 // Programming Languages
21 // POPL '95. ACM, New York, NY, 62-73.
23 // It has been modified to not explicitly use the DJ graph data structure and to
24 // directly compute pruned SSA using per-variable liveness information.
26 //===----------------------------------------------------------------------===//
28 #define DEBUG_TYPE "mem2reg"
29 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
30 #include "llvm/Constants.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/DIBuilder.h"
34 #include "llvm/Function.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/IntrinsicInst.h"
37 #include "llvm/Metadata.h"
38 #include "llvm/Analysis/AliasSetTracker.h"
39 #include "llvm/Analysis/Dominators.h"
40 #include "llvm/Analysis/InstructionSimplify.h"
41 #include "llvm/Analysis/ValueTracking.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/Hashing.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/Support/CFG.h"
54 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
55 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
56 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
57 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
61 struct DenseMapInfo<std::pair<BasicBlock*, unsigned> > {
62 typedef std::pair<BasicBlock*, unsigned> EltTy;
63 static inline EltTy getEmptyKey() {
64 return EltTy(reinterpret_cast<BasicBlock*>(-1), ~0U);
66 static inline EltTy getTombstoneKey() {
67 return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
69 static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val) {
70 using llvm::hash_value;
71 return static_cast<unsigned>(hash_value(Val));
73 static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
79 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
80 /// This is true if there are only loads and stores to the alloca.
82 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
83 // FIXME: If the memory unit is of pointer or integer type, we can permit
84 // assignments to subsections of the memory unit.
86 // Only allow direct and non-volatile loads and stores...
87 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
88 UI != UE; ++UI) { // Loop over all of the uses of the alloca
90 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
91 // Note that atomic loads can be transformed; atomic semantics do
92 // not have any meaning for a local alloca.
95 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
96 if (SI->getOperand(0) == AI)
97 return false; // Don't allow a store OF the AI, only INTO the AI.
98 // Note that atomic stores can be transformed; atomic semantics do
99 // not have any meaning for a local alloca.
100 if (SI->isVolatile())
102 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
103 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
104 II->getIntrinsicID() != Intrinsic::lifetime_end)
106 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
107 if (BCI->getType() != Type::getInt8PtrTy(U->getContext()))
109 if (!onlyUsedByLifetimeMarkers(BCI))
111 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
112 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext()))
114 if (!GEPI->hasAllZeroIndices())
116 if (!onlyUsedByLifetimeMarkers(GEPI))
129 // Data package used by RenamePass()
130 class RenamePassData {
132 typedef std::vector<Value *> ValVector;
134 RenamePassData() : BB(NULL), Pred(NULL), Values() {}
135 RenamePassData(BasicBlock *B, BasicBlock *P,
136 const ValVector &V) : BB(B), Pred(P), Values(V) {}
141 void swap(RenamePassData &RHS) {
142 std::swap(BB, RHS.BB);
143 std::swap(Pred, RHS.Pred);
144 Values.swap(RHS.Values);
148 /// LargeBlockInfo - This assigns and keeps a per-bb relative ordering of
149 /// load/store instructions in the block that directly load or store an alloca.
151 /// This functionality is important because it avoids scanning large basic
152 /// blocks multiple times when promoting many allocas in the same block.
153 class LargeBlockInfo {
154 /// InstNumbers - For each instruction that we track, keep the index of the
155 /// instruction. The index starts out as the number of the instruction from
156 /// the start of the block.
157 DenseMap<const Instruction *, unsigned> InstNumbers;
160 /// isInterestingInstruction - This code only looks at accesses to allocas.
161 static bool isInterestingInstruction(const Instruction *I) {
162 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
163 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
166 /// getInstructionIndex - Get or calculate the index of the specified
168 unsigned getInstructionIndex(const Instruction *I) {
169 assert(isInterestingInstruction(I) &&
170 "Not a load/store to/from an alloca?");
172 // If we already have this instruction number, return it.
173 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
174 if (It != InstNumbers.end()) return It->second;
176 // Scan the whole block to get the instruction. This accumulates
177 // information for every interesting instruction in the block, in order to
178 // avoid gratuitus rescans.
179 const BasicBlock *BB = I->getParent();
181 for (BasicBlock::const_iterator BBI = BB->begin(), E = BB->end();
183 if (isInterestingInstruction(BBI))
184 InstNumbers[BBI] = InstNo++;
185 It = InstNumbers.find(I);
187 assert(It != InstNumbers.end() && "Didn't insert instruction?");
191 void deleteValue(const Instruction *I) {
192 InstNumbers.erase(I);
200 struct PromoteMem2Reg {
201 /// Allocas - The alloca instructions being promoted.
203 std::vector<AllocaInst*> Allocas;
207 /// AST - An AliasSetTracker object to update. If null, don't update it.
209 AliasSetTracker *AST;
211 /// AllocaLookup - Reverse mapping of Allocas.
213 DenseMap<AllocaInst*, unsigned> AllocaLookup;
215 /// NewPhiNodes - The PhiNodes we're adding.
217 DenseMap<std::pair<unsigned, unsigned>, PHINode*> NewPhiNodes;
219 /// PhiToAllocaMap - For each PHI node, keep track of which entry in Allocas
220 /// it corresponds to.
221 DenseMap<PHINode*, unsigned> PhiToAllocaMap;
223 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
224 /// each alloca that is of pointer type, we keep track of what to copyValue
225 /// to the inserted PHI nodes here.
227 std::vector<Value*> PointerAllocaValues;
229 /// AllocaDbgDeclares - For each alloca, we keep track of the dbg.declare
230 /// intrinsic that describes it, if any, so that we can convert it to a
231 /// dbg.value intrinsic if the alloca gets promoted.
232 SmallVector<DbgDeclareInst*, 8> AllocaDbgDeclares;
234 /// Visited - The set of basic blocks the renamer has already visited.
236 SmallPtrSet<BasicBlock*, 16> Visited;
238 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
239 /// non-determinstic behavior.
240 DenseMap<BasicBlock*, unsigned> BBNumbers;
242 /// DomLevels - Maps DomTreeNodes to their level in the dominator tree.
243 DenseMap<DomTreeNode*, unsigned> DomLevels;
245 /// BBNumPreds - Lazily compute the number of predecessors a block has.
246 DenseMap<const BasicBlock*, unsigned> BBNumPreds;
248 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
249 AliasSetTracker *ast)
250 : Allocas(A), DT(dt), DIB(0), AST(ast) {}
257 /// dominates - Return true if BB1 dominates BB2 using the DominatorTree.
259 bool dominates(BasicBlock *BB1, BasicBlock *BB2) const {
260 return DT.dominates(BB1, BB2);
264 void RemoveFromAllocasList(unsigned &AllocaIdx) {
265 Allocas[AllocaIdx] = Allocas.back();
270 unsigned getNumPreds(const BasicBlock *BB) {
271 unsigned &NP = BBNumPreds[BB];
273 NP = std::distance(pred_begin(BB), pred_end(BB))+1;
277 void DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
279 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
280 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
281 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks);
283 void RewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
284 LargeBlockInfo &LBI);
285 void PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
286 LargeBlockInfo &LBI);
288 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
289 RenamePassData::ValVector &IncVals,
290 std::vector<RenamePassData> &Worklist);
291 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
295 SmallVector<BasicBlock*, 32> DefiningBlocks;
296 SmallVector<BasicBlock*, 32> UsingBlocks;
298 StoreInst *OnlyStore;
299 BasicBlock *OnlyBlock;
300 bool OnlyUsedInOneBlock;
302 Value *AllocaPointerVal;
303 DbgDeclareInst *DbgDeclare;
306 DefiningBlocks.clear();
310 OnlyUsedInOneBlock = true;
311 AllocaPointerVal = 0;
315 /// AnalyzeAlloca - Scan the uses of the specified alloca, filling in our
317 void AnalyzeAlloca(AllocaInst *AI) {
320 // As we scan the uses of the alloca instruction, keep track of stores,
321 // and decide whether all of the loads and stores to the alloca are within
322 // the same basic block.
323 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
325 Instruction *User = cast<Instruction>(*UI++);
327 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
328 // Remember the basic blocks which define new values for the alloca
329 DefiningBlocks.push_back(SI->getParent());
330 AllocaPointerVal = SI->getOperand(0);
333 LoadInst *LI = cast<LoadInst>(User);
334 // Otherwise it must be a load instruction, keep track of variable
336 UsingBlocks.push_back(LI->getParent());
337 AllocaPointerVal = LI;
340 if (OnlyUsedInOneBlock) {
342 OnlyBlock = User->getParent();
343 else if (OnlyBlock != User->getParent())
344 OnlyUsedInOneBlock = false;
348 DbgDeclare = FindAllocaDbgDeclare(AI);
352 typedef std::pair<DomTreeNode*, unsigned> DomTreeNodePair;
354 struct DomTreeNodeCompare {
355 bool operator()(const DomTreeNodePair &LHS, const DomTreeNodePair &RHS) {
356 return LHS.second < RHS.second;
359 } // end of anonymous namespace
361 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
362 // Knowing that this alloca is promotable, we know that it's safe to kill all
363 // instructions except for load and store.
365 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
367 Instruction *I = cast<Instruction>(*UI);
369 if (isa<LoadInst>(I) || isa<StoreInst>(I))
372 if (!I->getType()->isVoidTy()) {
373 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
374 // Follow the use/def chain to erase them now instead of leaving it for
375 // dead code elimination later.
376 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
378 Instruction *Inst = cast<Instruction>(*UI);
380 Inst->eraseFromParent();
383 I->eraseFromParent();
387 void PromoteMem2Reg::run() {
388 Function &F = *DT.getRoot()->getParent();
390 if (AST) PointerAllocaValues.resize(Allocas.size());
391 AllocaDbgDeclares.resize(Allocas.size());
396 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
397 AllocaInst *AI = Allocas[AllocaNum];
399 assert(isAllocaPromotable(AI) &&
400 "Cannot promote non-promotable alloca!");
401 assert(AI->getParent()->getParent() == &F &&
402 "All allocas should be in the same function, which is same as DF!");
404 removeLifetimeIntrinsicUsers(AI);
406 if (AI->use_empty()) {
407 // If there are no uses of the alloca, just delete it now.
408 if (AST) AST->deleteValue(AI);
409 AI->eraseFromParent();
411 // Remove the alloca from the Allocas list, since it has been processed
412 RemoveFromAllocasList(AllocaNum);
417 // Calculate the set of read and write-locations for each alloca. This is
418 // analogous to finding the 'uses' and 'definitions' of each variable.
419 Info.AnalyzeAlloca(AI);
421 // If there is only a single store to this value, replace any loads of
422 // it that are directly dominated by the definition with the value stored.
423 if (Info.DefiningBlocks.size() == 1) {
424 RewriteSingleStoreAlloca(AI, Info, LBI);
426 // Finally, after the scan, check to see if the store is all that is left.
427 if (Info.UsingBlocks.empty()) {
428 // Record debuginfo for the store and remove the declaration's
430 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
432 DIB = new DIBuilder(*DDI->getParent()->getParent()->getParent());
433 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, *DIB);
434 DDI->eraseFromParent();
436 // Remove the (now dead) store and alloca.
437 Info.OnlyStore->eraseFromParent();
438 LBI.deleteValue(Info.OnlyStore);
440 if (AST) AST->deleteValue(AI);
441 AI->eraseFromParent();
444 // The alloca has been processed, move on.
445 RemoveFromAllocasList(AllocaNum);
452 // If the alloca is only read and written in one basic block, just perform a
453 // linear sweep over the block to eliminate it.
454 if (Info.OnlyUsedInOneBlock) {
455 PromoteSingleBlockAlloca(AI, Info, LBI);
457 // Finally, after the scan, check to see if the stores are all that is
459 if (Info.UsingBlocks.empty()) {
461 // Remove the (now dead) stores and alloca.
462 while (!AI->use_empty()) {
463 StoreInst *SI = cast<StoreInst>(AI->use_back());
464 // Record debuginfo for the store before removing it.
465 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
467 DIB = new DIBuilder(*SI->getParent()->getParent()->getParent());
468 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
470 SI->eraseFromParent();
474 if (AST) AST->deleteValue(AI);
475 AI->eraseFromParent();
478 // The alloca has been processed, move on.
479 RemoveFromAllocasList(AllocaNum);
481 // The alloca's debuginfo can be removed as well.
482 if (DbgDeclareInst *DDI = Info.DbgDeclare)
483 DDI->eraseFromParent();
490 // If we haven't computed dominator tree levels, do so now.
491 if (DomLevels.empty()) {
492 SmallVector<DomTreeNode*, 32> Worklist;
494 DomTreeNode *Root = DT.getRootNode();
496 Worklist.push_back(Root);
498 while (!Worklist.empty()) {
499 DomTreeNode *Node = Worklist.pop_back_val();
500 unsigned ChildLevel = DomLevels[Node] + 1;
501 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end();
503 DomLevels[*CI] = ChildLevel;
504 Worklist.push_back(*CI);
509 // If we haven't computed a numbering for the BB's in the function, do so
511 if (BBNumbers.empty()) {
513 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
517 // If we have an AST to keep updated, remember some pointer value that is
518 // stored into the alloca.
520 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
522 // Remember the dbg.declare intrinsic describing this alloca, if any.
523 if (Info.DbgDeclare) AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
525 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
526 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
528 // At this point, we're committed to promoting the alloca using IDF's, and
529 // the standard SSA construction algorithm. Determine which blocks need PHI
530 // nodes and see if we can optimize out some work by avoiding insertion of
532 DetermineInsertionPoint(AI, AllocaNum, Info);
536 return; // All of the allocas must have been trivial!
541 // Set the incoming values for the basic block to be null values for all of
542 // the alloca's. We do this in case there is a load of a value that has not
543 // been stored yet. In this case, it will get this null value.
545 RenamePassData::ValVector Values(Allocas.size());
546 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
547 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
549 // Walks all basic blocks in the function performing the SSA rename algorithm
550 // and inserting the phi nodes we marked as necessary
552 std::vector<RenamePassData> RenamePassWorkList;
553 RenamePassWorkList.push_back(RenamePassData(F.begin(), 0, Values));
556 RPD.swap(RenamePassWorkList.back());
557 RenamePassWorkList.pop_back();
558 // RenamePass may add new worklist entries.
559 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
560 } while (!RenamePassWorkList.empty());
562 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
565 // Remove the allocas themselves from the function.
566 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
567 Instruction *A = Allocas[i];
569 // If there are any uses of the alloca instructions left, they must be in
570 // unreachable basic blocks that were not processed by walking the dominator
571 // tree. Just delete the users now.
573 A->replaceAllUsesWith(UndefValue::get(A->getType()));
574 if (AST) AST->deleteValue(A);
575 A->eraseFromParent();
578 // Remove alloca's dbg.declare instrinsics from the function.
579 for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
580 if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
581 DDI->eraseFromParent();
583 // Loop over all of the PHI nodes and see if there are any that we can get
584 // rid of because they merge all of the same incoming values. This can
585 // happen due to undef values coming into the PHI nodes. This process is
586 // iterative, because eliminating one PHI node can cause others to be removed.
587 bool EliminatedAPHI = true;
588 while (EliminatedAPHI) {
589 EliminatedAPHI = false;
591 for (DenseMap<std::pair<unsigned, unsigned>, PHINode*>::iterator I =
592 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E;) {
593 PHINode *PN = I->second;
595 // If this PHI node merges one value and/or undefs, get the value.
596 if (Value *V = SimplifyInstruction(PN, 0, 0, &DT)) {
597 if (AST && PN->getType()->isPointerTy())
598 AST->deleteValue(PN);
599 PN->replaceAllUsesWith(V);
600 PN->eraseFromParent();
601 NewPhiNodes.erase(I++);
602 EliminatedAPHI = true;
609 // At this point, the renamer has added entries to PHI nodes for all reachable
610 // code. Unfortunately, there may be unreachable blocks which the renamer
611 // hasn't traversed. If this is the case, the PHI nodes may not
612 // have incoming values for all predecessors. Loop over all PHI nodes we have
613 // created, inserting undef values if they are missing any incoming values.
615 for (DenseMap<std::pair<unsigned, unsigned>, PHINode*>::iterator I =
616 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
617 // We want to do this once per basic block. As such, only process a block
618 // when we find the PHI that is the first entry in the block.
619 PHINode *SomePHI = I->second;
620 BasicBlock *BB = SomePHI->getParent();
621 if (&BB->front() != SomePHI)
624 // Only do work here if there the PHI nodes are missing incoming values. We
625 // know that all PHI nodes that were inserted in a block will have the same
626 // number of incoming values, so we can just check any of them.
627 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
630 // Get the preds for BB.
631 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
633 // Ok, now we know that all of the PHI nodes are missing entries for some
634 // basic blocks. Start by sorting the incoming predecessors for efficient
636 std::sort(Preds.begin(), Preds.end());
638 // Now we loop through all BB's which have entries in SomePHI and remove
639 // them from the Preds list.
640 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
641 // Do a log(n) search of the Preds list for the entry we want.
642 SmallVector<BasicBlock*, 16>::iterator EntIt =
643 std::lower_bound(Preds.begin(), Preds.end(),
644 SomePHI->getIncomingBlock(i));
645 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i)&&
646 "PHI node has entry for a block which is not a predecessor!");
652 // At this point, the blocks left in the preds list must have dummy
653 // entries inserted into every PHI nodes for the block. Update all the phi
654 // nodes in this block that we are inserting (there could be phis before
656 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
657 BasicBlock::iterator BBI = BB->begin();
658 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
659 SomePHI->getNumIncomingValues() == NumBadPreds) {
660 Value *UndefVal = UndefValue::get(SomePHI->getType());
661 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
662 SomePHI->addIncoming(UndefVal, Preds[pred]);
670 /// ComputeLiveInBlocks - Determine which blocks the value is live in. These
671 /// are blocks which lead to uses. Knowing this allows us to avoid inserting
672 /// PHI nodes into blocks which don't lead to uses (thus, the inserted phi nodes
674 void PromoteMem2Reg::
675 ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
676 const SmallPtrSet<BasicBlock*, 32> &DefBlocks,
677 SmallPtrSet<BasicBlock*, 32> &LiveInBlocks) {
679 // To determine liveness, we must iterate through the predecessors of blocks
680 // where the def is live. Blocks are added to the worklist if we need to
681 // check their predecessors. Start with all the using blocks.
682 SmallVector<BasicBlock*, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
683 Info.UsingBlocks.end());
685 // If any of the using blocks is also a definition block, check to see if the
686 // definition occurs before or after the use. If it happens before the use,
687 // the value isn't really live-in.
688 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
689 BasicBlock *BB = LiveInBlockWorklist[i];
690 if (!DefBlocks.count(BB)) continue;
692 // Okay, this is a block that both uses and defines the value. If the first
693 // reference to the alloca is a def (store), then we know it isn't live-in.
694 for (BasicBlock::iterator I = BB->begin(); ; ++I) {
695 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
696 if (SI->getOperand(1) != AI) continue;
698 // We found a store to the alloca before a load. The alloca is not
699 // actually live-in here.
700 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
701 LiveInBlockWorklist.pop_back();
706 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
707 if (LI->getOperand(0) != AI) continue;
709 // Okay, we found a load before a store to the alloca. It is actually
710 // live into this block.
716 // Now that we have a set of blocks where the phi is live-in, recursively add
717 // their predecessors until we find the full region the value is live.
718 while (!LiveInBlockWorklist.empty()) {
719 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
721 // The block really is live in here, insert it into the set. If already in
722 // the set, then it has already been processed.
723 if (!LiveInBlocks.insert(BB))
726 // Since the value is live into BB, it is either defined in a predecessor or
727 // live into it to. Add the preds to the worklist unless they are a
729 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
732 // The value is not live into a predecessor if it defines the value.
733 if (DefBlocks.count(P))
736 // Otherwise it is, add to the worklist.
737 LiveInBlockWorklist.push_back(P);
742 /// DetermineInsertionPoint - At this point, we're committed to promoting the
743 /// alloca using IDF's, and the standard SSA construction algorithm. Determine
744 /// which blocks need phi nodes and see if we can optimize out some work by
745 /// avoiding insertion of dead phi nodes.
746 void PromoteMem2Reg::DetermineInsertionPoint(AllocaInst *AI, unsigned AllocaNum,
748 // Unique the set of defining blocks for efficient lookup.
749 SmallPtrSet<BasicBlock*, 32> DefBlocks;
750 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
752 // Determine which blocks the value is live in. These are blocks which lead
754 SmallPtrSet<BasicBlock*, 32> LiveInBlocks;
755 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
757 // Use a priority queue keyed on dominator tree level so that inserted nodes
758 // are handled from the bottom of the dominator tree upwards.
759 typedef std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>,
760 DomTreeNodeCompare> IDFPriorityQueue;
763 for (SmallPtrSet<BasicBlock*, 32>::const_iterator I = DefBlocks.begin(),
764 E = DefBlocks.end(); I != E; ++I) {
765 if (DomTreeNode *Node = DT.getNode(*I))
766 PQ.push(std::make_pair(Node, DomLevels[Node]));
769 SmallVector<std::pair<unsigned, BasicBlock*>, 32> DFBlocks;
770 SmallPtrSet<DomTreeNode*, 32> Visited;
771 SmallVector<DomTreeNode*, 32> Worklist;
772 while (!PQ.empty()) {
773 DomTreeNodePair RootPair = PQ.top();
775 DomTreeNode *Root = RootPair.first;
776 unsigned RootLevel = RootPair.second;
778 // Walk all dominator tree children of Root, inspecting their CFG edges with
779 // targets elsewhere on the dominator tree. Only targets whose level is at
780 // most Root's level are added to the iterated dominance frontier of the
784 Worklist.push_back(Root);
786 while (!Worklist.empty()) {
787 DomTreeNode *Node = Worklist.pop_back_val();
788 BasicBlock *BB = Node->getBlock();
790 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
792 DomTreeNode *SuccNode = DT.getNode(*SI);
794 // Quickly skip all CFG edges that are also dominator tree edges instead
795 // of catching them below.
796 if (SuccNode->getIDom() == Node)
799 unsigned SuccLevel = DomLevels[SuccNode];
800 if (SuccLevel > RootLevel)
803 if (!Visited.insert(SuccNode))
806 BasicBlock *SuccBB = SuccNode->getBlock();
807 if (!LiveInBlocks.count(SuccBB))
810 DFBlocks.push_back(std::make_pair(BBNumbers[SuccBB], SuccBB));
811 if (!DefBlocks.count(SuccBB))
812 PQ.push(std::make_pair(SuccNode, SuccLevel));
815 for (DomTreeNode::iterator CI = Node->begin(), CE = Node->end(); CI != CE;
817 if (!Visited.count(*CI))
818 Worklist.push_back(*CI);
823 if (DFBlocks.size() > 1)
824 std::sort(DFBlocks.begin(), DFBlocks.end());
826 unsigned CurrentVersion = 0;
827 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i)
828 QueuePhiNode(DFBlocks[i].second, AllocaNum, CurrentVersion);
831 /// RewriteSingleStoreAlloca - If there is only a single store to this value,
832 /// replace any loads of it that are directly dominated by the definition with
833 /// the value stored.
834 void PromoteMem2Reg::RewriteSingleStoreAlloca(AllocaInst *AI,
836 LargeBlockInfo &LBI) {
837 StoreInst *OnlyStore = Info.OnlyStore;
838 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
839 BasicBlock *StoreBB = OnlyStore->getParent();
842 // Clear out UsingBlocks. We will reconstruct it here if needed.
843 Info.UsingBlocks.clear();
845 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E; ) {
846 Instruction *UserInst = cast<Instruction>(*UI++);
847 if (!isa<LoadInst>(UserInst)) {
848 assert(UserInst == OnlyStore && "Should only have load/stores");
851 LoadInst *LI = cast<LoadInst>(UserInst);
853 // Okay, if we have a load from the alloca, we want to replace it with the
854 // only value stored to the alloca. We can do this if the value is
855 // dominated by the store. If not, we use the rest of the mem2reg machinery
856 // to insert the phi nodes as needed.
857 if (!StoringGlobalVal) { // Non-instructions are always dominated.
858 if (LI->getParent() == StoreBB) {
859 // If we have a use that is in the same block as the store, compare the
860 // indices of the two instructions to see which one came first. If the
861 // load came before the store, we can't handle it.
862 if (StoreIndex == -1)
863 StoreIndex = LBI.getInstructionIndex(OnlyStore);
865 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
866 // Can't handle this load, bail out.
867 Info.UsingBlocks.push_back(StoreBB);
871 } else if (LI->getParent() != StoreBB &&
872 !dominates(StoreBB, LI->getParent())) {
873 // If the load and store are in different blocks, use BB dominance to
874 // check their relationships. If the store doesn't dom the use, bail
876 Info.UsingBlocks.push_back(LI->getParent());
881 // Otherwise, we *can* safely rewrite this load.
882 Value *ReplVal = OnlyStore->getOperand(0);
883 // If the replacement value is the load, this must occur in unreachable
886 ReplVal = UndefValue::get(LI->getType());
887 LI->replaceAllUsesWith(ReplVal);
888 if (AST && LI->getType()->isPointerTy())
889 AST->deleteValue(LI);
890 LI->eraseFromParent();
897 /// StoreIndexSearchPredicate - This is a helper predicate used to search by the
898 /// first element of a pair.
899 struct StoreIndexSearchPredicate {
900 bool operator()(const std::pair<unsigned, StoreInst*> &LHS,
901 const std::pair<unsigned, StoreInst*> &RHS) {
902 return LHS.first < RHS.first;
908 /// PromoteSingleBlockAlloca - Many allocas are only used within a single basic
909 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
910 /// potentially useless PHI nodes by just performing a single linear pass over
911 /// the basic block using the Alloca.
913 /// If we cannot promote this alloca (because it is read before it is written),
914 /// return true. This is necessary in cases where, due to control flow, the
915 /// alloca is potentially undefined on some control flow paths. e.g. code like
916 /// this is potentially correct:
918 /// for (...) { if (c) { A = undef; undef = B; } }
920 /// ... so long as A is not used before undef is set.
922 void PromoteMem2Reg::PromoteSingleBlockAlloca(AllocaInst *AI, AllocaInfo &Info,
923 LargeBlockInfo &LBI) {
924 // The trickiest case to handle is when we have large blocks. Because of this,
925 // this code is optimized assuming that large blocks happen. This does not
926 // significantly pessimize the small block case. This uses LargeBlockInfo to
927 // make it efficient to get the index of various operations in the block.
929 // Clear out UsingBlocks. We will reconstruct it here if needed.
930 Info.UsingBlocks.clear();
932 // Walk the use-def list of the alloca, getting the locations of all stores.
933 typedef SmallVector<std::pair<unsigned, StoreInst*>, 64> StoresByIndexTy;
934 StoresByIndexTy StoresByIndex;
936 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
938 if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
939 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
941 // If there are no stores to the alloca, just replace any loads with undef.
942 if (StoresByIndex.empty()) {
943 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;)
944 if (LoadInst *LI = dyn_cast<LoadInst>(*UI++)) {
945 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
946 if (AST && LI->getType()->isPointerTy())
947 AST->deleteValue(LI);
949 LI->eraseFromParent();
954 // Sort the stores by their index, making it efficient to do a lookup with a
956 std::sort(StoresByIndex.begin(), StoresByIndex.end());
958 // Walk all of the loads from this alloca, replacing them with the nearest
959 // store above them, if any.
960 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); UI != E;) {
961 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
964 unsigned LoadIdx = LBI.getInstructionIndex(LI);
966 // Find the nearest store that has a lower than this load.
967 StoresByIndexTy::iterator I =
968 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
969 std::pair<unsigned, StoreInst*>(LoadIdx, static_cast<StoreInst*>(0)),
970 StoreIndexSearchPredicate());
972 // If there is no store before this load, then we can't promote this load.
973 if (I == StoresByIndex.begin()) {
974 // Can't handle this load, bail out.
975 Info.UsingBlocks.push_back(LI->getParent());
979 // Otherwise, there was a store before this load, the load takes its value.
981 LI->replaceAllUsesWith(I->second->getOperand(0));
982 if (AST && LI->getType()->isPointerTy())
983 AST->deleteValue(LI);
984 LI->eraseFromParent();
989 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
990 // Alloca returns true if there wasn't already a phi-node for that variable
992 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
994 // Look up the basic-block in question.
995 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
997 // If the BB already has a phi node added for the i'th alloca then we're done!
998 if (PN) return false;
1000 // Create a PhiNode using the dereferenced type... and add the phi-node to the
1002 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
1003 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
1006 PhiToAllocaMap[PN] = AllocaNo;
1008 if (AST && PN->getType()->isPointerTy())
1009 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
1014 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
1015 // stores to the allocas which we are promoting. IncomingVals indicates what
1016 // value each Alloca contains on exit from the predecessor block Pred.
1018 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
1019 RenamePassData::ValVector &IncomingVals,
1020 std::vector<RenamePassData> &Worklist) {
1022 // If we are inserting any phi nodes into this BB, they will already be in the
1024 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1025 // If we have PHI nodes to update, compute the number of edges from Pred to
1027 if (PhiToAllocaMap.count(APN)) {
1028 // We want to be able to distinguish between PHI nodes being inserted by
1029 // this invocation of mem2reg from those phi nodes that already existed in
1030 // the IR before mem2reg was run. We determine that APN is being inserted
1031 // because it is missing incoming edges. All other PHI nodes being
1032 // inserted by this pass of mem2reg will have the same number of incoming
1033 // operands so far. Remember this count.
1034 unsigned NewPHINumOperands = APN->getNumOperands();
1036 unsigned NumEdges = 0;
1037 for (succ_iterator I = succ_begin(Pred), E = succ_end(Pred); I != E; ++I)
1040 assert(NumEdges && "Must be at least one edge from Pred to BB!");
1042 // Add entries for all the phis.
1043 BasicBlock::iterator PNI = BB->begin();
1045 unsigned AllocaNo = PhiToAllocaMap[APN];
1047 // Add N incoming values to the PHI node.
1048 for (unsigned i = 0; i != NumEdges; ++i)
1049 APN->addIncoming(IncomingVals[AllocaNo], Pred);
1051 // The currently active variable for this block is now the PHI.
1052 IncomingVals[AllocaNo] = APN;
1054 // Get the next phi node.
1056 APN = dyn_cast<PHINode>(PNI);
1057 if (APN == 0) break;
1059 // Verify that it is missing entries. If not, it is not being inserted
1060 // by this mem2reg invocation so we want to ignore it.
1061 } while (APN->getNumOperands() == NewPHINumOperands);
1065 // Don't revisit blocks.
1066 if (!Visited.insert(BB)) return;
1068 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
1069 Instruction *I = II++; // get the instruction, increment iterator
1071 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1072 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1075 DenseMap<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
1076 if (AI == AllocaLookup.end()) continue;
1078 Value *V = IncomingVals[AI->second];
1080 // Anything using the load now uses the current value.
1081 LI->replaceAllUsesWith(V);
1082 if (AST && LI->getType()->isPointerTy())
1083 AST->deleteValue(LI);
1084 BB->getInstList().erase(LI);
1085 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1086 // Delete this instruction and mark the name as the current holder of the
1088 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1089 if (!Dest) continue;
1091 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1092 if (ai == AllocaLookup.end())
1095 // what value were we writing?
1096 IncomingVals[ai->second] = SI->getOperand(0);
1097 // Record debuginfo for the store before removing it.
1098 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second]) {
1100 DIB = new DIBuilder(*SI->getParent()->getParent()->getParent());
1101 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1103 BB->getInstList().erase(SI);
1107 // 'Recurse' to our successors.
1108 succ_iterator I = succ_begin(BB), E = succ_end(BB);
1111 // Keep track of the successors so we don't visit the same successor twice
1112 SmallPtrSet<BasicBlock*, 8> VisitedSuccs;
1114 // Handle the first successor without using the worklist.
1115 VisitedSuccs.insert(*I);
1121 if (VisitedSuccs.insert(*I))
1122 Worklist.push_back(RenamePassData(*I, Pred, IncomingVals));
1127 /// PromoteMemToReg - Promote the specified list of alloca instructions into
1128 /// scalar registers, inserting PHI nodes as appropriate. This function does
1129 /// not modify the CFG of the function at all. All allocas must be from the
1132 /// If AST is specified, the specified tracker is updated to reflect changes
1135 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
1136 DominatorTree &DT, AliasSetTracker *AST) {
1137 // If there is nothing to do, bail out...
1138 if (Allocas.empty()) return;
1140 PromoteMem2Reg(Allocas, DT, AST).run();