xref: /llvm-project/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp (revision cd1e6a587be6352f63f180b1ff5e0a348a8da444)
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 public:
397   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
398                  AssumptionCache *AC)
399       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
400         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
401         AC(AC), SQ(DT.getRoot()->getDataLayout(),
402                    nullptr, &DT, AC) {}
403 
404   void run();
405 
406 private:
407   void RemoveFromAllocasList(unsigned &AllocaIdx) {
408     Allocas[AllocaIdx] = Allocas.back();
409     Allocas.pop_back();
410     --AllocaIdx;
411   }
412 
413   unsigned getNumPreds(const BasicBlock *BB) {
414     unsigned &NP = BBNumPreds[BB];
415     if (NP == 0)
416       NP = pred_size(BB) + 1;
417     return NP - 1;
418   }
419 
420   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
421                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
422                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
423   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
424                   RenamePassData::ValVector &IncVals,
425                   RenamePassData::LocationVector &IncLocs,
426                   std::vector<RenamePassData> &Worklist);
427   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
428 
429   /// Delete dbg.assigns that have been demoted to dbg.values.
430   void cleanUpDbgAssigns() {
431     for (auto *DAI : DbgAssignsToDelete)
432       DAI->eraseFromParent();
433     DbgAssignsToDelete.clear();
434     for (auto *DVR : DVRAssignsToDelete)
435       DVR->eraseFromParent();
436     DVRAssignsToDelete.clear();
437   }
438 };
439 
440 } // end anonymous namespace
441 
442 /// Given a LoadInst LI this adds assume(LI != null) after it.
443 static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
444   Function *AssumeIntrinsic =
445       Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
446   ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
447                                        Constant::getNullValue(LI->getType()));
448   LoadNotNull->insertAfter(LI);
449   CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
450   CI->insertAfter(LoadNotNull);
451   AC->registerAssumption(cast<AssumeInst>(CI));
452 }
453 
454 static void convertMetadataToAssumes(LoadInst *LI, Value *Val,
455                                      const DataLayout &DL, AssumptionCache *AC,
456                                      const DominatorTree *DT) {
457   if (isa<UndefValue>(Val) && LI->hasMetadata(LLVMContext::MD_noundef)) {
458     // Insert non-terminator unreachable.
459     LLVMContext &Ctx = LI->getContext();
460     new StoreInst(ConstantInt::getTrue(Ctx),
461                   PoisonValue::get(PointerType::getUnqual(Ctx)),
462                   /*isVolatile=*/false, Align(1), LI);
463     return;
464   }
465 
466   // If the load was marked as nonnull we don't want to lose that information
467   // when we erase this Load. So we preserve it with an assume. As !nonnull
468   // returns poison while assume violations are immediate undefined behavior,
469   // we can only do this if the value is known non-poison.
470   if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
471       LI->getMetadata(LLVMContext::MD_noundef) &&
472       !isKnownNonZero(Val, SimplifyQuery(DL, DT, AC, LI)))
473     addAssumeNonNull(AC, LI);
474 }
475 
476 static void removeIntrinsicUsers(AllocaInst *AI) {
477   // Knowing that this alloca is promotable, we know that it's safe to kill all
478   // instructions except for load and store.
479 
480   for (Use &U : llvm::make_early_inc_range(AI->uses())) {
481     Instruction *I = cast<Instruction>(U.getUser());
482     if (isa<LoadInst>(I) || isa<StoreInst>(I))
483       continue;
484 
485     // Drop the use of AI in droppable instructions.
486     if (I->isDroppable()) {
487       I->dropDroppableUse(U);
488       continue;
489     }
490 
491     if (!I->getType()->isVoidTy()) {
492       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
493       // Follow the use/def chain to erase them now instead of leaving it for
494       // dead code elimination later.
495       for (Use &UU : llvm::make_early_inc_range(I->uses())) {
496         Instruction *Inst = cast<Instruction>(UU.getUser());
497 
498         // Drop the use of I in droppable instructions.
499         if (Inst->isDroppable()) {
500           Inst->dropDroppableUse(UU);
501           continue;
502         }
503         Inst->eraseFromParent();
504       }
505     }
506     I->eraseFromParent();
507   }
508 }
509 
510 /// Rewrite as many loads as possible given a single store.
511 ///
512 /// When there is only a single store, we can use the domtree to trivially
513 /// replace all of the dominated loads with the stored value. Do so, and return
514 /// true if this has successfully promoted the alloca entirely. If this returns
515 /// false there were some loads which were not dominated by the single store
516 /// and thus must be phi-ed with undef. We fall back to the standard alloca
517 /// promotion algorithm in that case.
518 static bool
519 rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI,
520                          const DataLayout &DL, DominatorTree &DT,
521                          AssumptionCache *AC,
522                          SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
523                          SmallSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
524   StoreInst *OnlyStore = Info.OnlyStore;
525   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
526   BasicBlock *StoreBB = OnlyStore->getParent();
527   int StoreIndex = -1;
528 
529   // Clear out UsingBlocks.  We will reconstruct it here if needed.
530   Info.UsingBlocks.clear();
531 
532   for (User *U : make_early_inc_range(AI->users())) {
533     Instruction *UserInst = cast<Instruction>(U);
534     if (UserInst == OnlyStore)
535       continue;
536     LoadInst *LI = cast<LoadInst>(UserInst);
537 
538     // Okay, if we have a load from the alloca, we want to replace it with the
539     // only value stored to the alloca.  We can do this if the value is
540     // dominated by the store.  If not, we use the rest of the mem2reg machinery
541     // to insert the phi nodes as needed.
542     if (!StoringGlobalVal) { // Non-instructions are always dominated.
543       if (LI->getParent() == StoreBB) {
544         // If we have a use that is in the same block as the store, compare the
545         // indices of the two instructions to see which one came first.  If the
546         // load came before the store, we can't handle it.
547         if (StoreIndex == -1)
548           StoreIndex = LBI.getInstructionIndex(OnlyStore);
549 
550         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
551           // Can't handle this load, bail out.
552           Info.UsingBlocks.push_back(StoreBB);
553           continue;
554         }
555       } else if (!DT.dominates(StoreBB, LI->getParent())) {
556         // If the load and store are in different blocks, use BB dominance to
557         // check their relationships.  If the store doesn't dom the use, bail
558         // out.
559         Info.UsingBlocks.push_back(LI->getParent());
560         continue;
561       }
562     }
563 
564     // Otherwise, we *can* safely rewrite this load.
565     Value *ReplVal = OnlyStore->getOperand(0);
566     // If the replacement value is the load, this must occur in unreachable
567     // code.
568     if (ReplVal == LI)
569       ReplVal = PoisonValue::get(LI->getType());
570 
571     convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
572     LI->replaceAllUsesWith(ReplVal);
573     LI->eraseFromParent();
574     LBI.deleteValue(LI);
575   }
576 
577   // Finally, after the scan, check to see if the store is all that is left.
578   if (!Info.UsingBlocks.empty())
579     return false; // If not, we'll have to fall back for the remainder.
580 
581   DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
582   // Update assignment tracking info for the store we're going to delete.
583   Info.AssignmentTracking.updateForDeletedStore(
584       Info.OnlyStore, DIB, DbgAssignsToDelete, DVRAssignsToDelete);
585 
586   // Record debuginfo for the store and remove the declaration's
587   // debuginfo.
588   auto ConvertDebugInfoForStore = [&](auto &Container) {
589     for (auto *DbgItem : Container) {
590       if (DbgItem->isAddressOfVariable()) {
591         ConvertDebugDeclareToDebugValue(DbgItem, Info.OnlyStore, DIB);
592         DbgItem->eraseFromParent();
593       } else if (DbgItem->getExpression()->startsWithDeref()) {
594         DbgItem->eraseFromParent();
595       }
596     }
597   };
598   ConvertDebugInfoForStore(Info.DbgUsers);
599   ConvertDebugInfoForStore(Info.DPUsers);
600 
601   // Remove dbg.assigns linked to the alloca as these are now redundant.
602   at::deleteAssignmentMarkers(AI);
603 
604   // Remove the (now dead) store and alloca.
605   Info.OnlyStore->eraseFromParent();
606   LBI.deleteValue(Info.OnlyStore);
607 
608   AI->eraseFromParent();
609   return true;
610 }
611 
612 /// Many allocas are only used within a single basic block.  If this is the
613 /// case, avoid traversing the CFG and inserting a lot of potentially useless
614 /// PHI nodes by just performing a single linear pass over the basic block
615 /// using the Alloca.
616 ///
617 /// If we cannot promote this alloca (because it is read before it is written),
618 /// return false.  This is necessary in cases where, due to control flow, the
619 /// alloca is undefined only on some control flow paths.  e.g. code like
620 /// this is correct in LLVM IR:
621 ///  // A is an alloca with no stores so far
622 ///  for (...) {
623 ///    int t = *A;
624 ///    if (!first_iteration)
625 ///      use(t);
626 ///    *A = 42;
627 ///  }
628 static bool
629 promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
630                          LargeBlockInfo &LBI, const DataLayout &DL,
631                          DominatorTree &DT, AssumptionCache *AC,
632                          SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
633                          SmallSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
634   // The trickiest case to handle is when we have large blocks. Because of this,
635   // this code is optimized assuming that large blocks happen.  This does not
636   // significantly pessimize the small block case.  This uses LargeBlockInfo to
637   // make it efficient to get the index of various operations in the block.
638 
639   // Walk the use-def list of the alloca, getting the locations of all stores.
640   using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
641   StoresByIndexTy StoresByIndex;
642 
643   for (User *U : AI->users())
644     if (StoreInst *SI = dyn_cast<StoreInst>(U))
645       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
646 
647   // Sort the stores by their index, making it efficient to do a lookup with a
648   // binary search.
649   llvm::sort(StoresByIndex, less_first());
650 
651   // Walk all of the loads from this alloca, replacing them with the nearest
652   // store above them, if any.
653   for (User *U : make_early_inc_range(AI->users())) {
654     LoadInst *LI = dyn_cast<LoadInst>(U);
655     if (!LI)
656       continue;
657 
658     unsigned LoadIdx = LBI.getInstructionIndex(LI);
659 
660     // Find the nearest store that has a lower index than this load.
661     StoresByIndexTy::iterator I = llvm::lower_bound(
662         StoresByIndex,
663         std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
664         less_first());
665     Value *ReplVal;
666     if (I == StoresByIndex.begin()) {
667       if (StoresByIndex.empty())
668         // If there are no stores, the load takes the undef value.
669         ReplVal = UndefValue::get(LI->getType());
670       else
671         // There is no store before this load, bail out (load may be affected
672         // by the following stores - see main comment).
673         return false;
674     } else {
675       // Otherwise, there was a store before this load, the load takes its
676       // value.
677       ReplVal = std::prev(I)->second->getOperand(0);
678     }
679 
680     convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
681 
682     // If the replacement value is the load, this must occur in unreachable
683     // code.
684     if (ReplVal == LI)
685       ReplVal = PoisonValue::get(LI->getType());
686 
687     LI->replaceAllUsesWith(ReplVal);
688     LI->eraseFromParent();
689     LBI.deleteValue(LI);
690   }
691 
692   // Remove the (now dead) stores and alloca.
693   DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
694   while (!AI->use_empty()) {
695     StoreInst *SI = cast<StoreInst>(AI->user_back());
696     // Update assignment tracking info for the store we're going to delete.
697     Info.AssignmentTracking.updateForDeletedStore(SI, DIB, DbgAssignsToDelete,
698                                                   DVRAssignsToDelete);
699     // Record debuginfo for the store before removing it.
700     auto DbgUpdateForStore = [&](auto &Container) {
701       for (auto *DbgItem : Container) {
702         if (DbgItem->isAddressOfVariable()) {
703           ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
704         }
705       }
706     };
707     DbgUpdateForStore(Info.DbgUsers);
708     DbgUpdateForStore(Info.DPUsers);
709 
710     SI->eraseFromParent();
711     LBI.deleteValue(SI);
712   }
713 
714   // Remove dbg.assigns linked to the alloca as these are now redundant.
715   at::deleteAssignmentMarkers(AI);
716   AI->eraseFromParent();
717 
718   // The alloca's debuginfo can be removed as well.
719   auto DbgUpdateForAlloca = [&](auto &Container) {
720     for (auto *DbgItem : Container)
721       if (DbgItem->isAddressOfVariable() ||
722           DbgItem->getExpression()->startsWithDeref())
723         DbgItem->eraseFromParent();
724   };
725   DbgUpdateForAlloca(Info.DbgUsers);
726   DbgUpdateForAlloca(Info.DPUsers);
727 
728   ++NumLocalPromoted;
729   return true;
730 }
731 
732 void PromoteMem2Reg::run() {
733   Function &F = *DT.getRoot()->getParent();
734 
735   AllocaDbgUsers.resize(Allocas.size());
736   AllocaATInfo.resize(Allocas.size());
737   AllocaDPUsers.resize(Allocas.size());
738 
739   AllocaInfo Info;
740   LargeBlockInfo LBI;
741   ForwardIDFCalculator IDF(DT);
742 
743   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
744     AllocaInst *AI = Allocas[AllocaNum];
745 
746     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
747     assert(AI->getParent()->getParent() == &F &&
748            "All allocas should be in the same function, which is same as DF!");
749 
750     removeIntrinsicUsers(AI);
751 
752     if (AI->use_empty()) {
753       // If there are no uses of the alloca, just delete it now.
754       AI->eraseFromParent();
755 
756       // Remove the alloca from the Allocas list, since it has been processed
757       RemoveFromAllocasList(AllocaNum);
758       ++NumDeadAlloca;
759       continue;
760     }
761 
762     // Calculate the set of read and write-locations for each alloca.  This is
763     // analogous to finding the 'uses' and 'definitions' of each variable.
764     Info.AnalyzeAlloca(AI);
765 
766     // If there is only a single store to this value, replace any loads of
767     // it that are directly dominated by the definition with the value stored.
768     if (Info.DefiningBlocks.size() == 1) {
769       if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC,
770                                    &DbgAssignsToDelete, &DVRAssignsToDelete)) {
771         // The alloca has been processed, move on.
772         RemoveFromAllocasList(AllocaNum);
773         ++NumSingleStore;
774         continue;
775       }
776     }
777 
778     // If the alloca is only read and written in one basic block, just perform a
779     // linear sweep over the block to eliminate it.
780     if (Info.OnlyUsedInOneBlock &&
781         promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC,
782                                  &DbgAssignsToDelete, &DVRAssignsToDelete)) {
783       // The alloca has been processed, move on.
784       RemoveFromAllocasList(AllocaNum);
785       continue;
786     }
787 
788     // If we haven't computed a numbering for the BB's in the function, do so
789     // now.
790     if (BBNumbers.empty()) {
791       unsigned ID = 0;
792       for (auto &BB : F)
793         BBNumbers[&BB] = ID++;
794     }
795 
796     // Remember the dbg.declare intrinsic describing this alloca, if any.
797     if (!Info.DbgUsers.empty())
798       AllocaDbgUsers[AllocaNum] = Info.DbgUsers;
799     if (!Info.AssignmentTracking.empty())
800       AllocaATInfo[AllocaNum] = Info.AssignmentTracking;
801     if (!Info.DPUsers.empty())
802       AllocaDPUsers[AllocaNum] = Info.DPUsers;
803 
804     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
805     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
806 
807     // Unique the set of defining blocks for efficient lookup.
808     SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
809                                             Info.DefiningBlocks.end());
810 
811     // Determine which blocks the value is live in.  These are blocks which lead
812     // to uses.
813     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
814     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
815 
816     // At this point, we're committed to promoting the alloca using IDF's, and
817     // the standard SSA construction algorithm.  Determine which blocks need phi
818     // nodes and see if we can optimize out some work by avoiding insertion of
819     // dead phi nodes.
820     IDF.setLiveInBlocks(LiveInBlocks);
821     IDF.setDefiningBlocks(DefBlocks);
822     SmallVector<BasicBlock *, 32> PHIBlocks;
823     IDF.calculate(PHIBlocks);
824     llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
825       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
826     });
827 
828     unsigned CurrentVersion = 0;
829     for (BasicBlock *BB : PHIBlocks)
830       QueuePhiNode(BB, AllocaNum, CurrentVersion);
831   }
832 
833   if (Allocas.empty()) {
834     cleanUpDbgAssigns();
835     return; // All of the allocas must have been trivial!
836   }
837   LBI.clear();
838 
839   // Set the incoming values for the basic block to be null values for all of
840   // the alloca's.  We do this in case there is a load of a value that has not
841   // been stored yet.  In this case, it will get this null value.
842   RenamePassData::ValVector Values(Allocas.size());
843   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
844     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
845 
846   // When handling debug info, treat all incoming values as if they have unknown
847   // locations until proven otherwise.
848   RenamePassData::LocationVector Locations(Allocas.size());
849 
850   // Walks all basic blocks in the function performing the SSA rename algorithm
851   // and inserting the phi nodes we marked as necessary
852   std::vector<RenamePassData> RenamePassWorkList;
853   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
854                                   std::move(Locations));
855   do {
856     RenamePassData RPD = std::move(RenamePassWorkList.back());
857     RenamePassWorkList.pop_back();
858     // RenamePass may add new worklist entries.
859     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
860   } while (!RenamePassWorkList.empty());
861 
862   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
863   Visited.clear();
864 
865   // Remove the allocas themselves from the function.
866   for (Instruction *A : Allocas) {
867     // Remove dbg.assigns linked to the alloca as these are now redundant.
868     at::deleteAssignmentMarkers(A);
869     // If there are any uses of the alloca instructions left, they must be in
870     // unreachable basic blocks that were not processed by walking the dominator
871     // tree. Just delete the users now.
872     if (!A->use_empty())
873       A->replaceAllUsesWith(PoisonValue::get(A->getType()));
874     A->eraseFromParent();
875   }
876 
877   // Remove alloca's dbg.declare intrinsics from the function.
878   auto RemoveDbgDeclares = [&](auto &Container) {
879     for (auto &DbgUsers : Container) {
880       for (auto *DbgItem : DbgUsers)
881         if (DbgItem->isAddressOfVariable() ||
882             DbgItem->getExpression()->startsWithDeref())
883           DbgItem->eraseFromParent();
884     }
885   };
886   RemoveDbgDeclares(AllocaDbgUsers);
887   RemoveDbgDeclares(AllocaDPUsers);
888 
889   // Loop over all of the PHI nodes and see if there are any that we can get
890   // rid of because they merge all of the same incoming values.  This can
891   // happen due to undef values coming into the PHI nodes.  This process is
892   // iterative, because eliminating one PHI node can cause others to be removed.
893   bool EliminatedAPHI = true;
894   while (EliminatedAPHI) {
895     EliminatedAPHI = false;
896 
897     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
898     // simplify and RAUW them as we go.  If it was not, we could add uses to
899     // the values we replace with in a non-deterministic order, thus creating
900     // non-deterministic def->use chains.
901     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
902              I = NewPhiNodes.begin(),
903              E = NewPhiNodes.end();
904          I != E;) {
905       PHINode *PN = I->second;
906 
907       // If this PHI node merges one value and/or undefs, get the value.
908       if (Value *V = simplifyInstruction(PN, SQ)) {
909         PN->replaceAllUsesWith(V);
910         PN->eraseFromParent();
911         NewPhiNodes.erase(I++);
912         EliminatedAPHI = true;
913         continue;
914       }
915       ++I;
916     }
917   }
918 
919   // At this point, the renamer has added entries to PHI nodes for all reachable
920   // code.  Unfortunately, there may be unreachable blocks which the renamer
921   // hasn't traversed.  If this is the case, the PHI nodes may not
922   // have incoming values for all predecessors.  Loop over all PHI nodes we have
923   // created, inserting poison values if they are missing any incoming values.
924   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
925            I = NewPhiNodes.begin(),
926            E = NewPhiNodes.end();
927        I != E; ++I) {
928     // We want to do this once per basic block.  As such, only process a block
929     // when we find the PHI that is the first entry in the block.
930     PHINode *SomePHI = I->second;
931     BasicBlock *BB = SomePHI->getParent();
932     if (&BB->front() != SomePHI)
933       continue;
934 
935     // Only do work here if there the PHI nodes are missing incoming values.  We
936     // know that all PHI nodes that were inserted in a block will have the same
937     // number of incoming values, so we can just check any of them.
938     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
939       continue;
940 
941     // Get the preds for BB.
942     SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
943 
944     // Ok, now we know that all of the PHI nodes are missing entries for some
945     // basic blocks.  Start by sorting the incoming predecessors for efficient
946     // access.
947     auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
948       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
949     };
950     llvm::sort(Preds, CompareBBNumbers);
951 
952     // Now we loop through all BB's which have entries in SomePHI and remove
953     // them from the Preds list.
954     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
955       // Do a log(n) search of the Preds list for the entry we want.
956       SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
957           Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
958       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
959              "PHI node has entry for a block which is not a predecessor!");
960 
961       // Remove the entry
962       Preds.erase(EntIt);
963     }
964 
965     // At this point, the blocks left in the preds list must have dummy
966     // entries inserted into every PHI nodes for the block.  Update all the phi
967     // nodes in this block that we are inserting (there could be phis before
968     // mem2reg runs).
969     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
970     BasicBlock::iterator BBI = BB->begin();
971     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
972            SomePHI->getNumIncomingValues() == NumBadPreds) {
973       Value *PoisonVal = PoisonValue::get(SomePHI->getType());
974       for (BasicBlock *Pred : Preds)
975         SomePHI->addIncoming(PoisonVal, Pred);
976     }
977   }
978 
979   NewPhiNodes.clear();
980   cleanUpDbgAssigns();
981 }
982 
983 /// Determine which blocks the value is live in.
984 ///
985 /// These are blocks which lead to uses.  Knowing this allows us to avoid
986 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
987 /// inserted phi nodes would be dead).
988 void PromoteMem2Reg::ComputeLiveInBlocks(
989     AllocaInst *AI, AllocaInfo &Info,
990     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
991     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
992   // To determine liveness, we must iterate through the predecessors of blocks
993   // where the def is live.  Blocks are added to the worklist if we need to
994   // check their predecessors.  Start with all the using blocks.
995   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
996                                                     Info.UsingBlocks.end());
997 
998   // If any of the using blocks is also a definition block, check to see if the
999   // definition occurs before or after the use.  If it happens before the use,
1000   // the value isn't really live-in.
1001   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
1002     BasicBlock *BB = LiveInBlockWorklist[i];
1003     if (!DefBlocks.count(BB))
1004       continue;
1005 
1006     // Okay, this is a block that both uses and defines the value.  If the first
1007     // reference to the alloca is a def (store), then we know it isn't live-in.
1008     for (BasicBlock::iterator I = BB->begin();; ++I) {
1009       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1010         if (SI->getOperand(1) != AI)
1011           continue;
1012 
1013         // We found a store to the alloca before a load.  The alloca is not
1014         // actually live-in here.
1015         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
1016         LiveInBlockWorklist.pop_back();
1017         --i;
1018         --e;
1019         break;
1020       }
1021 
1022       if (LoadInst *LI = dyn_cast<LoadInst>(I))
1023         // Okay, we found a load before a store to the alloca.  It is actually
1024         // live into this block.
1025         if (LI->getOperand(0) == AI)
1026           break;
1027     }
1028   }
1029 
1030   // Now that we have a set of blocks where the phi is live-in, recursively add
1031   // their predecessors until we find the full region the value is live.
1032   while (!LiveInBlockWorklist.empty()) {
1033     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1034 
1035     // The block really is live in here, insert it into the set.  If already in
1036     // the set, then it has already been processed.
1037     if (!LiveInBlocks.insert(BB).second)
1038       continue;
1039 
1040     // Since the value is live into BB, it is either defined in a predecessor or
1041     // live into it to.  Add the preds to the worklist unless they are a
1042     // defining block.
1043     for (BasicBlock *P : predecessors(BB)) {
1044       // The value is not live into a predecessor if it defines the value.
1045       if (DefBlocks.count(P))
1046         continue;
1047 
1048       // Otherwise it is, add to the worklist.
1049       LiveInBlockWorklist.push_back(P);
1050     }
1051   }
1052 }
1053 
1054 /// Queue a phi-node to be added to a basic-block for a specific Alloca.
1055 ///
1056 /// Returns true if there wasn't already a phi-node for that variable
1057 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
1058                                   unsigned &Version) {
1059   // Look up the basic-block in question.
1060   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
1061 
1062   // If the BB already has a phi node added for the i'th alloca then we're done!
1063   if (PN)
1064     return false;
1065 
1066   // Create a PhiNode using the dereferenced type... and add the phi-node to the
1067   // BasicBlock.
1068   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
1069                        Allocas[AllocaNo]->getName() + "." + Twine(Version++));
1070   PN->insertBefore(BB->begin());
1071   ++NumPHIInsert;
1072   PhiToAllocaMap[PN] = AllocaNo;
1073   return true;
1074 }
1075 
1076 /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
1077 /// create a merged location incorporating \p DL, or to set \p DL directly.
1078 static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
1079                                            bool ApplyMergedLoc) {
1080   if (ApplyMergedLoc)
1081     PN->applyMergedLocation(PN->getDebugLoc(), DL);
1082   else
1083     PN->setDebugLoc(DL);
1084 }
1085 
1086 /// Recursively traverse the CFG of the function, renaming loads and
1087 /// stores to the allocas which we are promoting.
1088 ///
1089 /// IncomingVals indicates what value each Alloca contains on exit from the
1090 /// predecessor block Pred.
1091 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
1092                                 RenamePassData::ValVector &IncomingVals,
1093                                 RenamePassData::LocationVector &IncomingLocs,
1094                                 std::vector<RenamePassData> &Worklist) {
1095 NextIteration:
1096   // If we are inserting any phi nodes into this BB, they will already be in the
1097   // block.
1098   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1099     // If we have PHI nodes to update, compute the number of edges from Pred to
1100     // BB.
1101     if (PhiToAllocaMap.count(APN)) {
1102       // We want to be able to distinguish between PHI nodes being inserted by
1103       // this invocation of mem2reg from those phi nodes that already existed in
1104       // the IR before mem2reg was run.  We determine that APN is being inserted
1105       // because it is missing incoming edges.  All other PHI nodes being
1106       // inserted by this pass of mem2reg will have the same number of incoming
1107       // operands so far.  Remember this count.
1108       unsigned NewPHINumOperands = APN->getNumOperands();
1109 
1110       unsigned NumEdges = llvm::count(successors(Pred), BB);
1111       assert(NumEdges && "Must be at least one edge from Pred to BB!");
1112 
1113       // Add entries for all the phis.
1114       BasicBlock::iterator PNI = BB->begin();
1115       do {
1116         unsigned AllocaNo = PhiToAllocaMap[APN];
1117 
1118         // Update the location of the phi node.
1119         updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
1120                                        APN->getNumIncomingValues() > 0);
1121 
1122         // Add N incoming values to the PHI node.
1123         for (unsigned i = 0; i != NumEdges; ++i)
1124           APN->addIncoming(IncomingVals[AllocaNo], Pred);
1125 
1126         // For the  sequence `return X > 0.0 ? X : -X`, it is expected that this
1127         // results in fabs intrinsic. However, without no-signed-zeros(nsz) flag
1128         // on the phi node generated at this stage, fabs folding does not
1129         // happen. So, we try to infer nsz flag from the function attributes to
1130         // enable this fabs folding.
1131         if (APN->isComplete() && isa<FPMathOperator>(APN) &&
1132             BB->getParent()
1133                 ->getFnAttribute("no-signed-zeros-fp-math")
1134                 .getValueAsBool())
1135           APN->setHasNoSignedZeros(true);
1136 
1137         // The currently active variable for this block is now the PHI.
1138         IncomingVals[AllocaNo] = APN;
1139         AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
1140         auto ConvertDbgDeclares = [&](auto &Container) {
1141           for (auto *DbgItem : Container)
1142             if (DbgItem->isAddressOfVariable())
1143               ConvertDebugDeclareToDebugValue(DbgItem, APN, DIB);
1144         };
1145         ConvertDbgDeclares(AllocaDbgUsers[AllocaNo]);
1146         ConvertDbgDeclares(AllocaDPUsers[AllocaNo]);
1147 
1148         // Get the next phi node.
1149         ++PNI;
1150         APN = dyn_cast<PHINode>(PNI);
1151         if (!APN)
1152           break;
1153 
1154         // Verify that it is missing entries.  If not, it is not being inserted
1155         // by this mem2reg invocation so we want to ignore it.
1156       } while (APN->getNumOperands() == NewPHINumOperands);
1157     }
1158   }
1159 
1160   // Don't revisit blocks.
1161   if (!Visited.insert(BB).second)
1162     return;
1163 
1164   for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
1165     Instruction *I = &*II++; // get the instruction, increment iterator
1166 
1167     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1168       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1169       if (!Src)
1170         continue;
1171 
1172       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
1173       if (AI == AllocaLookup.end())
1174         continue;
1175 
1176       Value *V = IncomingVals[AI->second];
1177       convertMetadataToAssumes(LI, V, SQ.DL, AC, &DT);
1178 
1179       // Anything using the load now uses the current value.
1180       LI->replaceAllUsesWith(V);
1181       LI->eraseFromParent();
1182     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1183       // Delete this instruction and mark the name as the current holder of the
1184       // value
1185       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1186       if (!Dest)
1187         continue;
1188 
1189       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
1190       if (ai == AllocaLookup.end())
1191         continue;
1192 
1193       // what value were we writing?
1194       unsigned AllocaNo = ai->second;
1195       IncomingVals[AllocaNo] = SI->getOperand(0);
1196 
1197       // Record debuginfo for the store before removing it.
1198       IncomingLocs[AllocaNo] = SI->getDebugLoc();
1199       AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB, &DbgAssignsToDelete,
1200                                                    &DVRAssignsToDelete);
1201       auto ConvertDbgDeclares = [&](auto &Container) {
1202         for (auto *DbgItem : Container)
1203           if (DbgItem->isAddressOfVariable())
1204             ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
1205       };
1206       ConvertDbgDeclares(AllocaDbgUsers[ai->second]);
1207       ConvertDbgDeclares(AllocaDPUsers[ai->second]);
1208       SI->eraseFromParent();
1209     }
1210   }
1211 
1212   // 'Recurse' to our successors.
1213   succ_iterator I = succ_begin(BB), E = succ_end(BB);
1214   if (I == E)
1215     return;
1216 
1217   // Keep track of the successors so we don't visit the same successor twice
1218   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1219 
1220   // Handle the first successor without using the worklist.
1221   VisitedSuccs.insert(*I);
1222   Pred = BB;
1223   BB = *I;
1224   ++I;
1225 
1226   for (; I != E; ++I)
1227     if (VisitedSuccs.insert(*I).second)
1228       Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
1229 
1230   goto NextIteration;
1231 }
1232 
1233 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
1234                            AssumptionCache *AC) {
1235   // If there is nothing to do, bail out...
1236   if (Allocas.empty())
1237     return;
1238 
1239   PromoteMem2Reg(Allocas, DT, AC).run();
1240 }
1241