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