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/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/TinyPtrVector.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AssumptionCache.h"
27 #include "llvm/Analysis/InstructionSimplify.h"
28 #include "llvm/Analysis/IteratedDominanceFrontier.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DIBuilder.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/InstrTypes.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/User.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
58 #define DEBUG_TYPE "mem2reg"
60 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
61 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
62 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
63 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
65 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
66 // FIXME: If the memory unit is of pointer or integer type, we can permit
67 // assignments to subsections of the memory unit.
68 unsigned AS = AI->getType()->getAddressSpace();
70 // Only allow direct and non-volatile loads and stores...
71 for (const User *U : AI->users()) {
72 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
73 // Note that atomic loads can be transformed; atomic semantics do
74 // not have any meaning for a local alloca.
77 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
78 if (SI->getOperand(0) == AI)
79 return false; // Don't allow a store OF the AI, only INTO the AI.
80 // Note that atomic stores can be transformed; atomic semantics do
81 // not have any meaning for a local alloca.
84 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
85 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
86 II->getIntrinsicID() != Intrinsic::lifetime_end)
88 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
89 if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
91 if (!onlyUsedByLifetimeMarkers(BCI))
93 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
94 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
96 if (!GEPI->hasAllZeroIndices())
98 if (!onlyUsedByLifetimeMarkers(GEPI))
111 SmallVector<BasicBlock *, 32> DefiningBlocks;
112 SmallVector<BasicBlock *, 32> UsingBlocks;
114 StoreInst *OnlyStore;
115 BasicBlock *OnlyBlock;
116 bool OnlyUsedInOneBlock;
118 Value *AllocaPointerVal;
119 TinyPtrVector<DbgInfoIntrinsic *> DbgDeclares;
122 DefiningBlocks.clear();
126 OnlyUsedInOneBlock = true;
127 AllocaPointerVal = nullptr;
131 /// Scan the uses of the specified alloca, filling in the AllocaInfo used
132 /// by the rest of the pass to reason about the uses of this alloca.
133 void AnalyzeAlloca(AllocaInst *AI) {
136 // As we scan the uses of the alloca instruction, keep track of stores,
137 // and decide whether all of the loads and stores to the alloca are within
138 // the same basic block.
139 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
140 Instruction *User = cast<Instruction>(*UI++);
142 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
143 // Remember the basic blocks which define new values for the alloca
144 DefiningBlocks.push_back(SI->getParent());
145 AllocaPointerVal = SI->getOperand(0);
148 LoadInst *LI = cast<LoadInst>(User);
149 // Otherwise it must be a load instruction, keep track of variable
151 UsingBlocks.push_back(LI->getParent());
152 AllocaPointerVal = LI;
155 if (OnlyUsedInOneBlock) {
157 OnlyBlock = User->getParent();
158 else if (OnlyBlock != User->getParent())
159 OnlyUsedInOneBlock = false;
163 DbgDeclares = FindDbgAddrUses(AI);
167 /// Data package used by RenamePass().
168 struct RenamePassData {
169 using ValVector = std::vector<Value *>;
170 using LocationVector = std::vector<DebugLoc>;
172 RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
173 : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
178 LocationVector Locations;
181 /// This assigns and keeps a per-bb relative ordering of load/store
182 /// instructions in the block that directly load or store an alloca.
184 /// This functionality is important because it avoids scanning large basic
185 /// blocks multiple times when promoting many allocas in the same block.
186 class LargeBlockInfo {
187 /// For each instruction that we track, keep the index of the
190 /// The index starts out as the number of the instruction from the start of
192 DenseMap<const Instruction *, unsigned> InstNumbers;
196 /// This code only looks at accesses to allocas.
197 static bool isInterestingInstruction(const Instruction *I) {
198 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
199 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
202 /// Get or calculate the index of the specified instruction.
203 unsigned getInstructionIndex(const Instruction *I) {
204 assert(isInterestingInstruction(I) &&
205 "Not a load/store to/from an alloca?");
207 // If we already have this instruction number, return it.
208 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
209 if (It != InstNumbers.end())
212 // Scan the whole block to get the instruction. This accumulates
213 // information for every interesting instruction in the block, in order to
214 // avoid gratuitus rescans.
215 const BasicBlock *BB = I->getParent();
217 for (const Instruction &BBI : *BB)
218 if (isInterestingInstruction(&BBI))
219 InstNumbers[&BBI] = InstNo++;
220 It = InstNumbers.find(I);
222 assert(It != InstNumbers.end() && "Didn't insert instruction?");
226 void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
228 void clear() { InstNumbers.clear(); }
231 struct PromoteMem2Reg {
232 /// The alloca instructions being promoted.
233 std::vector<AllocaInst *> Allocas;
238 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
241 const SimplifyQuery SQ;
243 /// Reverse mapping of Allocas.
244 DenseMap<AllocaInst *, unsigned> AllocaLookup;
246 /// The PhiNodes we're adding.
248 /// That map is used to simplify some Phi nodes as we iterate over it, so
249 /// it should have deterministic iterators. We could use a MapVector, but
250 /// since we already maintain a map from BasicBlock* to a stable numbering
251 /// (BBNumbers), the DenseMap is more efficient (also supports removal).
252 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
254 /// For each PHI node, keep track of which entry in Allocas it corresponds
256 DenseMap<PHINode *, unsigned> PhiToAllocaMap;
258 /// If we are updating an AliasSetTracker, then for each alloca that is of
259 /// pointer type, we keep track of what to copyValue to the inserted PHI
261 std::vector<Value *> PointerAllocaValues;
263 /// For each alloca, we keep track of the dbg.declare intrinsic that
264 /// describes it, if any, so that we can convert it to a dbg.value
265 /// intrinsic if the alloca gets promoted.
266 SmallVector<TinyPtrVector<DbgInfoIntrinsic *>, 8> AllocaDbgDeclares;
268 /// The set of basic blocks the renamer has already visited.
269 SmallPtrSet<BasicBlock *, 16> Visited;
271 /// Contains a stable numbering of basic blocks to avoid non-determinstic
273 DenseMap<BasicBlock *, unsigned> BBNumbers;
275 /// Lazily compute the number of predecessors a block has.
276 DenseMap<const BasicBlock *, unsigned> BBNumPreds;
279 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
281 : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
282 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
283 AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
289 void RemoveFromAllocasList(unsigned &AllocaIdx) {
290 Allocas[AllocaIdx] = Allocas.back();
295 unsigned getNumPreds(const BasicBlock *BB) {
296 unsigned &NP = BBNumPreds[BB];
298 NP = pred_size(BB) + 1;
302 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
303 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
304 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
305 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
306 RenamePassData::ValVector &IncVals,
307 RenamePassData::LocationVector &IncLocs,
308 std::vector<RenamePassData> &Worklist);
309 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
312 } // end anonymous namespace
314 /// Given a LoadInst LI this adds assume(LI != null) after it.
315 static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
316 Function *AssumeIntrinsic =
317 Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
318 ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
319 Constant::getNullValue(LI->getType()));
320 LoadNotNull->insertAfter(LI);
321 CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
322 CI->insertAfter(LoadNotNull);
323 AC->registerAssumption(CI);
326 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
327 // Knowing that this alloca is promotable, we know that it's safe to kill all
328 // instructions except for load and store.
330 for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
331 Instruction *I = cast<Instruction>(*UI);
333 if (isa<LoadInst>(I) || isa<StoreInst>(I))
336 if (!I->getType()->isVoidTy()) {
337 // The only users of this bitcast/GEP instruction are lifetime intrinsics.
338 // Follow the use/def chain to erase them now instead of leaving it for
339 // dead code elimination later.
340 for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
341 Instruction *Inst = cast<Instruction>(*UUI);
343 Inst->eraseFromParent();
346 I->eraseFromParent();
350 /// Rewrite as many loads as possible given a single store.
352 /// When there is only a single store, we can use the domtree to trivially
353 /// replace all of the dominated loads with the stored value. Do so, and return
354 /// true if this has successfully promoted the alloca entirely. If this returns
355 /// false there were some loads which were not dominated by the single store
356 /// and thus must be phi-ed with undef. We fall back to the standard alloca
357 /// promotion algorithm in that case.
358 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
359 LargeBlockInfo &LBI, const DataLayout &DL,
360 DominatorTree &DT, AssumptionCache *AC) {
361 StoreInst *OnlyStore = Info.OnlyStore;
362 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
363 BasicBlock *StoreBB = OnlyStore->getParent();
366 // Clear out UsingBlocks. We will reconstruct it here if needed.
367 Info.UsingBlocks.clear();
369 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
370 Instruction *UserInst = cast<Instruction>(*UI++);
371 if (!isa<LoadInst>(UserInst)) {
372 assert(UserInst == OnlyStore && "Should only have load/stores");
375 LoadInst *LI = cast<LoadInst>(UserInst);
377 // Okay, if we have a load from the alloca, we want to replace it with the
378 // only value stored to the alloca. We can do this if the value is
379 // dominated by the store. If not, we use the rest of the mem2reg machinery
380 // to insert the phi nodes as needed.
381 if (!StoringGlobalVal) { // Non-instructions are always dominated.
382 if (LI->getParent() == StoreBB) {
383 // If we have a use that is in the same block as the store, compare the
384 // indices of the two instructions to see which one came first. If the
385 // load came before the store, we can't handle it.
386 if (StoreIndex == -1)
387 StoreIndex = LBI.getInstructionIndex(OnlyStore);
389 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
390 // Can't handle this load, bail out.
391 Info.UsingBlocks.push_back(StoreBB);
394 } else if (LI->getParent() != StoreBB &&
395 !DT.dominates(StoreBB, LI->getParent())) {
396 // If the load and store are in different blocks, use BB dominance to
397 // check their relationships. If the store doesn't dom the use, bail
399 Info.UsingBlocks.push_back(LI->getParent());
404 // Otherwise, we *can* safely rewrite this load.
405 Value *ReplVal = OnlyStore->getOperand(0);
406 // If the replacement value is the load, this must occur in unreachable
409 ReplVal = UndefValue::get(LI->getType());
411 // If the load was marked as nonnull we don't want to lose
412 // that information when we erase this Load. So we preserve
413 // it with an assume.
414 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
415 !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
416 addAssumeNonNull(AC, LI);
418 LI->replaceAllUsesWith(ReplVal);
419 LI->eraseFromParent();
423 // Finally, after the scan, check to see if the store is all that is left.
424 if (!Info.UsingBlocks.empty())
425 return false; // If not, we'll have to fall back for the remainder.
427 // Record debuginfo for the store and remove the declaration's
429 for (DbgInfoIntrinsic *DII : Info.DbgDeclares) {
430 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
431 ConvertDebugDeclareToDebugValue(DII, Info.OnlyStore, DIB);
432 DII->eraseFromParent();
433 LBI.deleteValue(DII);
435 // Remove the (now dead) store and alloca.
436 Info.OnlyStore->eraseFromParent();
437 LBI.deleteValue(Info.OnlyStore);
439 AI->eraseFromParent();
444 /// Many allocas are only used within a single basic block. If this is the
445 /// case, avoid traversing the CFG and inserting a lot of potentially useless
446 /// PHI nodes by just performing a single linear pass over the basic block
447 /// using the Alloca.
449 /// If we cannot promote this alloca (because it is read before it is written),
450 /// return false. This is necessary in cases where, due to control flow, the
451 /// alloca is undefined only on some control flow paths. e.g. code like
452 /// this is correct in LLVM IR:
453 /// // A is an alloca with no stores so far
456 /// if (!first_iteration)
460 static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
462 const DataLayout &DL,
464 AssumptionCache *AC) {
465 // The trickiest case to handle is when we have large blocks. Because of this,
466 // this code is optimized assuming that large blocks happen. This does not
467 // significantly pessimize the small block case. This uses LargeBlockInfo to
468 // make it efficient to get the index of various operations in the block.
470 // Walk the use-def list of the alloca, getting the locations of all stores.
471 using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
472 StoresByIndexTy StoresByIndex;
474 for (User *U : AI->users())
475 if (StoreInst *SI = dyn_cast<StoreInst>(U))
476 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
478 // Sort the stores by their index, making it efficient to do a lookup with a
480 llvm::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
482 // Walk all of the loads from this alloca, replacing them with the nearest
483 // store above them, if any.
484 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
485 LoadInst *LI = dyn_cast<LoadInst>(*UI++);
489 unsigned LoadIdx = LBI.getInstructionIndex(LI);
491 // Find the nearest store that has a lower index than this load.
492 StoresByIndexTy::iterator I =
493 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
494 std::make_pair(LoadIdx,
495 static_cast<StoreInst *>(nullptr)),
497 if (I == StoresByIndex.begin()) {
498 if (StoresByIndex.empty())
499 // If there are no stores, the load takes the undef value.
500 LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
502 // There is no store before this load, bail out (load may be affected
503 // by the following stores - see main comment).
506 // Otherwise, there was a store before this load, the load takes its value.
507 // Note, if the load was marked as nonnull we don't want to lose that
508 // information when we erase it. So we preserve it with an assume.
509 Value *ReplVal = std::prev(I)->second->getOperand(0);
510 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
511 !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
512 addAssumeNonNull(AC, LI);
514 // If the replacement value is the load, this must occur in unreachable
517 ReplVal = UndefValue::get(LI->getType());
519 LI->replaceAllUsesWith(ReplVal);
522 LI->eraseFromParent();
526 // Remove the (now dead) stores and alloca.
527 while (!AI->use_empty()) {
528 StoreInst *SI = cast<StoreInst>(AI->user_back());
529 // Record debuginfo for the store before removing it.
530 for (DbgInfoIntrinsic *DII : Info.DbgDeclares) {
531 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
532 ConvertDebugDeclareToDebugValue(DII, SI, DIB);
534 SI->eraseFromParent();
538 AI->eraseFromParent();
541 // The alloca's debuginfo can be removed as well.
542 for (DbgInfoIntrinsic *DII : Info.DbgDeclares) {
543 DII->eraseFromParent();
544 LBI.deleteValue(DII);
551 void PromoteMem2Reg::run() {
552 Function &F = *DT.getRoot()->getParent();
554 AllocaDbgDeclares.resize(Allocas.size());
558 ForwardIDFCalculator IDF(DT);
560 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
561 AllocaInst *AI = Allocas[AllocaNum];
563 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
564 assert(AI->getParent()->getParent() == &F &&
565 "All allocas should be in the same function, which is same as DF!");
567 removeLifetimeIntrinsicUsers(AI);
569 if (AI->use_empty()) {
570 // If there are no uses of the alloca, just delete it now.
571 AI->eraseFromParent();
573 // Remove the alloca from the Allocas list, since it has been processed
574 RemoveFromAllocasList(AllocaNum);
579 // Calculate the set of read and write-locations for each alloca. This is
580 // analogous to finding the 'uses' and 'definitions' of each variable.
581 Info.AnalyzeAlloca(AI);
583 // If there is only a single store to this value, replace any loads of
584 // it that are directly dominated by the definition with the value stored.
585 if (Info.DefiningBlocks.size() == 1) {
586 if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
587 // The alloca has been processed, move on.
588 RemoveFromAllocasList(AllocaNum);
594 // If the alloca is only read and written in one basic block, just perform a
595 // linear sweep over the block to eliminate it.
596 if (Info.OnlyUsedInOneBlock &&
597 promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
598 // The alloca has been processed, move on.
599 RemoveFromAllocasList(AllocaNum);
603 // If we haven't computed a numbering for the BB's in the function, do so
605 if (BBNumbers.empty()) {
608 BBNumbers[&BB] = ID++;
611 // Remember the dbg.declare intrinsic describing this alloca, if any.
612 if (!Info.DbgDeclares.empty())
613 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclares;
615 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
616 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
618 // At this point, we're committed to promoting the alloca using IDF's, and
619 // the standard SSA construction algorithm. Determine which blocks need PHI
620 // nodes and see if we can optimize out some work by avoiding insertion of
623 // Unique the set of defining blocks for efficient lookup.
624 SmallPtrSet<BasicBlock *, 32> DefBlocks;
625 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
627 // Determine which blocks the value is live in. These are blocks which lead
629 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
630 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
632 // At this point, we're committed to promoting the alloca using IDF's, and
633 // the standard SSA construction algorithm. Determine which blocks need phi
634 // nodes and see if we can optimize out some work by avoiding insertion of
636 IDF.setLiveInBlocks(LiveInBlocks);
637 IDF.setDefiningBlocks(DefBlocks);
638 SmallVector<BasicBlock *, 32> PHIBlocks;
639 IDF.calculate(PHIBlocks);
640 if (PHIBlocks.size() > 1)
641 llvm::sort(PHIBlocks.begin(), PHIBlocks.end(),
642 [this](BasicBlock *A, BasicBlock *B) {
643 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
646 unsigned CurrentVersion = 0;
647 for (BasicBlock *BB : PHIBlocks)
648 QueuePhiNode(BB, AllocaNum, CurrentVersion);
652 return; // All of the allocas must have been trivial!
656 // Set the incoming values for the basic block to be null values for all of
657 // the alloca's. We do this in case there is a load of a value that has not
658 // been stored yet. In this case, it will get this null value.
659 RenamePassData::ValVector Values(Allocas.size());
660 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
661 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
663 // When handling debug info, treat all incoming values as if they have unknown
664 // locations until proven otherwise.
665 RenamePassData::LocationVector Locations(Allocas.size());
667 // Walks all basic blocks in the function performing the SSA rename algorithm
668 // and inserting the phi nodes we marked as necessary
669 std::vector<RenamePassData> RenamePassWorkList;
670 RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
671 std::move(Locations));
673 RenamePassData RPD = std::move(RenamePassWorkList.back());
674 RenamePassWorkList.pop_back();
675 // RenamePass may add new worklist entries.
676 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
677 } while (!RenamePassWorkList.empty());
679 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
682 // Remove the allocas themselves from the function.
683 for (Instruction *A : Allocas) {
684 // If there are any uses of the alloca instructions left, they must be in
685 // unreachable basic blocks that were not processed by walking the dominator
686 // tree. Just delete the users now.
688 A->replaceAllUsesWith(UndefValue::get(A->getType()));
689 A->eraseFromParent();
692 // Remove alloca's dbg.declare instrinsics from the function.
693 for (auto &Declares : AllocaDbgDeclares)
694 for (auto *DII : Declares)
695 DII->eraseFromParent();
697 // Loop over all of the PHI nodes and see if there are any that we can get
698 // rid of because they merge all of the same incoming values. This can
699 // happen due to undef values coming into the PHI nodes. This process is
700 // iterative, because eliminating one PHI node can cause others to be removed.
701 bool EliminatedAPHI = true;
702 while (EliminatedAPHI) {
703 EliminatedAPHI = false;
705 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
706 // simplify and RAUW them as we go. If it was not, we could add uses to
707 // the values we replace with in a non-deterministic order, thus creating
708 // non-deterministic def->use chains.
709 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
710 I = NewPhiNodes.begin(),
711 E = NewPhiNodes.end();
713 PHINode *PN = I->second;
715 // If this PHI node merges one value and/or undefs, get the value.
716 if (Value *V = SimplifyInstruction(PN, SQ)) {
717 PN->replaceAllUsesWith(V);
718 PN->eraseFromParent();
719 NewPhiNodes.erase(I++);
720 EliminatedAPHI = true;
727 // At this point, the renamer has added entries to PHI nodes for all reachable
728 // code. Unfortunately, there may be unreachable blocks which the renamer
729 // hasn't traversed. If this is the case, the PHI nodes may not
730 // have incoming values for all predecessors. Loop over all PHI nodes we have
731 // created, inserting undef values if they are missing any incoming values.
732 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
733 I = NewPhiNodes.begin(),
734 E = NewPhiNodes.end();
736 // We want to do this once per basic block. As such, only process a block
737 // when we find the PHI that is the first entry in the block.
738 PHINode *SomePHI = I->second;
739 BasicBlock *BB = SomePHI->getParent();
740 if (&BB->front() != SomePHI)
743 // Only do work here if there the PHI nodes are missing incoming values. We
744 // know that all PHI nodes that were inserted in a block will have the same
745 // number of incoming values, so we can just check any of them.
746 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
749 // Get the preds for BB.
750 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
752 // Ok, now we know that all of the PHI nodes are missing entries for some
753 // basic blocks. Start by sorting the incoming predecessors for efficient
755 llvm::sort(Preds.begin(), Preds.end());
757 // Now we loop through all BB's which have entries in SomePHI and remove
758 // them from the Preds list.
759 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
760 // Do a log(n) search of the Preds list for the entry we want.
761 SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
762 Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
763 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
764 "PHI node has entry for a block which is not a predecessor!");
770 // At this point, the blocks left in the preds list must have dummy
771 // entries inserted into every PHI nodes for the block. Update all the phi
772 // nodes in this block that we are inserting (there could be phis before
774 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
775 BasicBlock::iterator BBI = BB->begin();
776 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
777 SomePHI->getNumIncomingValues() == NumBadPreds) {
778 Value *UndefVal = UndefValue::get(SomePHI->getType());
779 for (BasicBlock *Pred : Preds)
780 SomePHI->addIncoming(UndefVal, Pred);
787 /// Determine which blocks the value is live in.
789 /// These are blocks which lead to uses. Knowing this allows us to avoid
790 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
791 /// inserted phi nodes would be dead).
792 void PromoteMem2Reg::ComputeLiveInBlocks(
793 AllocaInst *AI, AllocaInfo &Info,
794 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
795 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
796 // To determine liveness, we must iterate through the predecessors of blocks
797 // where the def is live. Blocks are added to the worklist if we need to
798 // check their predecessors. Start with all the using blocks.
799 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
800 Info.UsingBlocks.end());
802 // If any of the using blocks is also a definition block, check to see if the
803 // definition occurs before or after the use. If it happens before the use,
804 // the value isn't really live-in.
805 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
806 BasicBlock *BB = LiveInBlockWorklist[i];
807 if (!DefBlocks.count(BB))
810 // Okay, this is a block that both uses and defines the value. If the first
811 // reference to the alloca is a def (store), then we know it isn't live-in.
812 for (BasicBlock::iterator I = BB->begin();; ++I) {
813 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
814 if (SI->getOperand(1) != AI)
817 // We found a store to the alloca before a load. The alloca is not
818 // actually live-in here.
819 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
820 LiveInBlockWorklist.pop_back();
826 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
827 if (LI->getOperand(0) != AI)
830 // Okay, we found a load before a store to the alloca. It is actually
831 // live into this block.
837 // Now that we have a set of blocks where the phi is live-in, recursively add
838 // their predecessors until we find the full region the value is live.
839 while (!LiveInBlockWorklist.empty()) {
840 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
842 // The block really is live in here, insert it into the set. If already in
843 // the set, then it has already been processed.
844 if (!LiveInBlocks.insert(BB).second)
847 // Since the value is live into BB, it is either defined in a predecessor or
848 // live into it to. Add the preds to the worklist unless they are a
850 for (BasicBlock *P : predecessors(BB)) {
851 // The value is not live into a predecessor if it defines the value.
852 if (DefBlocks.count(P))
855 // Otherwise it is, add to the worklist.
856 LiveInBlockWorklist.push_back(P);
861 /// Queue a phi-node to be added to a basic-block for a specific Alloca.
863 /// Returns true if there wasn't already a phi-node for that variable
864 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
866 // Look up the basic-block in question.
867 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
869 // If the BB already has a phi node added for the i'th alloca then we're done!
873 // Create a PhiNode using the dereferenced type... and add the phi-node to the
875 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
876 Allocas[AllocaNo]->getName() + "." + Twine(Version++),
879 PhiToAllocaMap[PN] = AllocaNo;
883 /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
884 /// create a merged location incorporating \p DL, or to set \p DL directly.
885 static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
886 bool ApplyMergedLoc) {
888 PN->applyMergedLocation(PN->getDebugLoc(), DL);
893 /// Recursively traverse the CFG of the function, renaming loads and
894 /// stores to the allocas which we are promoting.
896 /// IncomingVals indicates what value each Alloca contains on exit from the
897 /// predecessor block Pred.
898 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
899 RenamePassData::ValVector &IncomingVals,
900 RenamePassData::LocationVector &IncomingLocs,
901 std::vector<RenamePassData> &Worklist) {
903 // If we are inserting any phi nodes into this BB, they will already be in the
905 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
906 // If we have PHI nodes to update, compute the number of edges from Pred to
908 if (PhiToAllocaMap.count(APN)) {
909 // We want to be able to distinguish between PHI nodes being inserted by
910 // this invocation of mem2reg from those phi nodes that already existed in
911 // the IR before mem2reg was run. We determine that APN is being inserted
912 // because it is missing incoming edges. All other PHI nodes being
913 // inserted by this pass of mem2reg will have the same number of incoming
914 // operands so far. Remember this count.
915 unsigned NewPHINumOperands = APN->getNumOperands();
917 unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
918 assert(NumEdges && "Must be at least one edge from Pred to BB!");
920 // Add entries for all the phis.
921 BasicBlock::iterator PNI = BB->begin();
923 unsigned AllocaNo = PhiToAllocaMap[APN];
925 // Update the location of the phi node.
926 updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
927 APN->getNumIncomingValues() > 0);
929 // Add N incoming values to the PHI node.
930 for (unsigned i = 0; i != NumEdges; ++i)
931 APN->addIncoming(IncomingVals[AllocaNo], Pred);
933 // The currently active variable for this block is now the PHI.
934 IncomingVals[AllocaNo] = APN;
935 for (DbgInfoIntrinsic *DII : AllocaDbgDeclares[AllocaNo])
936 ConvertDebugDeclareToDebugValue(DII, APN, DIB);
938 // Get the next phi node.
940 APN = dyn_cast<PHINode>(PNI);
944 // Verify that it is missing entries. If not, it is not being inserted
945 // by this mem2reg invocation so we want to ignore it.
946 } while (APN->getNumOperands() == NewPHINumOperands);
950 // Don't revisit blocks.
951 if (!Visited.insert(BB).second)
954 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
955 Instruction *I = &*II++; // get the instruction, increment iterator
957 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
958 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
962 DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
963 if (AI == AllocaLookup.end())
966 Value *V = IncomingVals[AI->second];
968 // If the load was marked as nonnull we don't want to lose
969 // that information when we erase this Load. So we preserve
970 // it with an assume.
971 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
972 !isKnownNonZero(V, SQ.DL, 0, AC, LI, &DT))
973 addAssumeNonNull(AC, LI);
975 // Anything using the load now uses the current value.
976 LI->replaceAllUsesWith(V);
977 BB->getInstList().erase(LI);
978 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
979 // Delete this instruction and mark the name as the current holder of the
981 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
985 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
986 if (ai == AllocaLookup.end())
989 // what value were we writing?
990 unsigned AllocaNo = ai->second;
991 IncomingVals[AllocaNo] = SI->getOperand(0);
993 // Record debuginfo for the store before removing it.
994 IncomingLocs[AllocaNo] = SI->getDebugLoc();
995 for (DbgInfoIntrinsic *DII : AllocaDbgDeclares[ai->second])
996 ConvertDebugDeclareToDebugValue(DII, SI, DIB);
997 BB->getInstList().erase(SI);
1001 // 'Recurse' to our successors.
1002 succ_iterator I = succ_begin(BB), E = succ_end(BB);
1006 // Keep track of the successors so we don't visit the same successor twice
1007 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1009 // Handle the first successor without using the worklist.
1010 VisitedSuccs.insert(*I);
1016 if (VisitedSuccs.insert(*I).second)
1017 Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
1022 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1023 AssumptionCache *AC) {
1024 // If there is nothing to do, bail out...
1025 if (Allocas.empty())
1028 PromoteMem2Reg(Allocas, DT, AC).run();