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 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/IteratedDominanceFrontier.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/Transforms/Utils/Local.h"
44 #define DEBUG_TYPE "mem2reg"
46 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
47 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
48 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
49 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
51 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
52 // FIXME: If the memory unit is of pointer or integer type, we can permit
53 // assignments to subsections of the memory unit.
54 unsigned AS = AI->getType()->getAddressSpace();
56 // Only allow direct and non-volatile loads and stores...
57 for (const User *U : AI->users()) {
58 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
59 // Note that atomic loads can be transformed; atomic semantics do
60 // not have any meaning for a local alloca.
63 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
64 if (SI->getOperand(0) == AI)
65 return false; // Don't allow a store OF the AI, only INTO the AI.
66 // Note that atomic stores can be transformed; atomic semantics do
67 // not have any meaning for a local alloca.
70 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
71 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
72 II->getIntrinsicID() != Intrinsic::lifetime_end)
74 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
75 if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
77 if (!onlyUsedByLifetimeMarkers(BCI))
79 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
80 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
82 if (!GEPI->hasAllZeroIndices())
84 if (!onlyUsedByLifetimeMarkers(GEPI))
97 SmallVector<BasicBlock *, 32> DefiningBlocks;
98 SmallVector<BasicBlock *, 32> UsingBlocks;
100 StoreInst *OnlyStore;
101 BasicBlock *OnlyBlock;
102 bool OnlyUsedInOneBlock;
104 Value *AllocaPointerVal;
105 DbgDeclareInst *DbgDeclare;
108 DefiningBlocks.clear();
112 OnlyUsedInOneBlock = true;
113 AllocaPointerVal = nullptr;
114 DbgDeclare = nullptr;
117 /// Scan the uses of the specified alloca, filling in the AllocaInfo used
118 /// by the rest of the pass to reason about the uses of this alloca.
119 void AnalyzeAlloca(AllocaInst *AI) {
122 // As we scan the uses of the alloca instruction, keep track of stores,
123 // and decide whether all of the loads and stores to the alloca are within
124 // the same basic block.
125 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
126 Instruction *User = cast<Instruction>(*UI++);
128 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
129 // Remember the basic blocks which define new values for the alloca
130 DefiningBlocks.push_back(SI->getParent());
131 AllocaPointerVal = SI->getOperand(0);
134 LoadInst *LI = cast<LoadInst>(User);
135 // Otherwise it must be a load instruction, keep track of variable
137 UsingBlocks.push_back(LI->getParent());
138 AllocaPointerVal = LI;
141 if (OnlyUsedInOneBlock) {
143 OnlyBlock = User->getParent();
144 else if (OnlyBlock != User->getParent())
145 OnlyUsedInOneBlock = false;
149 DbgDeclare = FindAllocaDbgDeclare(AI);
153 // Data package used by RenamePass()
154 class RenamePassData {
156 typedef std::vector<Value *> ValVector;
158 RenamePassData() : BB(nullptr), Pred(nullptr), Values() {}
159 RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
160 : BB(B), Pred(P), Values(V) {}
165 void swap(RenamePassData &RHS) {
166 std::swap(BB, RHS.BB);
167 std::swap(Pred, RHS.Pred);
168 Values.swap(RHS.Values);
172 /// \brief This assigns and keeps a per-bb relative ordering of load/store
173 /// instructions in the block that directly load or store an alloca.
175 /// This functionality is important because it avoids scanning large basic
176 /// blocks multiple times when promoting many allocas in the same block.
177 class LargeBlockInfo {
178 /// \brief For each instruction that we track, keep the index of the
181 /// The index starts out as the number of the instruction from the start of
183 DenseMap<const Instruction *, unsigned> InstNumbers;
187 /// This code only looks at accesses to allocas.
188 static bool isInterestingInstruction(const Instruction *I) {
189 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
190 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
193 /// Get or calculate the index of the specified instruction.
194 unsigned getInstructionIndex(const Instruction *I) {
195 assert(isInterestingInstruction(I) &&
196 "Not a load/store to/from an alloca?");
198 // If we already have this instruction number, return it.
199 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
200 if (It != InstNumbers.end())
203 // Scan the whole block to get the instruction. This accumulates
204 // information for every interesting instruction in the block, in order to
205 // avoid gratuitus rescans.
206 const BasicBlock *BB = I->getParent();
208 for (const Instruction &BBI : *BB)
209 if (isInterestingInstruction(&BBI))
210 InstNumbers[&BBI] = InstNo++;
211 It = InstNumbers.find(I);
213 assert(It != InstNumbers.end() && "Didn't insert instruction?");
217 void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
219 void clear() { InstNumbers.clear(); }
222 struct PromoteMem2Reg {
223 /// The alloca instructions being promoted.
224 std::vector<AllocaInst *> Allocas;
228 /// An AliasSetTracker object to update. If null, don't update it.
229 AliasSetTracker *AST;
231 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
234 /// Reverse mapping of Allocas.
235 DenseMap<AllocaInst *, unsigned> AllocaLookup;
237 /// \brief The PhiNodes we're adding.
239 /// That map is used to simplify some Phi nodes as we iterate over it, so
240 /// it should have deterministic iterators. We could use a MapVector, but
241 /// since we already maintain a map from BasicBlock* to a stable numbering
242 /// (BBNumbers), the DenseMap is more efficient (also supports removal).
243 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
245 /// For each PHI node, keep track of which entry in Allocas it corresponds
247 DenseMap<PHINode *, unsigned> PhiToAllocaMap;
249 /// If we are updating an AliasSetTracker, then for each alloca that is of
250 /// pointer type, we keep track of what to copyValue to the inserted PHI
252 std::vector<Value *> PointerAllocaValues;
254 /// For each alloca, we keep track of the dbg.declare intrinsic that
255 /// describes it, if any, so that we can convert it to a dbg.value
256 /// intrinsic if the alloca gets promoted.
257 SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
259 /// The set of basic blocks the renamer has already visited.
261 SmallPtrSet<BasicBlock *, 16> Visited;
263 /// Contains a stable numbering of basic blocks to avoid non-determinstic
265 DenseMap<BasicBlock *, unsigned> BBNumbers;
267 /// Lazily compute the number of predecessors a block has.
268 DenseMap<const BasicBlock *, unsigned> BBNumPreds;
271 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
272 AliasSetTracker *AST, AssumptionCache *AC)
273 : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
274 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
280 void RemoveFromAllocasList(unsigned &AllocaIdx) {
281 Allocas[AllocaIdx] = Allocas.back();
286 unsigned getNumPreds(const BasicBlock *BB) {
287 unsigned &NP = BBNumPreds[BB];
289 NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
293 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
294 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
295 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
296 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
297 RenamePassData::ValVector &IncVals,
298 std::vector<RenamePassData> &Worklist);
299 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
302 } // end of anonymous namespace
304 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
305 // Knowing that this alloca is promotable, we know that it's safe to kill all
306 // instructions except for load and store.
308 for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
309 Instruction *I = cast<Instruction>(*UI);
311 if (isa<LoadInst>(I) || isa<StoreInst>(I))
314 if (!I->getType()->isVoidTy()) {
315 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
316 // Follow the use/def chain to erase them now instead of leaving it for
317 // dead code elimination later.
318 for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
319 Instruction *Inst = cast<Instruction>(*UUI);
321 Inst->eraseFromParent();
324 I->eraseFromParent();
328 /// \brief Rewrite as many loads as possible given a single store.
330 /// When there is only a single store, we can use the domtree to trivially
331 /// replace all of the dominated loads with the stored value. Do so, and return
332 /// true if this has successfully promoted the alloca entirely. If this returns
333 /// false there were some loads which were not dominated by the single store
334 /// and thus must be phi-ed with undef. We fall back to the standard alloca
335 /// promotion algorithm in that case.
336 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
339 AliasSetTracker *AST) {
340 StoreInst *OnlyStore = Info.OnlyStore;
341 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
342 BasicBlock *StoreBB = OnlyStore->getParent();
345 // Clear out UsingBlocks. We will reconstruct it here if needed.
346 Info.UsingBlocks.clear();
348 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
349 Instruction *UserInst = cast<Instruction>(*UI++);
350 if (!isa<LoadInst>(UserInst)) {
351 assert(UserInst == OnlyStore && "Should only have load/stores");
354 LoadInst *LI = cast<LoadInst>(UserInst);
356 // Okay, if we have a load from the alloca, we want to replace it with the
357 // only value stored to the alloca. We can do this if the value is
358 // dominated by the store. If not, we use the rest of the mem2reg machinery
359 // to insert the phi nodes as needed.
360 if (!StoringGlobalVal) { // Non-instructions are always dominated.
361 if (LI->getParent() == StoreBB) {
362 // If we have a use that is in the same block as the store, compare the
363 // indices of the two instructions to see which one came first. If the
364 // load came before the store, we can't handle it.
365 if (StoreIndex == -1)
366 StoreIndex = LBI.getInstructionIndex(OnlyStore);
368 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
369 // Can't handle this load, bail out.
370 Info.UsingBlocks.push_back(StoreBB);
374 } else if (LI->getParent() != StoreBB &&
375 !DT.dominates(StoreBB, LI->getParent())) {
376 // If the load and store are in different blocks, use BB dominance to
377 // check their relationships. If the store doesn't dom the use, bail
379 Info.UsingBlocks.push_back(LI->getParent());
384 // Otherwise, we *can* safely rewrite this load.
385 Value *ReplVal = OnlyStore->getOperand(0);
386 // If the replacement value is the load, this must occur in unreachable
389 ReplVal = UndefValue::get(LI->getType());
390 LI->replaceAllUsesWith(ReplVal);
391 if (AST && LI->getType()->isPointerTy())
392 AST->deleteValue(LI);
393 LI->eraseFromParent();
397 // Finally, after the scan, check to see if the store is all that is left.
398 if (!Info.UsingBlocks.empty())
399 return false; // If not, we'll have to fall back for the remainder.
401 // Record debuginfo for the store and remove the declaration's
403 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
404 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
405 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
406 DDI->eraseFromParent();
407 LBI.deleteValue(DDI);
409 // Remove the (now dead) store and alloca.
410 Info.OnlyStore->eraseFromParent();
411 LBI.deleteValue(Info.OnlyStore);
414 AST->deleteValue(AI);
415 AI->eraseFromParent();
420 /// Many allocas are only used within a single basic block. If this is the
421 /// case, avoid traversing the CFG and inserting a lot of potentially useless
422 /// PHI nodes by just performing a single linear pass over the basic block
423 /// using the Alloca.
425 /// If we cannot promote this alloca (because it is read before it is written),
426 /// return false. This is necessary in cases where, due to control flow, the
427 /// alloca is undefined only on some control flow paths. e.g. code like
428 /// this is correct in LLVM IR:
429 /// // A is an alloca with no stores so far
432 /// if (!first_iteration)
436 static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
438 AliasSetTracker *AST) {
439 // The trickiest case to handle is when we have large blocks. Because of this,
440 // this code is optimized assuming that large blocks happen. This does not
441 // significantly pessimize the small block case. This uses LargeBlockInfo to
442 // make it efficient to get the index of various operations in the block.
444 // Walk the use-def list of the alloca, getting the locations of all stores.
445 typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
446 StoresByIndexTy StoresByIndex;
448 for (User *U : AI->users())
449 if (StoreInst *SI = dyn_cast<StoreInst>(U))
450 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
452 // Sort the stores by their index, making it efficient to do a lookup with a
454 std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
456 // Walk all of the loads from this alloca, replacing them with the nearest
457 // store above them, if any.
458 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
459 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
463 unsigned LoadIdx = LBI.getInstructionIndex(LI);
465 // Find the nearest store that has a lower index than this load.
466 StoresByIndexTy::iterator I =
467 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
468 std::make_pair(LoadIdx,
469 static_cast<StoreInst *>(nullptr)),
471 if (I == StoresByIndex.begin()) {
472 if (StoresByIndex.empty())
473 // If there are no stores, the load takes the undef value.
474 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
476 // There is no store before this load, bail out (load may be affected
477 // by the following stores - see main comment).
481 // Otherwise, there was a store before this load, the load takes its value.
482 LI->replaceAllUsesWith(std::prev(I)->second->getOperand(0));
484 if (AST && LI->getType()->isPointerTy())
485 AST->deleteValue(LI);
486 LI->eraseFromParent();
490 // Remove the (now dead) stores and alloca.
491 while (!AI->use_empty()) {
492 StoreInst *SI = cast<StoreInst>(AI->user_back());
493 // Record debuginfo for the store before removing it.
494 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
495 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
496 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
498 SI->eraseFromParent();
503 AST->deleteValue(AI);
504 AI->eraseFromParent();
507 // The alloca's debuginfo can be removed as well.
508 if (DbgDeclareInst *DDI = Info.DbgDeclare) {
509 DDI->eraseFromParent();
510 LBI.deleteValue(DDI);
517 void PromoteMem2Reg::run() {
518 Function &F = *DT.getRoot()->getParent();
521 PointerAllocaValues.resize(Allocas.size());
522 AllocaDbgDeclares.resize(Allocas.size());
526 IDFCalculator IDF(DT);
528 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
529 AllocaInst *AI = Allocas[AllocaNum];
531 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
532 assert(AI->getParent()->getParent() == &F &&
533 "All allocas should be in the same function, which is same as DF!");
535 removeLifetimeIntrinsicUsers(AI);
537 if (AI->use_empty()) {
538 // If there are no uses of the alloca, just delete it now.
540 AST->deleteValue(AI);
541 AI->eraseFromParent();
543 // Remove the alloca from the Allocas list, since it has been processed
544 RemoveFromAllocasList(AllocaNum);
549 // Calculate the set of read and write-locations for each alloca. This is
550 // analogous to finding the 'uses' and 'definitions' of each variable.
551 Info.AnalyzeAlloca(AI);
553 // If there is only a single store to this value, replace any loads of
554 // it that are directly dominated by the definition with the value stored.
555 if (Info.DefiningBlocks.size() == 1) {
556 if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
557 // The alloca has been processed, move on.
558 RemoveFromAllocasList(AllocaNum);
564 // If the alloca is only read and written in one basic block, just perform a
565 // linear sweep over the block to eliminate it.
566 if (Info.OnlyUsedInOneBlock &&
567 promoteSingleBlockAlloca(AI, Info, LBI, AST)) {
568 // The alloca has been processed, move on.
569 RemoveFromAllocasList(AllocaNum);
573 // If we haven't computed a numbering for the BB's in the function, do so
575 if (BBNumbers.empty()) {
578 BBNumbers[&BB] = ID++;
581 // If we have an AST to keep updated, remember some pointer value that is
582 // stored into the alloca.
584 PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
586 // Remember the dbg.declare intrinsic describing this alloca, if any.
588 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
590 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
591 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
593 // At this point, we're committed to promoting the alloca using IDF's, and
594 // the standard SSA construction algorithm. Determine which blocks need PHI
595 // nodes and see if we can optimize out some work by avoiding insertion of
599 // Unique the set of defining blocks for efficient lookup.
600 SmallPtrSet<BasicBlock *, 32> DefBlocks;
601 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
603 // Determine which blocks the value is live in. These are blocks which lead
605 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
606 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
608 // At this point, we're committed to promoting the alloca using IDF's, and
609 // the standard SSA construction algorithm. Determine which blocks need phi
610 // nodes and see if we can optimize out some work by avoiding insertion of
612 IDF.setLiveInBlocks(LiveInBlocks);
613 IDF.setDefiningBlocks(DefBlocks);
614 SmallVector<BasicBlock *, 32> PHIBlocks;
615 IDF.calculate(PHIBlocks);
616 if (PHIBlocks.size() > 1)
617 std::sort(PHIBlocks.begin(), PHIBlocks.end(),
618 [this](BasicBlock *A, BasicBlock *B) {
619 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
622 unsigned CurrentVersion = 0;
623 for (unsigned i = 0, e = PHIBlocks.size(); i != e; ++i)
624 QueuePhiNode(PHIBlocks[i], AllocaNum, CurrentVersion);
628 return; // All of the allocas must have been trivial!
632 // Set the incoming values for the basic block to be null values for all of
633 // the alloca's. We do this in case there is a load of a value that has not
634 // been stored yet. In this case, it will get this null value.
636 RenamePassData::ValVector Values(Allocas.size());
637 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
638 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
640 // Walks all basic blocks in the function performing the SSA rename algorithm
641 // and inserting the phi nodes we marked as necessary
643 std::vector<RenamePassData> RenamePassWorkList;
644 RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values));
647 RPD.swap(RenamePassWorkList.back());
648 RenamePassWorkList.pop_back();
649 // RenamePass may add new worklist entries.
650 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
651 } while (!RenamePassWorkList.empty());
653 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
656 // Remove the allocas themselves from the function.
657 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
658 Instruction *A = Allocas[i];
660 // If there are any uses of the alloca instructions left, they must be in
661 // unreachable basic blocks that were not processed by walking the dominator
662 // tree. Just delete the users now.
664 A->replaceAllUsesWith(UndefValue::get(A->getType()));
667 A->eraseFromParent();
670 const DataLayout &DL = F.getParent()->getDataLayout();
672 // Remove alloca's dbg.declare instrinsics from the function.
673 for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
674 if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
675 DDI->eraseFromParent();
677 // Loop over all of the PHI nodes and see if there are any that we can get
678 // rid of because they merge all of the same incoming values. This can
679 // happen due to undef values coming into the PHI nodes. This process is
680 // iterative, because eliminating one PHI node can cause others to be removed.
681 bool EliminatedAPHI = true;
682 while (EliminatedAPHI) {
683 EliminatedAPHI = false;
685 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
686 // simplify and RAUW them as we go. If it was not, we could add uses to
687 // the values we replace with in a non-deterministic order, thus creating
688 // non-deterministic def->use chains.
689 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
690 I = NewPhiNodes.begin(),
691 E = NewPhiNodes.end();
693 PHINode *PN = I->second;
695 // If this PHI node merges one value and/or undefs, get the value.
696 if (Value *V = SimplifyInstruction(PN, DL, nullptr, &DT, AC)) {
697 if (AST && PN->getType()->isPointerTy())
698 AST->deleteValue(PN);
699 PN->replaceAllUsesWith(V);
700 PN->eraseFromParent();
701 NewPhiNodes.erase(I++);
702 EliminatedAPHI = true;
709 // At this point, the renamer has added entries to PHI nodes for all reachable
710 // code. Unfortunately, there may be unreachable blocks which the renamer
711 // hasn't traversed. If this is the case, the PHI nodes may not
712 // have incoming values for all predecessors. Loop over all PHI nodes we have
713 // created, inserting undef values if they are missing any incoming values.
715 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
716 I = NewPhiNodes.begin(),
717 E = NewPhiNodes.end();
719 // We want to do this once per basic block. As such, only process a block
720 // when we find the PHI that is the first entry in the block.
721 PHINode *SomePHI = I->second;
722 BasicBlock *BB = SomePHI->getParent();
723 if (&BB->front() != SomePHI)
726 // Only do work here if there the PHI nodes are missing incoming values. We
727 // know that all PHI nodes that were inserted in a block will have the same
728 // number of incoming values, so we can just check any of them.
729 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
732 // Get the preds for BB.
733 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
735 // Ok, now we know that all of the PHI nodes are missing entries for some
736 // basic blocks. Start by sorting the incoming predecessors for efficient
738 std::sort(Preds.begin(), Preds.end());
740 // Now we loop through all BB's which have entries in SomePHI and remove
741 // them from the Preds list.
742 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
743 // Do a log(n) search of the Preds list for the entry we want.
744 SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
745 Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
746 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
747 "PHI node has entry for a block which is not a predecessor!");
753 // At this point, the blocks left in the preds list must have dummy
754 // entries inserted into every PHI nodes for the block. Update all the phi
755 // nodes in this block that we are inserting (there could be phis before
757 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
758 BasicBlock::iterator BBI = BB->begin();
759 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
760 SomePHI->getNumIncomingValues() == NumBadPreds) {
761 Value *UndefVal = UndefValue::get(SomePHI->getType());
762 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
763 SomePHI->addIncoming(UndefVal, Preds[pred]);
770 /// \brief Determine which blocks the value is live in.
772 /// These are blocks which lead to uses. Knowing this allows us to avoid
773 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
774 /// inserted phi nodes would be dead).
775 void PromoteMem2Reg::ComputeLiveInBlocks(
776 AllocaInst *AI, AllocaInfo &Info,
777 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
778 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
780 // To determine liveness, we must iterate through the predecessors of blocks
781 // where the def is live. Blocks are added to the worklist if we need to
782 // check their predecessors. Start with all the using blocks.
783 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
784 Info.UsingBlocks.end());
786 // If any of the using blocks is also a definition block, check to see if the
787 // definition occurs before or after the use. If it happens before the use,
788 // the value isn't really live-in.
789 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
790 BasicBlock *BB = LiveInBlockWorklist[i];
791 if (!DefBlocks.count(BB))
794 // Okay, this is a block that both uses and defines the value. If the first
795 // reference to the alloca is a def (store), then we know it isn't live-in.
796 for (BasicBlock::iterator I = BB->begin();; ++I) {
797 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
798 if (SI->getOperand(1) != AI)
801 // We found a store to the alloca before a load. The alloca is not
802 // actually live-in here.
803 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
804 LiveInBlockWorklist.pop_back();
809 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
810 if (LI->getOperand(0) != AI)
813 // Okay, we found a load before a store to the alloca. It is actually
814 // live into this block.
820 // Now that we have a set of blocks where the phi is live-in, recursively add
821 // their predecessors until we find the full region the value is live.
822 while (!LiveInBlockWorklist.empty()) {
823 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
825 // The block really is live in here, insert it into the set. If already in
826 // the set, then it has already been processed.
827 if (!LiveInBlocks.insert(BB).second)
830 // Since the value is live into BB, it is either defined in a predecessor or
831 // live into it to. Add the preds to the worklist unless they are a
833 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
836 // The value is not live into a predecessor if it defines the value.
837 if (DefBlocks.count(P))
840 // Otherwise it is, add to the worklist.
841 LiveInBlockWorklist.push_back(P);
846 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
848 /// Returns true if there wasn't already a phi-node for that variable
849 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
851 // Look up the basic-block in question.
852 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
854 // If the BB already has a phi node added for the i'th alloca then we're done!
858 // Create a PhiNode using the dereferenced type... and add the phi-node to the
860 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
861 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
864 PhiToAllocaMap[PN] = AllocaNo;
866 if (AST && PN->getType()->isPointerTy())
867 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
872 /// \brief Recursively traverse the CFG of the function, renaming loads and
873 /// stores to the allocas which we are promoting.
875 /// IncomingVals indicates what value each Alloca contains on exit from the
876 /// predecessor block Pred.
877 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
878 RenamePassData::ValVector &IncomingVals,
879 std::vector<RenamePassData> &Worklist) {
881 // If we are inserting any phi nodes into this BB, they will already be in the
883 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
884 // If we have PHI nodes to update, compute the number of edges from Pred to
886 if (PhiToAllocaMap.count(APN)) {
887 // We want to be able to distinguish between PHI nodes being inserted by
888 // this invocation of mem2reg from those phi nodes that already existed in
889 // the IR before mem2reg was run. We determine that APN is being inserted
890 // because it is missing incoming edges. All other PHI nodes being
891 // inserted by this pass of mem2reg will have the same number of incoming
892 // operands so far. Remember this count.
893 unsigned NewPHINumOperands = APN->getNumOperands();
895 unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
896 assert(NumEdges && "Must be at least one edge from Pred to BB!");
898 // Add entries for all the phis.
899 BasicBlock::iterator PNI = BB->begin();
901 unsigned AllocaNo = PhiToAllocaMap[APN];
903 // Add N incoming values to the PHI node.
904 for (unsigned i = 0; i != NumEdges; ++i)
905 APN->addIncoming(IncomingVals[AllocaNo], Pred);
907 // The currently active variable for this block is now the PHI.
908 IncomingVals[AllocaNo] = APN;
910 // Get the next phi node.
912 APN = dyn_cast<PHINode>(PNI);
916 // Verify that it is missing entries. If not, it is not being inserted
917 // by this mem2reg invocation so we want to ignore it.
918 } while (APN->getNumOperands() == NewPHINumOperands);
922 // Don't revisit blocks.
923 if (!Visited.insert(BB).second)
926 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
927 Instruction *I = &*II++; // get the instruction, increment iterator
929 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
930 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
934 DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
935 if (AI == AllocaLookup.end())
938 Value *V = IncomingVals[AI->second];
940 // Anything using the load now uses the current value.
941 LI->replaceAllUsesWith(V);
942 if (AST && LI->getType()->isPointerTy())
943 AST->deleteValue(LI);
944 BB->getInstList().erase(LI);
945 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
946 // Delete this instruction and mark the name as the current holder of the
948 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
952 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
953 if (ai == AllocaLookup.end())
956 // what value were we writing?
957 IncomingVals[ai->second] = SI->getOperand(0);
958 // Record debuginfo for the store before removing it.
959 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
960 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
961 BB->getInstList().erase(SI);
965 // 'Recurse' to our successors.
966 succ_iterator I = succ_begin(BB), E = succ_end(BB);
970 // Keep track of the successors so we don't visit the same successor twice
971 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
973 // Handle the first successor without using the worklist.
974 VisitedSuccs.insert(*I);
980 if (VisitedSuccs.insert(*I).second)
981 Worklist.emplace_back(*I, Pred, IncomingVals);
986 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
987 AliasSetTracker *AST, AssumptionCache *AC) {
988 // If there is nothing to do, bail out...
992 PromoteMem2Reg(Allocas, DT, AST, AC).run();