1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file promotes memory references to be register references.  It promotes
10 // alloca instructions which only have loads and stores as uses.  An alloca is
11 // transformed by using iterated dominator frontiers to place PHI nodes, then
12 // traversing the function in depth-first order to rewrite loads and stores as
13 // appropriate.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/TinyPtrVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/IteratedDominanceFrontier.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DIBuilder.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/User.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <iterator>
52 #include <utility>
53 #include <vector>
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "mem2reg"
58 
59 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
60 STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
61 STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
62 STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
63 
64 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
65   // FIXME: If the memory unit is of pointer or integer type, we can permit
66   // assignments to subsections of the memory unit.
67   unsigned AS = AI->getType()->getAddressSpace();
68 
69   // Only allow direct and non-volatile loads and stores...
70   for (const User *U : AI->users()) {
71     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
72       // Note that atomic loads can be transformed; atomic semantics do
73       // not have any meaning for a local alloca.
74       if (LI->isVolatile())
75         return false;
76     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
77       if (SI->getOperand(0) == AI)
78         return false; // Don't allow a store OF the AI, only INTO the AI.
79       // Note that atomic stores can be transformed; atomic semantics do
80       // not have any meaning for a local alloca.
81       if (SI->isVolatile())
82         return false;
83     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
84       if (!II->isLifetimeStartOrEnd())
85         return false;
86     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
87       if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
88         return false;
89       if (!onlyUsedByLifetimeMarkers(BCI))
90         return false;
91     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
92       if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
93         return false;
94       if (!GEPI->hasAllZeroIndices())
95         return false;
96       if (!onlyUsedByLifetimeMarkers(GEPI))
97         return false;
98     } else if (const AddrSpaceCastInst *ASCI = dyn_cast<AddrSpaceCastInst>(U)) {
99       if (!onlyUsedByLifetimeMarkers(ASCI))
100         return false;
101     } else {
102       return false;
103     }
104   }
105 
106   return true;
107 }
108 
109 namespace {
110 
111 struct AllocaInfo {
112   SmallVector<BasicBlock *, 32> DefiningBlocks;
113   SmallVector<BasicBlock *, 32> UsingBlocks;
114 
115   StoreInst *OnlyStore;
116   BasicBlock *OnlyBlock;
117   bool OnlyUsedInOneBlock;
118 
119   TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares;
120 
121   void clear() {
122     DefiningBlocks.clear();
123     UsingBlocks.clear();
124     OnlyStore = nullptr;
125     OnlyBlock = nullptr;
126     OnlyUsedInOneBlock = true;
127     DbgDeclares.clear();
128   }
129 
130   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
131   /// by the rest of the pass to reason about the uses of this alloca.
132   void AnalyzeAlloca(AllocaInst *AI) {
133     clear();
134 
135     // As we scan the uses of the alloca instruction, keep track of stores,
136     // and decide whether all of the loads and stores to the alloca are within
137     // the same basic block.
138     for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
139       Instruction *User = cast<Instruction>(*UI++);
140 
141       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
142         // Remember the basic blocks which define new values for the alloca
143         DefiningBlocks.push_back(SI->getParent());
144         OnlyStore = SI;
145       } else {
146         LoadInst *LI = cast<LoadInst>(User);
147         // Otherwise it must be a load instruction, keep track of variable
148         // reads.
149         UsingBlocks.push_back(LI->getParent());
150       }
151 
152       if (OnlyUsedInOneBlock) {
153         if (!OnlyBlock)
154           OnlyBlock = User->getParent();
155         else if (OnlyBlock != User->getParent())
156           OnlyUsedInOneBlock = false;
157       }
158     }
159 
160     DbgDeclares = FindDbgAddrUses(AI);
161   }
162 };
163 
164 /// Data package used by RenamePass().
165 struct RenamePassData {
166   using ValVector = std::vector<Value *>;
167   using LocationVector = std::vector<DebugLoc>;
168 
169   RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
170       : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
171 
172   BasicBlock *BB;
173   BasicBlock *Pred;
174   ValVector Values;
175   LocationVector Locations;
176 };
177 
178 /// This assigns and keeps a per-bb relative ordering of load/store
179 /// instructions in the block that directly load or store an alloca.
180 ///
181 /// This functionality is important because it avoids scanning large basic
182 /// blocks multiple times when promoting many allocas in the same block.
183 class LargeBlockInfo {
184   /// For each instruction that we track, keep the index of the
185   /// instruction.
186   ///
187   /// The index starts out as the number of the instruction from the start of
188   /// the block.
189   DenseMap<const Instruction *, unsigned> InstNumbers;
190 
191 public:
192 
193   /// This code only looks at accesses to allocas.
194   static bool isInterestingInstruction(const Instruction *I) {
195     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
196            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
197   }
198 
199   /// Get or calculate the index of the specified instruction.
200   unsigned getInstructionIndex(const Instruction *I) {
201     assert(isInterestingInstruction(I) &&
202            "Not a load/store to/from an alloca?");
203 
204     // If we already have this instruction number, return it.
205     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
206     if (It != InstNumbers.end())
207       return It->second;
208 
209     // Scan the whole block to get the instruction.  This accumulates
210     // information for every interesting instruction in the block, in order to
211     // avoid gratuitus rescans.
212     const BasicBlock *BB = I->getParent();
213     unsigned InstNo = 0;
214     for (const Instruction &BBI : *BB)
215       if (isInterestingInstruction(&BBI))
216         InstNumbers[&BBI] = InstNo++;
217     It = InstNumbers.find(I);
218 
219     assert(It != InstNumbers.end() && "Didn't insert instruction?");
220     return It->second;
221   }
222 
223   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
224 
225   void clear() { InstNumbers.clear(); }
226 };
227 
228 struct PromoteMem2Reg {
229   /// The alloca instructions being promoted.
230   std::vector<AllocaInst *> Allocas;
231 
232   DominatorTree &DT;
233   DIBuilder DIB;
234 
235   /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
236   AssumptionCache *AC;
237 
238   const SimplifyQuery SQ;
239 
240   /// Reverse mapping of Allocas.
241   DenseMap<AllocaInst *, unsigned> AllocaLookup;
242 
243   /// The PhiNodes we're adding.
244   ///
245   /// That map is used to simplify some Phi nodes as we iterate over it, so
246   /// it should have deterministic iterators.  We could use a MapVector, but
247   /// since we already maintain a map from BasicBlock* to a stable numbering
248   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
249   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
250 
251   /// For each PHI node, keep track of which entry in Allocas it corresponds
252   /// to.
253   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
254 
255   /// For each alloca, we keep track of the dbg.declare intrinsic that
256   /// describes it, if any, so that we can convert it to a dbg.value
257   /// intrinsic if the alloca gets promoted.
258   SmallVector<TinyPtrVector<DbgVariableIntrinsic *>, 8> AllocaDbgDeclares;
259 
260   /// The set of basic blocks the renamer has already visited.
261   SmallPtrSet<BasicBlock *, 16> Visited;
262 
263   /// Contains a stable numbering of basic blocks to avoid non-determinstic
264   /// behavior.
265   DenseMap<BasicBlock *, unsigned> BBNumbers;
266 
267   /// Lazily compute the number of predecessors a block has.
268   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
269 
270 public:
271   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
272                  AssumptionCache *AC)
273       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
274         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
275         AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
276                    nullptr, &DT, AC) {}
277 
278   void run();
279 
280 private:
281   void RemoveFromAllocasList(unsigned &AllocaIdx) {
282     Allocas[AllocaIdx] = Allocas.back();
283     Allocas.pop_back();
284     --AllocaIdx;
285   }
286 
287   unsigned getNumPreds(const BasicBlock *BB) {
288     unsigned &NP = BBNumPreds[BB];
289     if (NP == 0)
290       NP = pred_size(BB) + 1;
291     return NP - 1;
292   }
293 
294   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
295                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
296                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
297   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
298                   RenamePassData::ValVector &IncVals,
299                   RenamePassData::LocationVector &IncLocs,
300                   std::vector<RenamePassData> &Worklist);
301   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
302 };
303 
304 } // end anonymous namespace
305 
306 /// Given a LoadInst LI this adds assume(LI != null) after it.
307 static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
308   Function *AssumeIntrinsic =
309       Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
310   ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
311                                        Constant::getNullValue(LI->getType()));
312   LoadNotNull->insertAfter(LI);
313   CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
314   CI->insertAfter(LoadNotNull);
315   AC->registerAssumption(CI);
316 }
317 
318 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
319   // Knowing that this alloca is promotable, we know that it's safe to kill all
320   // instructions except for load and store.
321 
322   for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
323     Instruction *I = cast<Instruction>(*UI);
324     ++UI;
325     if (isa<LoadInst>(I) || isa<StoreInst>(I))
326       continue;
327 
328     if (!I->getType()->isVoidTy()) {
329       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
330       // Follow the use/def chain to erase them now instead of leaving it for
331       // dead code elimination later.
332       for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
333         Instruction *Inst = cast<Instruction>(*UUI);
334         ++UUI;
335         Inst->eraseFromParent();
336       }
337     }
338     I->eraseFromParent();
339   }
340 }
341 
342 /// Rewrite as many loads as possible given a single store.
343 ///
344 /// When there is only a single store, we can use the domtree to trivially
345 /// replace all of the dominated loads with the stored value. Do so, and return
346 /// true if this has successfully promoted the alloca entirely. If this returns
347 /// false there were some loads which were not dominated by the single store
348 /// and thus must be phi-ed with undef. We fall back to the standard alloca
349 /// promotion algorithm in that case.
350 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
351                                      LargeBlockInfo &LBI, const DataLayout &DL,
352                                      DominatorTree &DT, AssumptionCache *AC) {
353   StoreInst *OnlyStore = Info.OnlyStore;
354   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
355   BasicBlock *StoreBB = OnlyStore->getParent();
356   int StoreIndex = -1;
357 
358   // Clear out UsingBlocks.  We will reconstruct it here if needed.
359   Info.UsingBlocks.clear();
360 
361   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
362     Instruction *UserInst = cast<Instruction>(*UI++);
363     if (UserInst == OnlyStore)
364       continue;
365     LoadInst *LI = cast<LoadInst>(UserInst);
366 
367     // Okay, if we have a load from the alloca, we want to replace it with the
368     // only value stored to the alloca.  We can do this if the value is
369     // dominated by the store.  If not, we use the rest of the mem2reg machinery
370     // to insert the phi nodes as needed.
371     if (!StoringGlobalVal) { // Non-instructions are always dominated.
372       if (LI->getParent() == StoreBB) {
373         // If we have a use that is in the same block as the store, compare the
374         // indices of the two instructions to see which one came first.  If the
375         // load came before the store, we can't handle it.
376         if (StoreIndex == -1)
377           StoreIndex = LBI.getInstructionIndex(OnlyStore);
378 
379         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
380           // Can't handle this load, bail out.
381           Info.UsingBlocks.push_back(StoreBB);
382           continue;
383         }
384       } else if (!DT.dominates(StoreBB, LI->getParent())) {
385         // If the load and store are in different blocks, use BB dominance to
386         // check their relationships.  If the store doesn't dom the use, bail
387         // out.
388         Info.UsingBlocks.push_back(LI->getParent());
389         continue;
390       }
391     }
392 
393     // Otherwise, we *can* safely rewrite this load.
394     Value *ReplVal = OnlyStore->getOperand(0);
395     // If the replacement value is the load, this must occur in unreachable
396     // code.
397     if (ReplVal == LI)
398       ReplVal = UndefValue::get(LI->getType());
399 
400     // If the load was marked as nonnull we don't want to lose
401     // that information when we erase this Load. So we preserve
402     // it with an assume.
403     if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
404         !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
405       addAssumeNonNull(AC, LI);
406 
407     LI->replaceAllUsesWith(ReplVal);
408     LI->eraseFromParent();
409     LBI.deleteValue(LI);
410   }
411 
412   // Finally, after the scan, check to see if the store is all that is left.
413   if (!Info.UsingBlocks.empty())
414     return false; // If not, we'll have to fall back for the remainder.
415 
416   // Record debuginfo for the store and remove the declaration's
417   // debuginfo.
418   for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
419     DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
420     ConvertDebugDeclareToDebugValue(DII, Info.OnlyStore, DIB);
421     DII->eraseFromParent();
422   }
423   // Remove the (now dead) store and alloca.
424   Info.OnlyStore->eraseFromParent();
425   LBI.deleteValue(Info.OnlyStore);
426 
427   AI->eraseFromParent();
428   return true;
429 }
430 
431 /// Many allocas are only used within a single basic block.  If this is the
432 /// case, avoid traversing the CFG and inserting a lot of potentially useless
433 /// PHI nodes by just performing a single linear pass over the basic block
434 /// using the Alloca.
435 ///
436 /// If we cannot promote this alloca (because it is read before it is written),
437 /// return false.  This is necessary in cases where, due to control flow, the
438 /// alloca is undefined only on some control flow paths.  e.g. code like
439 /// this is correct in LLVM IR:
440 ///  // A is an alloca with no stores so far
441 ///  for (...) {
442 ///    int t = *A;
443 ///    if (!first_iteration)
444 ///      use(t);
445 ///    *A = 42;
446 ///  }
447 static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
448                                      LargeBlockInfo &LBI,
449                                      const DataLayout &DL,
450                                      DominatorTree &DT,
451                                      AssumptionCache *AC) {
452   // The trickiest case to handle is when we have large blocks. Because of this,
453   // this code is optimized assuming that large blocks happen.  This does not
454   // significantly pessimize the small block case.  This uses LargeBlockInfo to
455   // make it efficient to get the index of various operations in the block.
456 
457   // Walk the use-def list of the alloca, getting the locations of all stores.
458   using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
459   StoresByIndexTy StoresByIndex;
460 
461   for (User *U : AI->users())
462     if (StoreInst *SI = dyn_cast<StoreInst>(U))
463       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
464 
465   // Sort the stores by their index, making it efficient to do a lookup with a
466   // binary search.
467   llvm::sort(StoresByIndex, less_first());
468 
469   // Walk all of the loads from this alloca, replacing them with the nearest
470   // store above them, if any.
471   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
472     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
473     if (!LI)
474       continue;
475 
476     unsigned LoadIdx = LBI.getInstructionIndex(LI);
477 
478     // Find the nearest store that has a lower index than this load.
479     StoresByIndexTy::iterator I = llvm::lower_bound(
480         StoresByIndex,
481         std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
482         less_first());
483     if (I == StoresByIndex.begin()) {
484       if (StoresByIndex.empty())
485         // If there are no stores, the load takes the undef value.
486         LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
487       else
488         // There is no store before this load, bail out (load may be affected
489         // by the following stores - see main comment).
490         return false;
491     } else {
492       // Otherwise, there was a store before this load, the load takes its value.
493       // Note, if the load was marked as nonnull we don't want to lose that
494       // information when we erase it. So we preserve it with an assume.
495       Value *ReplVal = std::prev(I)->second->getOperand(0);
496       if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
497           !isKnownNonZero(ReplVal, DL, 0, AC, LI, &DT))
498         addAssumeNonNull(AC, LI);
499 
500       // If the replacement value is the load, this must occur in unreachable
501       // code.
502       if (ReplVal == LI)
503         ReplVal = UndefValue::get(LI->getType());
504 
505       LI->replaceAllUsesWith(ReplVal);
506     }
507 
508     LI->eraseFromParent();
509     LBI.deleteValue(LI);
510   }
511 
512   // Remove the (now dead) stores and alloca.
513   while (!AI->use_empty()) {
514     StoreInst *SI = cast<StoreInst>(AI->user_back());
515     // Record debuginfo for the store before removing it.
516     for (DbgVariableIntrinsic *DII : Info.DbgDeclares) {
517       DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
518       ConvertDebugDeclareToDebugValue(DII, SI, DIB);
519     }
520     SI->eraseFromParent();
521     LBI.deleteValue(SI);
522   }
523 
524   AI->eraseFromParent();
525 
526   // The alloca's debuginfo can be removed as well.
527   for (DbgVariableIntrinsic *DII : Info.DbgDeclares)
528     DII->eraseFromParent();
529 
530   ++NumLocalPromoted;
531   return true;
532 }
533 
534 void PromoteMem2Reg::run() {
535   Function &F = *DT.getRoot()->getParent();
536 
537   AllocaDbgDeclares.resize(Allocas.size());
538 
539   AllocaInfo Info;
540   LargeBlockInfo LBI;
541   ForwardIDFCalculator IDF(DT);
542 
543   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
544     AllocaInst *AI = Allocas[AllocaNum];
545 
546     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
547     assert(AI->getParent()->getParent() == &F &&
548            "All allocas should be in the same function, which is same as DF!");
549 
550     removeLifetimeIntrinsicUsers(AI);
551 
552     if (AI->use_empty()) {
553       // If there are no uses of the alloca, just delete it now.
554       AI->eraseFromParent();
555 
556       // Remove the alloca from the Allocas list, since it has been processed
557       RemoveFromAllocasList(AllocaNum);
558       ++NumDeadAlloca;
559       continue;
560     }
561 
562     // Calculate the set of read and write-locations for each alloca.  This is
563     // analogous to finding the 'uses' and 'definitions' of each variable.
564     Info.AnalyzeAlloca(AI);
565 
566     // If there is only a single store to this value, replace any loads of
567     // it that are directly dominated by the definition with the value stored.
568     if (Info.DefiningBlocks.size() == 1) {
569       if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
570         // The alloca has been processed, move on.
571         RemoveFromAllocasList(AllocaNum);
572         ++NumSingleStore;
573         continue;
574       }
575     }
576 
577     // If the alloca is only read and written in one basic block, just perform a
578     // linear sweep over the block to eliminate it.
579     if (Info.OnlyUsedInOneBlock &&
580         promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
581       // The alloca has been processed, move on.
582       RemoveFromAllocasList(AllocaNum);
583       continue;
584     }
585 
586     // If we haven't computed a numbering for the BB's in the function, do so
587     // now.
588     if (BBNumbers.empty()) {
589       unsigned ID = 0;
590       for (auto &BB : F)
591         BBNumbers[&BB] = ID++;
592     }
593 
594     // Remember the dbg.declare intrinsic describing this alloca, if any.
595     if (!Info.DbgDeclares.empty())
596       AllocaDbgDeclares[AllocaNum] = Info.DbgDeclares;
597 
598     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
599     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
600 
601     // Unique the set of defining blocks for efficient lookup.
602     SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
603                                             Info.DefiningBlocks.end());
604 
605     // Determine which blocks the value is live in.  These are blocks which lead
606     // to uses.
607     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
608     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
609 
610     // At this point, we're committed to promoting the alloca using IDF's, and
611     // the standard SSA construction algorithm.  Determine which blocks need phi
612     // nodes and see if we can optimize out some work by avoiding insertion of
613     // dead phi nodes.
614     IDF.setLiveInBlocks(LiveInBlocks);
615     IDF.setDefiningBlocks(DefBlocks);
616     SmallVector<BasicBlock *, 32> PHIBlocks;
617     IDF.calculate(PHIBlocks);
618     llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
619       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
620     });
621 
622     unsigned CurrentVersion = 0;
623     for (BasicBlock *BB : PHIBlocks)
624       QueuePhiNode(BB, AllocaNum, CurrentVersion);
625   }
626 
627   if (Allocas.empty())
628     return; // All of the allocas must have been trivial!
629 
630   LBI.clear();
631 
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.
635   RenamePassData::ValVector Values(Allocas.size());
636   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
637     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
638 
639   // When handling debug info, treat all incoming values as if they have unknown
640   // locations until proven otherwise.
641   RenamePassData::LocationVector Locations(Allocas.size());
642 
643   // Walks all basic blocks in the function performing the SSA rename algorithm
644   // and inserting the phi nodes we marked as necessary
645   std::vector<RenamePassData> RenamePassWorkList;
646   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
647                                   std::move(Locations));
648   do {
649     RenamePassData RPD = std::move(RenamePassWorkList.back());
650     RenamePassWorkList.pop_back();
651     // RenamePass may add new worklist entries.
652     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
653   } while (!RenamePassWorkList.empty());
654 
655   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
656   Visited.clear();
657 
658   // Remove the allocas themselves from the function.
659   for (Instruction *A : Allocas) {
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.
663     if (!A->use_empty())
664       A->replaceAllUsesWith(UndefValue::get(A->getType()));
665     A->eraseFromParent();
666   }
667 
668   // Remove alloca's dbg.declare instrinsics from the function.
669   for (auto &Declares : AllocaDbgDeclares)
670     for (auto *DII : Declares)
671       DII->eraseFromParent();
672 
673   // Loop over all of the PHI nodes and see if there are any that we can get
674   // rid of because they merge all of the same incoming values.  This can
675   // happen due to undef values coming into the PHI nodes.  This process is
676   // iterative, because eliminating one PHI node can cause others to be removed.
677   bool EliminatedAPHI = true;
678   while (EliminatedAPHI) {
679     EliminatedAPHI = false;
680 
681     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
682     // simplify and RAUW them as we go.  If it was not, we could add uses to
683     // the values we replace with in a non-deterministic order, thus creating
684     // non-deterministic def->use chains.
685     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
686              I = NewPhiNodes.begin(),
687              E = NewPhiNodes.end();
688          I != E;) {
689       PHINode *PN = I->second;
690 
691       // If this PHI node merges one value and/or undefs, get the value.
692       if (Value *V = SimplifyInstruction(PN, SQ)) {
693         PN->replaceAllUsesWith(V);
694         PN->eraseFromParent();
695         NewPhiNodes.erase(I++);
696         EliminatedAPHI = true;
697         continue;
698       }
699       ++I;
700     }
701   }
702 
703   // At this point, the renamer has added entries to PHI nodes for all reachable
704   // code.  Unfortunately, there may be unreachable blocks which the renamer
705   // hasn't traversed.  If this is the case, the PHI nodes may not
706   // have incoming values for all predecessors.  Loop over all PHI nodes we have
707   // created, inserting undef values if they are missing any incoming values.
708   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
709            I = NewPhiNodes.begin(),
710            E = NewPhiNodes.end();
711        I != E; ++I) {
712     // We want to do this once per basic block.  As such, only process a block
713     // when we find the PHI that is the first entry in the block.
714     PHINode *SomePHI = I->second;
715     BasicBlock *BB = SomePHI->getParent();
716     if (&BB->front() != SomePHI)
717       continue;
718 
719     // Only do work here if there the PHI nodes are missing incoming values.  We
720     // know that all PHI nodes that were inserted in a block will have the same
721     // number of incoming values, so we can just check any of them.
722     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
723       continue;
724 
725     // Get the preds for BB.
726     SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
727 
728     // Ok, now we know that all of the PHI nodes are missing entries for some
729     // basic blocks.  Start by sorting the incoming predecessors for efficient
730     // access.
731     auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
732       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
733     };
734     llvm::sort(Preds, CompareBBNumbers);
735 
736     // Now we loop through all BB's which have entries in SomePHI and remove
737     // them from the Preds list.
738     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
739       // Do a log(n) search of the Preds list for the entry we want.
740       SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
741           Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
742       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
743              "PHI node has entry for a block which is not a predecessor!");
744 
745       // Remove the entry
746       Preds.erase(EntIt);
747     }
748 
749     // At this point, the blocks left in the preds list must have dummy
750     // entries inserted into every PHI nodes for the block.  Update all the phi
751     // nodes in this block that we are inserting (there could be phis before
752     // mem2reg runs).
753     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
754     BasicBlock::iterator BBI = BB->begin();
755     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
756            SomePHI->getNumIncomingValues() == NumBadPreds) {
757       Value *UndefVal = UndefValue::get(SomePHI->getType());
758       for (BasicBlock *Pred : Preds)
759         SomePHI->addIncoming(UndefVal, Pred);
760     }
761   }
762 
763   NewPhiNodes.clear();
764 }
765 
766 /// Determine which blocks the value is live in.
767 ///
768 /// These are blocks which lead to uses.  Knowing this allows us to avoid
769 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
770 /// inserted phi nodes would be dead).
771 void PromoteMem2Reg::ComputeLiveInBlocks(
772     AllocaInst *AI, AllocaInfo &Info,
773     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
774     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
775   // To determine liveness, we must iterate through the predecessors of blocks
776   // where the def is live.  Blocks are added to the worklist if we need to
777   // check their predecessors.  Start with all the using blocks.
778   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
779                                                     Info.UsingBlocks.end());
780 
781   // If any of the using blocks is also a definition block, check to see if the
782   // definition occurs before or after the use.  If it happens before the use,
783   // the value isn't really live-in.
784   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
785     BasicBlock *BB = LiveInBlockWorklist[i];
786     if (!DefBlocks.count(BB))
787       continue;
788 
789     // Okay, this is a block that both uses and defines the value.  If the first
790     // reference to the alloca is a def (store), then we know it isn't live-in.
791     for (BasicBlock::iterator I = BB->begin();; ++I) {
792       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
793         if (SI->getOperand(1) != AI)
794           continue;
795 
796         // We found a store to the alloca before a load.  The alloca is not
797         // actually live-in here.
798         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
799         LiveInBlockWorklist.pop_back();
800         --i;
801         --e;
802         break;
803       }
804 
805       if (LoadInst *LI = dyn_cast<LoadInst>(I))
806         // Okay, we found a load before a store to the alloca.  It is actually
807         // live into this block.
808         if (LI->getOperand(0) == AI)
809           break;
810     }
811   }
812 
813   // Now that we have a set of blocks where the phi is live-in, recursively add
814   // their predecessors until we find the full region the value is live.
815   while (!LiveInBlockWorklist.empty()) {
816     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
817 
818     // The block really is live in here, insert it into the set.  If already in
819     // the set, then it has already been processed.
820     if (!LiveInBlocks.insert(BB).second)
821       continue;
822 
823     // Since the value is live into BB, it is either defined in a predecessor or
824     // live into it to.  Add the preds to the worklist unless they are a
825     // defining block.
826     for (BasicBlock *P : predecessors(BB)) {
827       // The value is not live into a predecessor if it defines the value.
828       if (DefBlocks.count(P))
829         continue;
830 
831       // Otherwise it is, add to the worklist.
832       LiveInBlockWorklist.push_back(P);
833     }
834   }
835 }
836 
837 /// Queue a phi-node to be added to a basic-block for a specific Alloca.
838 ///
839 /// Returns true if there wasn't already a phi-node for that variable
840 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
841                                   unsigned &Version) {
842   // Look up the basic-block in question.
843   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
844 
845   // If the BB already has a phi node added for the i'th alloca then we're done!
846   if (PN)
847     return false;
848 
849   // Create a PhiNode using the dereferenced type... and add the phi-node to the
850   // BasicBlock.
851   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
852                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
853                        &BB->front());
854   ++NumPHIInsert;
855   PhiToAllocaMap[PN] = AllocaNo;
856   return true;
857 }
858 
859 /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
860 /// create a merged location incorporating \p DL, or to set \p DL directly.
861 static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
862                                            bool ApplyMergedLoc) {
863   if (ApplyMergedLoc)
864     PN->applyMergedLocation(PN->getDebugLoc(), DL);
865   else
866     PN->setDebugLoc(DL);
867 }
868 
869 /// Recursively traverse the CFG of the function, renaming loads and
870 /// stores to the allocas which we are promoting.
871 ///
872 /// IncomingVals indicates what value each Alloca contains on exit from the
873 /// predecessor block Pred.
874 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
875                                 RenamePassData::ValVector &IncomingVals,
876                                 RenamePassData::LocationVector &IncomingLocs,
877                                 std::vector<RenamePassData> &Worklist) {
878 NextIteration:
879   // If we are inserting any phi nodes into this BB, they will already be in the
880   // block.
881   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
882     // If we have PHI nodes to update, compute the number of edges from Pred to
883     // BB.
884     if (PhiToAllocaMap.count(APN)) {
885       // We want to be able to distinguish between PHI nodes being inserted by
886       // this invocation of mem2reg from those phi nodes that already existed in
887       // the IR before mem2reg was run.  We determine that APN is being inserted
888       // because it is missing incoming edges.  All other PHI nodes being
889       // inserted by this pass of mem2reg will have the same number of incoming
890       // operands so far.  Remember this count.
891       unsigned NewPHINumOperands = APN->getNumOperands();
892 
893       unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
894       assert(NumEdges && "Must be at least one edge from Pred to BB!");
895 
896       // Add entries for all the phis.
897       BasicBlock::iterator PNI = BB->begin();
898       do {
899         unsigned AllocaNo = PhiToAllocaMap[APN];
900 
901         // Update the location of the phi node.
902         updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
903                                        APN->getNumIncomingValues() > 0);
904 
905         // Add N incoming values to the PHI node.
906         for (unsigned i = 0; i != NumEdges; ++i)
907           APN->addIncoming(IncomingVals[AllocaNo], Pred);
908 
909         // The currently active variable for this block is now the PHI.
910         IncomingVals[AllocaNo] = APN;
911         for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[AllocaNo])
912           ConvertDebugDeclareToDebugValue(DII, APN, DIB);
913 
914         // Get the next phi node.
915         ++PNI;
916         APN = dyn_cast<PHINode>(PNI);
917         if (!APN)
918           break;
919 
920         // Verify that it is missing entries.  If not, it is not being inserted
921         // by this mem2reg invocation so we want to ignore it.
922       } while (APN->getNumOperands() == NewPHINumOperands);
923     }
924   }
925 
926   // Don't revisit blocks.
927   if (!Visited.insert(BB).second)
928     return;
929 
930   for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
931     Instruction *I = &*II++; // get the instruction, increment iterator
932 
933     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
934       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
935       if (!Src)
936         continue;
937 
938       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
939       if (AI == AllocaLookup.end())
940         continue;
941 
942       Value *V = IncomingVals[AI->second];
943 
944       // If the load was marked as nonnull we don't want to lose
945       // that information when we erase this Load. So we preserve
946       // it with an assume.
947       if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
948           !isKnownNonZero(V, SQ.DL, 0, AC, LI, &DT))
949         addAssumeNonNull(AC, LI);
950 
951       // Anything using the load now uses the current value.
952       LI->replaceAllUsesWith(V);
953       BB->getInstList().erase(LI);
954     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
955       // Delete this instruction and mark the name as the current holder of the
956       // value
957       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
958       if (!Dest)
959         continue;
960 
961       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
962       if (ai == AllocaLookup.end())
963         continue;
964 
965       // what value were we writing?
966       unsigned AllocaNo = ai->second;
967       IncomingVals[AllocaNo] = SI->getOperand(0);
968 
969       // Record debuginfo for the store before removing it.
970       IncomingLocs[AllocaNo] = SI->getDebugLoc();
971       for (DbgVariableIntrinsic *DII : AllocaDbgDeclares[ai->second])
972         ConvertDebugDeclareToDebugValue(DII, SI, DIB);
973       BB->getInstList().erase(SI);
974     }
975   }
976 
977   // 'Recurse' to our successors.
978   succ_iterator I = succ_begin(BB), E = succ_end(BB);
979   if (I == E)
980     return;
981 
982   // Keep track of the successors so we don't visit the same successor twice
983   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
984 
985   // Handle the first successor without using the worklist.
986   VisitedSuccs.insert(*I);
987   Pred = BB;
988   BB = *I;
989   ++I;
990 
991   for (; I != E; ++I)
992     if (VisitedSuccs.insert(*I).second)
993       Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
994 
995   goto NextIteration;
996 }
997 
998 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
999                            AssumptionCache *AC) {
1000   // If there is nothing to do, bail out...
1001   if (Allocas.empty())
1002     return;
1003 
1004   PromoteMem2Reg(Allocas, DT, AC).run();
1005 }
1006