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