xref: /llvm-project/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp (revision 9f8f6ce53cb7bc3f139db7b8f614a4f0e9a1b579)
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/Twine.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/IteratedDominanceFrontier.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DIBuilder.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DebugProgramInstruction.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/User.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <iterator>
53 #include <utility>
54 #include <vector>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "mem2reg"
59 
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");
64 
65 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
66   // Only allow direct and non-volatile loads and stores...
67   for (const User *U : AI->users()) {
68     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
69       // Note that atomic loads can be transformed; atomic semantics do
70       // not have any meaning for a local alloca.
71       if (LI->isVolatile() || LI->getType() != AI->getAllocatedType())
72         return false;
73     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
74       if (SI->getValueOperand() == AI ||
75           SI->getValueOperand()->getType() != AI->getAllocatedType())
76         return false; // Don't allow a store OF the AI, only INTO the AI.
77       // Note that atomic stores can be transformed; atomic semantics do
78       // not have any meaning for a local alloca.
79       if (SI->isVolatile())
80         return false;
81     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
82       if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
83         return false;
84     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
85       if (!onlyUsedByLifetimeMarkersOrDroppableInsts(BCI))
86         return false;
87     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
88       if (!GEPI->hasAllZeroIndices())
89         return false;
90       if (!onlyUsedByLifetimeMarkersOrDroppableInsts(GEPI))
91         return false;
92     } else if (const AddrSpaceCastInst *ASCI = dyn_cast<AddrSpaceCastInst>(U)) {
93       if (!onlyUsedByLifetimeMarkers(ASCI))
94         return false;
95     } else {
96       return false;
97     }
98   }
99 
100   return true;
101 }
102 
103 namespace {
104 
105 static void createDebugValue(DIBuilder &DIB, Value *NewValue,
106                              DILocalVariable *Variable,
107                              DIExpression *Expression, const DILocation *DI,
108                              DbgVariableRecord *InsertBefore) {
109   // FIXME: Merge these two functions now that DIBuilder supports
110   // DbgVariableRecords. We neeed the API to accept DbgVariableRecords as an
111   // insert point for that to work.
112   (void)DIB;
113   DbgVariableRecord::createDbgVariableRecord(NewValue, Variable, Expression, DI,
114                                              *InsertBefore);
115 }
116 static void createDebugValue(DIBuilder &DIB, Value *NewValue,
117                              DILocalVariable *Variable,
118                              DIExpression *Expression, const DILocation *DI,
119                              Instruction *InsertBefore) {
120   DIB.insertDbgValueIntrinsic(NewValue, Variable, Expression, DI, InsertBefore);
121 }
122 
123 /// Helper for updating assignment tracking debug info when promoting allocas.
124 class AssignmentTrackingInfo {
125   /// DbgAssignIntrinsics linked to the alloca with at most one per variable
126   /// fragment. (i.e. not be a comprehensive set if there are multiple
127   /// dbg.assigns for one variable fragment).
128   SmallVector<DbgVariableIntrinsic *> DbgAssigns;
129   SmallVector<DbgVariableRecord *> DVRAssigns;
130 
131 public:
132   void init(AllocaInst *AI) {
133     SmallSet<DebugVariable, 2> Vars;
134     for (DbgAssignIntrinsic *DAI : at::getAssignmentMarkers(AI)) {
135       if (Vars.insert(DebugVariable(DAI)).second)
136         DbgAssigns.push_back(DAI);
137     }
138     for (DbgVariableRecord *DVR : at::getDVRAssignmentMarkers(AI)) {
139       if (Vars.insert(DebugVariable(DVR)).second)
140         DVRAssigns.push_back(DVR);
141     }
142   }
143 
144   /// Update assignment tracking debug info given for the to-be-deleted store
145   /// \p ToDelete that stores to this alloca.
146   void updateForDeletedStore(
147       StoreInst *ToDelete, DIBuilder &DIB,
148       SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
149       SmallSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) const {
150     // There's nothing to do if the alloca doesn't have any variables using
151     // assignment tracking.
152     if (DbgAssigns.empty() && DVRAssigns.empty())
153       return;
154 
155     // Insert a dbg.value where the linked dbg.assign is and remember to delete
156     // the dbg.assign later. Demoting to dbg.value isn't necessary for
157     // correctness but does reduce compile time and memory usage by reducing
158     // unnecessary function-local metadata. Remember that we've seen a
159     // dbg.assign for each variable fragment for the untracked store handling
160     // (after this loop).
161     SmallSet<DebugVariableAggregate, 2> VarHasDbgAssignForStore;
162     auto InsertValueForAssign = [&](auto *DbgAssign, auto *&AssignList) {
163       VarHasDbgAssignForStore.insert(DebugVariableAggregate(DbgAssign));
164       AssignList->insert(DbgAssign);
165       createDebugValue(DIB, DbgAssign->getValue(), DbgAssign->getVariable(),
166                        DbgAssign->getExpression(), DbgAssign->getDebugLoc(),
167                        DbgAssign);
168     };
169     for (auto *Assign : at::getAssignmentMarkers(ToDelete))
170       InsertValueForAssign(Assign, DbgAssignsToDelete);
171     for (auto *Assign : at::getDVRAssignmentMarkers(ToDelete))
172       InsertValueForAssign(Assign, DVRAssignsToDelete);
173 
174     // It's possible for variables using assignment tracking to have no
175     // dbg.assign linked to this store. These are variables in DbgAssigns that
176     // are missing from VarHasDbgAssignForStore. Since there isn't a dbg.assign
177     // to mark the assignment - and the store is going to be deleted - insert a
178     // dbg.value to do that now. An untracked store may be either one that
179     // cannot be represented using assignment tracking (non-const offset or
180     // size) or one that is trackable but has had its DIAssignID attachment
181     // dropped accidentally.
182     auto ConvertUnlinkedAssignToValue = [&](auto *Assign) {
183       if (VarHasDbgAssignForStore.contains(DebugVariableAggregate(Assign)))
184         return;
185       ConvertDebugDeclareToDebugValue(Assign, ToDelete, DIB);
186     };
187     for_each(DbgAssigns, ConvertUnlinkedAssignToValue);
188     for_each(DVRAssigns, ConvertUnlinkedAssignToValue);
189   }
190 
191   /// Update assignment tracking debug info given for the newly inserted PHI \p
192   /// NewPhi.
193   void updateForNewPhi(PHINode *NewPhi, DIBuilder &DIB) const {
194     // Regardless of the position of dbg.assigns relative to stores, the
195     // incoming values into a new PHI should be the same for the (imaginary)
196     // debug-phi.
197     for (auto *DAI : DbgAssigns)
198       ConvertDebugDeclareToDebugValue(DAI, NewPhi, DIB);
199     for (auto *DVR : DVRAssigns)
200       ConvertDebugDeclareToDebugValue(DVR, NewPhi, DIB);
201   }
202 
203   void clear() {
204     DbgAssigns.clear();
205     DVRAssigns.clear();
206   }
207   bool empty() { return DbgAssigns.empty() && DVRAssigns.empty(); }
208 };
209 
210 struct AllocaInfo {
211   using DbgUserVec = SmallVector<DbgVariableIntrinsic *, 1>;
212   using DPUserVec = SmallVector<DbgVariableRecord *, 1>;
213 
214   SmallVector<BasicBlock *, 32> DefiningBlocks;
215   SmallVector<BasicBlock *, 32> UsingBlocks;
216 
217   StoreInst *OnlyStore;
218   BasicBlock *OnlyBlock;
219   bool OnlyUsedInOneBlock;
220 
221   /// Debug users of the alloca - does not include dbg.assign intrinsics.
222   DbgUserVec DbgUsers;
223   DPUserVec DPUsers;
224   /// Helper to update assignment tracking debug info.
225   AssignmentTrackingInfo AssignmentTracking;
226 
227   void clear() {
228     DefiningBlocks.clear();
229     UsingBlocks.clear();
230     OnlyStore = nullptr;
231     OnlyBlock = nullptr;
232     OnlyUsedInOneBlock = true;
233     DbgUsers.clear();
234     DPUsers.clear();
235     AssignmentTracking.clear();
236   }
237 
238   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
239   /// by the rest of the pass to reason about the uses of this alloca.
240   void AnalyzeAlloca(AllocaInst *AI) {
241     clear();
242 
243     // As we scan the uses of the alloca instruction, keep track of stores,
244     // and decide whether all of the loads and stores to the alloca are within
245     // the same basic block.
246     for (User *U : AI->users()) {
247       Instruction *User = cast<Instruction>(U);
248 
249       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
250         // Remember the basic blocks which define new values for the alloca
251         DefiningBlocks.push_back(SI->getParent());
252         OnlyStore = SI;
253       } else {
254         LoadInst *LI = cast<LoadInst>(User);
255         // Otherwise it must be a load instruction, keep track of variable
256         // reads.
257         UsingBlocks.push_back(LI->getParent());
258       }
259 
260       if (OnlyUsedInOneBlock) {
261         if (!OnlyBlock)
262           OnlyBlock = User->getParent();
263         else if (OnlyBlock != User->getParent())
264           OnlyUsedInOneBlock = false;
265       }
266     }
267     DbgUserVec AllDbgUsers;
268     SmallVector<DbgVariableRecord *> AllDPUsers;
269     findDbgUsers(AllDbgUsers, AI, &AllDPUsers);
270     std::copy_if(AllDbgUsers.begin(), AllDbgUsers.end(),
271                  std::back_inserter(DbgUsers), [](DbgVariableIntrinsic *DII) {
272                    return !isa<DbgAssignIntrinsic>(DII);
273                  });
274     std::copy_if(AllDPUsers.begin(), AllDPUsers.end(),
275                  std::back_inserter(DPUsers),
276                  [](DbgVariableRecord *DVR) { return !DVR->isDbgAssign(); });
277     AssignmentTracking.init(AI);
278   }
279 };
280 
281 /// Data package used by RenamePass().
282 struct RenamePassData {
283   using ValVector = std::vector<Value *>;
284   using LocationVector = std::vector<DebugLoc>;
285 
286   RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
287       : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
288 
289   BasicBlock *BB;
290   BasicBlock *Pred;
291   ValVector Values;
292   LocationVector Locations;
293 };
294 
295 /// This assigns and keeps a per-bb relative ordering of load/store
296 /// instructions in the block that directly load or store an alloca.
297 ///
298 /// This functionality is important because it avoids scanning large basic
299 /// blocks multiple times when promoting many allocas in the same block.
300 class LargeBlockInfo {
301   /// For each instruction that we track, keep the index of the
302   /// instruction.
303   ///
304   /// The index starts out as the number of the instruction from the start of
305   /// the block.
306   DenseMap<const Instruction *, unsigned> InstNumbers;
307 
308 public:
309 
310   /// This code only looks at accesses to allocas.
311   static bool isInterestingInstruction(const Instruction *I) {
312     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
313            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
314   }
315 
316   /// Get or calculate the index of the specified instruction.
317   unsigned getInstructionIndex(const Instruction *I) {
318     assert(isInterestingInstruction(I) &&
319            "Not a load/store to/from an alloca?");
320 
321     // If we already have this instruction number, return it.
322     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
323     if (It != InstNumbers.end())
324       return It->second;
325 
326     // Scan the whole block to get the instruction.  This accumulates
327     // information for every interesting instruction in the block, in order to
328     // avoid gratuitus rescans.
329     const BasicBlock *BB = I->getParent();
330     unsigned InstNo = 0;
331     for (const Instruction &BBI : *BB)
332       if (isInterestingInstruction(&BBI))
333         InstNumbers[&BBI] = InstNo++;
334     It = InstNumbers.find(I);
335 
336     assert(It != InstNumbers.end() && "Didn't insert instruction?");
337     return It->second;
338   }
339 
340   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
341 
342   void clear() { InstNumbers.clear(); }
343 };
344 
345 struct PromoteMem2Reg {
346   /// The alloca instructions being promoted.
347   std::vector<AllocaInst *> Allocas;
348 
349   DominatorTree &DT;
350   DIBuilder DIB;
351 
352   /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
353   AssumptionCache *AC;
354 
355   const SimplifyQuery SQ;
356 
357   /// Reverse mapping of Allocas.
358   DenseMap<AllocaInst *, unsigned> AllocaLookup;
359 
360   /// The PhiNodes we're adding.
361   ///
362   /// That map is used to simplify some Phi nodes as we iterate over it, so
363   /// it should have deterministic iterators.  We could use a MapVector, but
364   /// since we already maintain a map from BasicBlock* to a stable numbering
365   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
366   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
367 
368   /// For each PHI node, keep track of which entry in Allocas it corresponds
369   /// to.
370   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
371 
372   /// For each alloca, we keep track of the dbg.declare intrinsic that
373   /// describes it, if any, so that we can convert it to a dbg.value
374   /// intrinsic if the alloca gets promoted.
375   SmallVector<AllocaInfo::DbgUserVec, 8> AllocaDbgUsers;
376   SmallVector<AllocaInfo::DPUserVec, 8> AllocaDPUsers;
377 
378   /// For each alloca, keep an instance of a helper class that gives us an easy
379   /// way to update assignment tracking debug info if the alloca is promoted.
380   SmallVector<AssignmentTrackingInfo, 8> AllocaATInfo;
381   /// A set of dbg.assigns to delete because they've been demoted to
382   /// dbg.values. Call cleanUpDbgAssigns to delete them.
383   SmallSet<DbgAssignIntrinsic *, 8> DbgAssignsToDelete;
384   SmallSet<DbgVariableRecord *, 8> DVRAssignsToDelete;
385 
386   /// The set of basic blocks the renamer has already visited.
387   SmallPtrSet<BasicBlock *, 16> Visited;
388 
389   /// Contains a stable numbering of basic blocks to avoid non-determinstic
390   /// behavior.
391   DenseMap<BasicBlock *, unsigned> BBNumbers;
392 
393   /// Lazily compute the number of predecessors a block has.
394   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
395 
396   /// Whether the function has the no-signed-zeros-fp-math attribute set.
397   bool NoSignedZeros = false;
398 
399 public:
400   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
401                  AssumptionCache *AC)
402       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
403         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
404         AC(AC), SQ(DT.getRoot()->getDataLayout(),
405                    nullptr, &DT, AC) {}
406 
407   void run();
408 
409 private:
410   void RemoveFromAllocasList(unsigned &AllocaIdx) {
411     Allocas[AllocaIdx] = Allocas.back();
412     Allocas.pop_back();
413     --AllocaIdx;
414   }
415 
416   unsigned getNumPreds(const BasicBlock *BB) {
417     unsigned &NP = BBNumPreds[BB];
418     if (NP == 0)
419       NP = pred_size(BB) + 1;
420     return NP - 1;
421   }
422 
423   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
424                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
425                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
426   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
427                   RenamePassData::ValVector &IncVals,
428                   RenamePassData::LocationVector &IncLocs,
429                   std::vector<RenamePassData> &Worklist);
430   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
431 
432   /// Delete dbg.assigns that have been demoted to dbg.values.
433   void cleanUpDbgAssigns() {
434     for (auto *DAI : DbgAssignsToDelete)
435       DAI->eraseFromParent();
436     DbgAssignsToDelete.clear();
437     for (auto *DVR : DVRAssignsToDelete)
438       DVR->eraseFromParent();
439     DVRAssignsToDelete.clear();
440   }
441 };
442 
443 } // end anonymous namespace
444 
445 /// Given a LoadInst LI this adds assume(LI != null) after it.
446 static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
447   Function *AssumeIntrinsic =
448       Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
449   ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
450                                        Constant::getNullValue(LI->getType()));
451   LoadNotNull->insertAfter(LI);
452   CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
453   CI->insertAfter(LoadNotNull);
454   AC->registerAssumption(cast<AssumeInst>(CI));
455 }
456 
457 static void convertMetadataToAssumes(LoadInst *LI, Value *Val,
458                                      const DataLayout &DL, AssumptionCache *AC,
459                                      const DominatorTree *DT) {
460   if (isa<UndefValue>(Val) && LI->hasMetadata(LLVMContext::MD_noundef)) {
461     // Insert non-terminator unreachable.
462     LLVMContext &Ctx = LI->getContext();
463     new StoreInst(ConstantInt::getTrue(Ctx),
464                   PoisonValue::get(PointerType::getUnqual(Ctx)),
465                   /*isVolatile=*/false, Align(1), LI);
466     return;
467   }
468 
469   // If the load was marked as nonnull we don't want to lose that information
470   // when we erase this Load. So we preserve it with an assume. As !nonnull
471   // returns poison while assume violations are immediate undefined behavior,
472   // we can only do this if the value is known non-poison.
473   if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
474       LI->getMetadata(LLVMContext::MD_noundef) &&
475       !isKnownNonZero(Val, SimplifyQuery(DL, DT, AC, LI)))
476     addAssumeNonNull(AC, LI);
477 }
478 
479 static void removeIntrinsicUsers(AllocaInst *AI) {
480   // Knowing that this alloca is promotable, we know that it's safe to kill all
481   // instructions except for load and store.
482 
483   for (Use &U : llvm::make_early_inc_range(AI->uses())) {
484     Instruction *I = cast<Instruction>(U.getUser());
485     if (isa<LoadInst>(I) || isa<StoreInst>(I))
486       continue;
487 
488     // Drop the use of AI in droppable instructions.
489     if (I->isDroppable()) {
490       I->dropDroppableUse(U);
491       continue;
492     }
493 
494     if (!I->getType()->isVoidTy()) {
495       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
496       // Follow the use/def chain to erase them now instead of leaving it for
497       // dead code elimination later.
498       for (Use &UU : llvm::make_early_inc_range(I->uses())) {
499         Instruction *Inst = cast<Instruction>(UU.getUser());
500 
501         // Drop the use of I in droppable instructions.
502         if (Inst->isDroppable()) {
503           Inst->dropDroppableUse(UU);
504           continue;
505         }
506         Inst->eraseFromParent();
507       }
508     }
509     I->eraseFromParent();
510   }
511 }
512 
513 /// Rewrite as many loads as possible given a single store.
514 ///
515 /// When there is only a single store, we can use the domtree to trivially
516 /// replace all of the dominated loads with the stored value. Do so, and return
517 /// true if this has successfully promoted the alloca entirely. If this returns
518 /// false there were some loads which were not dominated by the single store
519 /// and thus must be phi-ed with undef. We fall back to the standard alloca
520 /// promotion algorithm in that case.
521 static bool
522 rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI,
523                          const DataLayout &DL, DominatorTree &DT,
524                          AssumptionCache *AC,
525                          SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
526                          SmallSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
527   StoreInst *OnlyStore = Info.OnlyStore;
528   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
529   BasicBlock *StoreBB = OnlyStore->getParent();
530   int StoreIndex = -1;
531 
532   // Clear out UsingBlocks.  We will reconstruct it here if needed.
533   Info.UsingBlocks.clear();
534 
535   for (User *U : make_early_inc_range(AI->users())) {
536     Instruction *UserInst = cast<Instruction>(U);
537     if (UserInst == OnlyStore)
538       continue;
539     LoadInst *LI = cast<LoadInst>(UserInst);
540 
541     // Okay, if we have a load from the alloca, we want to replace it with the
542     // only value stored to the alloca.  We can do this if the value is
543     // dominated by the store.  If not, we use the rest of the mem2reg machinery
544     // to insert the phi nodes as needed.
545     if (!StoringGlobalVal) { // Non-instructions are always dominated.
546       if (LI->getParent() == StoreBB) {
547         // If we have a use that is in the same block as the store, compare the
548         // indices of the two instructions to see which one came first.  If the
549         // load came before the store, we can't handle it.
550         if (StoreIndex == -1)
551           StoreIndex = LBI.getInstructionIndex(OnlyStore);
552 
553         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
554           // Can't handle this load, bail out.
555           Info.UsingBlocks.push_back(StoreBB);
556           continue;
557         }
558       } else if (!DT.dominates(StoreBB, LI->getParent())) {
559         // If the load and store are in different blocks, use BB dominance to
560         // check their relationships.  If the store doesn't dom the use, bail
561         // out.
562         Info.UsingBlocks.push_back(LI->getParent());
563         continue;
564       }
565     }
566 
567     // Otherwise, we *can* safely rewrite this load.
568     Value *ReplVal = OnlyStore->getOperand(0);
569     // If the replacement value is the load, this must occur in unreachable
570     // code.
571     if (ReplVal == LI)
572       ReplVal = PoisonValue::get(LI->getType());
573 
574     convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
575     LI->replaceAllUsesWith(ReplVal);
576     LI->eraseFromParent();
577     LBI.deleteValue(LI);
578   }
579 
580   // Finally, after the scan, check to see if the store is all that is left.
581   if (!Info.UsingBlocks.empty())
582     return false; // If not, we'll have to fall back for the remainder.
583 
584   DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
585   // Update assignment tracking info for the store we're going to delete.
586   Info.AssignmentTracking.updateForDeletedStore(
587       Info.OnlyStore, DIB, DbgAssignsToDelete, DVRAssignsToDelete);
588 
589   // Record debuginfo for the store and remove the declaration's
590   // debuginfo.
591   auto ConvertDebugInfoForStore = [&](auto &Container) {
592     for (auto *DbgItem : Container) {
593       if (DbgItem->isAddressOfVariable()) {
594         ConvertDebugDeclareToDebugValue(DbgItem, Info.OnlyStore, DIB);
595         DbgItem->eraseFromParent();
596       } else if (DbgItem->getExpression()->startsWithDeref()) {
597         DbgItem->eraseFromParent();
598       }
599     }
600   };
601   ConvertDebugInfoForStore(Info.DbgUsers);
602   ConvertDebugInfoForStore(Info.DPUsers);
603 
604   // Remove dbg.assigns linked to the alloca as these are now redundant.
605   at::deleteAssignmentMarkers(AI);
606 
607   // Remove the (now dead) store and alloca.
608   Info.OnlyStore->eraseFromParent();
609   LBI.deleteValue(Info.OnlyStore);
610 
611   AI->eraseFromParent();
612   return true;
613 }
614 
615 /// Many allocas are only used within a single basic block.  If this is the
616 /// case, avoid traversing the CFG and inserting a lot of potentially useless
617 /// PHI nodes by just performing a single linear pass over the basic block
618 /// using the Alloca.
619 ///
620 /// If we cannot promote this alloca (because it is read before it is written),
621 /// return false.  This is necessary in cases where, due to control flow, the
622 /// alloca is undefined only on some control flow paths.  e.g. code like
623 /// this is correct in LLVM IR:
624 ///  // A is an alloca with no stores so far
625 ///  for (...) {
626 ///    int t = *A;
627 ///    if (!first_iteration)
628 ///      use(t);
629 ///    *A = 42;
630 ///  }
631 static bool
632 promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
633                          LargeBlockInfo &LBI, const DataLayout &DL,
634                          DominatorTree &DT, AssumptionCache *AC,
635                          SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
636                          SmallSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
637   // The trickiest case to handle is when we have large blocks. Because of this,
638   // this code is optimized assuming that large blocks happen.  This does not
639   // significantly pessimize the small block case.  This uses LargeBlockInfo to
640   // make it efficient to get the index of various operations in the block.
641 
642   // Walk the use-def list of the alloca, getting the locations of all stores.
643   using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
644   StoresByIndexTy StoresByIndex;
645 
646   for (User *U : AI->users())
647     if (StoreInst *SI = dyn_cast<StoreInst>(U))
648       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
649 
650   // Sort the stores by their index, making it efficient to do a lookup with a
651   // binary search.
652   llvm::sort(StoresByIndex, less_first());
653 
654   // Walk all of the loads from this alloca, replacing them with the nearest
655   // store above them, if any.
656   for (User *U : make_early_inc_range(AI->users())) {
657     LoadInst *LI = dyn_cast<LoadInst>(U);
658     if (!LI)
659       continue;
660 
661     unsigned LoadIdx = LBI.getInstructionIndex(LI);
662 
663     // Find the nearest store that has a lower index than this load.
664     StoresByIndexTy::iterator I = llvm::lower_bound(
665         StoresByIndex,
666         std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
667         less_first());
668     Value *ReplVal;
669     if (I == StoresByIndex.begin()) {
670       if (StoresByIndex.empty())
671         // If there are no stores, the load takes the undef value.
672         ReplVal = UndefValue::get(LI->getType());
673       else
674         // There is no store before this load, bail out (load may be affected
675         // by the following stores - see main comment).
676         return false;
677     } else {
678       // Otherwise, there was a store before this load, the load takes its
679       // value.
680       ReplVal = std::prev(I)->second->getOperand(0);
681     }
682 
683     convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
684 
685     // If the replacement value is the load, this must occur in unreachable
686     // code.
687     if (ReplVal == LI)
688       ReplVal = PoisonValue::get(LI->getType());
689 
690     LI->replaceAllUsesWith(ReplVal);
691     LI->eraseFromParent();
692     LBI.deleteValue(LI);
693   }
694 
695   // Remove the (now dead) stores and alloca.
696   DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
697   while (!AI->use_empty()) {
698     StoreInst *SI = cast<StoreInst>(AI->user_back());
699     // Update assignment tracking info for the store we're going to delete.
700     Info.AssignmentTracking.updateForDeletedStore(SI, DIB, DbgAssignsToDelete,
701                                                   DVRAssignsToDelete);
702     // Record debuginfo for the store before removing it.
703     auto DbgUpdateForStore = [&](auto &Container) {
704       for (auto *DbgItem : Container) {
705         if (DbgItem->isAddressOfVariable()) {
706           ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
707         }
708       }
709     };
710     DbgUpdateForStore(Info.DbgUsers);
711     DbgUpdateForStore(Info.DPUsers);
712 
713     SI->eraseFromParent();
714     LBI.deleteValue(SI);
715   }
716 
717   // Remove dbg.assigns linked to the alloca as these are now redundant.
718   at::deleteAssignmentMarkers(AI);
719   AI->eraseFromParent();
720 
721   // The alloca's debuginfo can be removed as well.
722   auto DbgUpdateForAlloca = [&](auto &Container) {
723     for (auto *DbgItem : Container)
724       if (DbgItem->isAddressOfVariable() ||
725           DbgItem->getExpression()->startsWithDeref())
726         DbgItem->eraseFromParent();
727   };
728   DbgUpdateForAlloca(Info.DbgUsers);
729   DbgUpdateForAlloca(Info.DPUsers);
730 
731   ++NumLocalPromoted;
732   return true;
733 }
734 
735 void PromoteMem2Reg::run() {
736   Function &F = *DT.getRoot()->getParent();
737 
738   AllocaDbgUsers.resize(Allocas.size());
739   AllocaATInfo.resize(Allocas.size());
740   AllocaDPUsers.resize(Allocas.size());
741 
742   AllocaInfo Info;
743   LargeBlockInfo LBI;
744   ForwardIDFCalculator IDF(DT);
745 
746   NoSignedZeros = F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool();
747 
748   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
749     AllocaInst *AI = Allocas[AllocaNum];
750 
751     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
752     assert(AI->getParent()->getParent() == &F &&
753            "All allocas should be in the same function, which is same as DF!");
754 
755     removeIntrinsicUsers(AI);
756 
757     if (AI->use_empty()) {
758       // If there are no uses of the alloca, just delete it now.
759       AI->eraseFromParent();
760 
761       // Remove the alloca from the Allocas list, since it has been processed
762       RemoveFromAllocasList(AllocaNum);
763       ++NumDeadAlloca;
764       continue;
765     }
766 
767     // Calculate the set of read and write-locations for each alloca.  This is
768     // analogous to finding the 'uses' and 'definitions' of each variable.
769     Info.AnalyzeAlloca(AI);
770 
771     // If there is only a single store to this value, replace any loads of
772     // it that are directly dominated by the definition with the value stored.
773     if (Info.DefiningBlocks.size() == 1) {
774       if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC,
775                                    &DbgAssignsToDelete, &DVRAssignsToDelete)) {
776         // The alloca has been processed, move on.
777         RemoveFromAllocasList(AllocaNum);
778         ++NumSingleStore;
779         continue;
780       }
781     }
782 
783     // If the alloca is only read and written in one basic block, just perform a
784     // linear sweep over the block to eliminate it.
785     if (Info.OnlyUsedInOneBlock &&
786         promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC,
787                                  &DbgAssignsToDelete, &DVRAssignsToDelete)) {
788       // The alloca has been processed, move on.
789       RemoveFromAllocasList(AllocaNum);
790       continue;
791     }
792 
793     // If we haven't computed a numbering for the BB's in the function, do so
794     // now.
795     if (BBNumbers.empty()) {
796       unsigned ID = 0;
797       for (auto &BB : F)
798         BBNumbers[&BB] = ID++;
799     }
800 
801     // Remember the dbg.declare intrinsic describing this alloca, if any.
802     if (!Info.DbgUsers.empty())
803       AllocaDbgUsers[AllocaNum] = Info.DbgUsers;
804     if (!Info.AssignmentTracking.empty())
805       AllocaATInfo[AllocaNum] = Info.AssignmentTracking;
806     if (!Info.DPUsers.empty())
807       AllocaDPUsers[AllocaNum] = Info.DPUsers;
808 
809     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
810     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
811 
812     // Unique the set of defining blocks for efficient lookup.
813     SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
814                                             Info.DefiningBlocks.end());
815 
816     // Determine which blocks the value is live in.  These are blocks which lead
817     // to uses.
818     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
819     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
820 
821     // At this point, we're committed to promoting the alloca using IDF's, and
822     // the standard SSA construction algorithm.  Determine which blocks need phi
823     // nodes and see if we can optimize out some work by avoiding insertion of
824     // dead phi nodes.
825     IDF.setLiveInBlocks(LiveInBlocks);
826     IDF.setDefiningBlocks(DefBlocks);
827     SmallVector<BasicBlock *, 32> PHIBlocks;
828     IDF.calculate(PHIBlocks);
829     llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
830       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
831     });
832 
833     unsigned CurrentVersion = 0;
834     for (BasicBlock *BB : PHIBlocks)
835       QueuePhiNode(BB, AllocaNum, CurrentVersion);
836   }
837 
838   if (Allocas.empty()) {
839     cleanUpDbgAssigns();
840     return; // All of the allocas must have been trivial!
841   }
842   LBI.clear();
843 
844   // Set the incoming values for the basic block to be null values for all of
845   // the alloca's.  We do this in case there is a load of a value that has not
846   // been stored yet.  In this case, it will get this null value.
847   RenamePassData::ValVector Values(Allocas.size());
848   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
849     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
850 
851   // When handling debug info, treat all incoming values as if they have unknown
852   // locations until proven otherwise.
853   RenamePassData::LocationVector Locations(Allocas.size());
854 
855   // Walks all basic blocks in the function performing the SSA rename algorithm
856   // and inserting the phi nodes we marked as necessary
857   std::vector<RenamePassData> RenamePassWorkList;
858   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
859                                   std::move(Locations));
860   do {
861     RenamePassData RPD = std::move(RenamePassWorkList.back());
862     RenamePassWorkList.pop_back();
863     // RenamePass may add new worklist entries.
864     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
865   } while (!RenamePassWorkList.empty());
866 
867   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
868   Visited.clear();
869 
870   // Remove the allocas themselves from the function.
871   for (Instruction *A : Allocas) {
872     // Remove dbg.assigns linked to the alloca as these are now redundant.
873     at::deleteAssignmentMarkers(A);
874     // If there are any uses of the alloca instructions left, they must be in
875     // unreachable basic blocks that were not processed by walking the dominator
876     // tree. Just delete the users now.
877     if (!A->use_empty())
878       A->replaceAllUsesWith(PoisonValue::get(A->getType()));
879     A->eraseFromParent();
880   }
881 
882   // Remove alloca's dbg.declare intrinsics from the function.
883   auto RemoveDbgDeclares = [&](auto &Container) {
884     for (auto &DbgUsers : Container) {
885       for (auto *DbgItem : DbgUsers)
886         if (DbgItem->isAddressOfVariable() ||
887             DbgItem->getExpression()->startsWithDeref())
888           DbgItem->eraseFromParent();
889     }
890   };
891   RemoveDbgDeclares(AllocaDbgUsers);
892   RemoveDbgDeclares(AllocaDPUsers);
893 
894   // Loop over all of the PHI nodes and see if there are any that we can get
895   // rid of because they merge all of the same incoming values.  This can
896   // happen due to undef values coming into the PHI nodes.  This process is
897   // iterative, because eliminating one PHI node can cause others to be removed.
898   bool EliminatedAPHI = true;
899   while (EliminatedAPHI) {
900     EliminatedAPHI = false;
901 
902     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
903     // simplify and RAUW them as we go.  If it was not, we could add uses to
904     // the values we replace with in a non-deterministic order, thus creating
905     // non-deterministic def->use chains.
906     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
907              I = NewPhiNodes.begin(),
908              E = NewPhiNodes.end();
909          I != E;) {
910       PHINode *PN = I->second;
911 
912       // If this PHI node merges one value and/or undefs, get the value.
913       if (Value *V = simplifyInstruction(PN, SQ)) {
914         PN->replaceAllUsesWith(V);
915         PN->eraseFromParent();
916         NewPhiNodes.erase(I++);
917         EliminatedAPHI = true;
918         continue;
919       }
920       ++I;
921     }
922   }
923 
924   // At this point, the renamer has added entries to PHI nodes for all reachable
925   // code.  Unfortunately, there may be unreachable blocks which the renamer
926   // hasn't traversed.  If this is the case, the PHI nodes may not
927   // have incoming values for all predecessors.  Loop over all PHI nodes we have
928   // created, inserting poison values if they are missing any incoming values.
929   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
930            I = NewPhiNodes.begin(),
931            E = NewPhiNodes.end();
932        I != E; ++I) {
933     // We want to do this once per basic block.  As such, only process a block
934     // when we find the PHI that is the first entry in the block.
935     PHINode *SomePHI = I->second;
936     BasicBlock *BB = SomePHI->getParent();
937     if (&BB->front() != SomePHI)
938       continue;
939 
940     // Only do work here if there the PHI nodes are missing incoming values.  We
941     // know that all PHI nodes that were inserted in a block will have the same
942     // number of incoming values, so we can just check any of them.
943     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
944       continue;
945 
946     // Get the preds for BB.
947     SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
948 
949     // Ok, now we know that all of the PHI nodes are missing entries for some
950     // basic blocks.  Start by sorting the incoming predecessors for efficient
951     // access.
952     auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
953       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
954     };
955     llvm::sort(Preds, CompareBBNumbers);
956 
957     // Now we loop through all BB's which have entries in SomePHI and remove
958     // them from the Preds list.
959     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
960       // Do a log(n) search of the Preds list for the entry we want.
961       SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
962           Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
963       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
964              "PHI node has entry for a block which is not a predecessor!");
965 
966       // Remove the entry
967       Preds.erase(EntIt);
968     }
969 
970     // At this point, the blocks left in the preds list must have dummy
971     // entries inserted into every PHI nodes for the block.  Update all the phi
972     // nodes in this block that we are inserting (there could be phis before
973     // mem2reg runs).
974     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
975     BasicBlock::iterator BBI = BB->begin();
976     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
977            SomePHI->getNumIncomingValues() == NumBadPreds) {
978       Value *PoisonVal = PoisonValue::get(SomePHI->getType());
979       for (BasicBlock *Pred : Preds)
980         SomePHI->addIncoming(PoisonVal, Pred);
981     }
982   }
983 
984   NewPhiNodes.clear();
985   cleanUpDbgAssigns();
986 }
987 
988 /// Determine which blocks the value is live in.
989 ///
990 /// These are blocks which lead to uses.  Knowing this allows us to avoid
991 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
992 /// inserted phi nodes would be dead).
993 void PromoteMem2Reg::ComputeLiveInBlocks(
994     AllocaInst *AI, AllocaInfo &Info,
995     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
996     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
997   // To determine liveness, we must iterate through the predecessors of blocks
998   // where the def is live.  Blocks are added to the worklist if we need to
999   // check their predecessors.  Start with all the using blocks.
1000   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
1001                                                     Info.UsingBlocks.end());
1002 
1003   // If any of the using blocks is also a definition block, check to see if the
1004   // definition occurs before or after the use.  If it happens before the use,
1005   // the value isn't really live-in.
1006   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
1007     BasicBlock *BB = LiveInBlockWorklist[i];
1008     if (!DefBlocks.count(BB))
1009       continue;
1010 
1011     // Okay, this is a block that both uses and defines the value.  If the first
1012     // reference to the alloca is a def (store), then we know it isn't live-in.
1013     for (BasicBlock::iterator I = BB->begin();; ++I) {
1014       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1015         if (SI->getOperand(1) != AI)
1016           continue;
1017 
1018         // We found a store to the alloca before a load.  The alloca is not
1019         // actually live-in here.
1020         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
1021         LiveInBlockWorklist.pop_back();
1022         --i;
1023         --e;
1024         break;
1025       }
1026 
1027       if (LoadInst *LI = dyn_cast<LoadInst>(I))
1028         // Okay, we found a load before a store to the alloca.  It is actually
1029         // live into this block.
1030         if (LI->getOperand(0) == AI)
1031           break;
1032     }
1033   }
1034 
1035   // Now that we have a set of blocks where the phi is live-in, recursively add
1036   // their predecessors until we find the full region the value is live.
1037   while (!LiveInBlockWorklist.empty()) {
1038     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1039 
1040     // The block really is live in here, insert it into the set.  If already in
1041     // the set, then it has already been processed.
1042     if (!LiveInBlocks.insert(BB).second)
1043       continue;
1044 
1045     // Since the value is live into BB, it is either defined in a predecessor or
1046     // live into it to.  Add the preds to the worklist unless they are a
1047     // defining block.
1048     for (BasicBlock *P : predecessors(BB)) {
1049       // The value is not live into a predecessor if it defines the value.
1050       if (DefBlocks.count(P))
1051         continue;
1052 
1053       // Otherwise it is, add to the worklist.
1054       LiveInBlockWorklist.push_back(P);
1055     }
1056   }
1057 }
1058 
1059 /// Queue a phi-node to be added to a basic-block for a specific Alloca.
1060 ///
1061 /// Returns true if there wasn't already a phi-node for that variable
1062 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
1063                                   unsigned &Version) {
1064   // Look up the basic-block in question.
1065   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
1066 
1067   // If the BB already has a phi node added for the i'th alloca then we're done!
1068   if (PN)
1069     return false;
1070 
1071   // Create a PhiNode using the dereferenced type... and add the phi-node to the
1072   // BasicBlock.
1073   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
1074                        Allocas[AllocaNo]->getName() + "." + Twine(Version++));
1075   PN->insertBefore(BB->begin());
1076   ++NumPHIInsert;
1077   PhiToAllocaMap[PN] = AllocaNo;
1078   return true;
1079 }
1080 
1081 /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
1082 /// create a merged location incorporating \p DL, or to set \p DL directly.
1083 static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
1084                                            bool ApplyMergedLoc) {
1085   if (ApplyMergedLoc)
1086     PN->applyMergedLocation(PN->getDebugLoc(), DL);
1087   else
1088     PN->setDebugLoc(DL);
1089 }
1090 
1091 /// Recursively traverse the CFG of the function, renaming loads and
1092 /// stores to the allocas which we are promoting.
1093 ///
1094 /// IncomingVals indicates what value each Alloca contains on exit from the
1095 /// predecessor block Pred.
1096 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
1097                                 RenamePassData::ValVector &IncomingVals,
1098                                 RenamePassData::LocationVector &IncomingLocs,
1099                                 std::vector<RenamePassData> &Worklist) {
1100 NextIteration:
1101   // If we are inserting any phi nodes into this BB, they will already be in the
1102   // block.
1103   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1104     // If we have PHI nodes to update, compute the number of edges from Pred to
1105     // BB.
1106     if (PhiToAllocaMap.count(APN)) {
1107       // We want to be able to distinguish between PHI nodes being inserted by
1108       // this invocation of mem2reg from those phi nodes that already existed in
1109       // the IR before mem2reg was run.  We determine that APN is being inserted
1110       // because it is missing incoming edges.  All other PHI nodes being
1111       // inserted by this pass of mem2reg will have the same number of incoming
1112       // operands so far.  Remember this count.
1113       unsigned NewPHINumOperands = APN->getNumOperands();
1114 
1115       unsigned NumEdges = llvm::count(successors(Pred), BB);
1116       assert(NumEdges && "Must be at least one edge from Pred to BB!");
1117 
1118       // Add entries for all the phis.
1119       BasicBlock::iterator PNI = BB->begin();
1120       do {
1121         unsigned AllocaNo = PhiToAllocaMap[APN];
1122 
1123         // Update the location of the phi node.
1124         updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
1125                                        APN->getNumIncomingValues() > 0);
1126 
1127         // Add N incoming values to the PHI node.
1128         for (unsigned i = 0; i != NumEdges; ++i)
1129           APN->addIncoming(IncomingVals[AllocaNo], Pred);
1130 
1131         // For the  sequence `return X > 0.0 ? X : -X`, it is expected that this
1132         // results in fabs intrinsic. However, without no-signed-zeros(nsz) flag
1133         // on the phi node generated at this stage, fabs folding does not
1134         // happen. So, we try to infer nsz flag from the function attributes to
1135         // enable this fabs folding.
1136         if (isa<FPMathOperator>(APN) && NoSignedZeros)
1137           APN->setHasNoSignedZeros(true);
1138 
1139         // The currently active variable for this block is now the PHI.
1140         IncomingVals[AllocaNo] = APN;
1141         AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
1142         auto ConvertDbgDeclares = [&](auto &Container) {
1143           for (auto *DbgItem : Container)
1144             if (DbgItem->isAddressOfVariable())
1145               ConvertDebugDeclareToDebugValue(DbgItem, APN, DIB);
1146         };
1147         ConvertDbgDeclares(AllocaDbgUsers[AllocaNo]);
1148         ConvertDbgDeclares(AllocaDPUsers[AllocaNo]);
1149 
1150         // Get the next phi node.
1151         ++PNI;
1152         APN = dyn_cast<PHINode>(PNI);
1153         if (!APN)
1154           break;
1155 
1156         // Verify that it is missing entries.  If not, it is not being inserted
1157         // by this mem2reg invocation so we want to ignore it.
1158       } while (APN->getNumOperands() == NewPHINumOperands);
1159     }
1160   }
1161 
1162   // Don't revisit blocks.
1163   if (!Visited.insert(BB).second)
1164     return;
1165 
1166   for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
1167     Instruction *I = &*II++; // get the instruction, increment iterator
1168 
1169     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1170       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1171       if (!Src)
1172         continue;
1173 
1174       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1175       if (AI == AllocaLookup.end())
1176         continue;
1177 
1178       Value *V = IncomingVals[AI->second];
1179       convertMetadataToAssumes(LI, V, SQ.DL, AC, &DT);
1180 
1181       // Anything using the load now uses the current value.
1182       LI->replaceAllUsesWith(V);
1183       LI->eraseFromParent();
1184     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1185       // Delete this instruction and mark the name as the current holder of the
1186       // value
1187       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1188       if (!Dest)
1189         continue;
1190 
1191       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1192       if (ai == AllocaLookup.end())
1193         continue;
1194 
1195       // what value were we writing?
1196       unsigned AllocaNo = ai->second;
1197       IncomingVals[AllocaNo] = SI->getOperand(0);
1198 
1199       // Record debuginfo for the store before removing it.
1200       IncomingLocs[AllocaNo] = SI->getDebugLoc();
1201       AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB, &DbgAssignsToDelete,
1202                                                    &DVRAssignsToDelete);
1203       auto ConvertDbgDeclares = [&](auto &Container) {
1204         for (auto *DbgItem : Container)
1205           if (DbgItem->isAddressOfVariable())
1206             ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
1207       };
1208       ConvertDbgDeclares(AllocaDbgUsers[ai->second]);
1209       ConvertDbgDeclares(AllocaDPUsers[ai->second]);
1210       SI->eraseFromParent();
1211     }
1212   }
1213 
1214   // 'Recurse' to our successors.
1215   succ_iterator I = succ_begin(BB), E = succ_end(BB);
1216   if (I == E)
1217     return;
1218 
1219   // Keep track of the successors so we don't visit the same successor twice
1220   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1221 
1222   // Handle the first successor without using the worklist.
1223   VisitedSuccs.insert(*I);
1224   Pred = BB;
1225   BB = *I;
1226   ++I;
1227 
1228   for (; I != E; ++I)
1229     if (VisitedSuccs.insert(*I).second)
1230       Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
1231 
1232   goto NextIteration;
1233 }
1234 
1235 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1236                            AssumptionCache *AC) {
1237   // If there is nothing to do, bail out...
1238   if (Allocas.empty())
1239     return;
1240 
1241   PromoteMem2Reg(Allocas, DT, AC).run();
1242 }
1243