10b57cec5SDimitry Andric //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file promotes memory references to be register references.  It promotes
100b57cec5SDimitry Andric // alloca instructions which only have loads and stores as uses.  An alloca is
110b57cec5SDimitry Andric // transformed by using iterated dominator frontiers to place PHI nodes, then
120b57cec5SDimitry Andric // traversing the function in depth-first order to rewrite loads and stores as
130b57cec5SDimitry Andric // appropriate.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
280b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
290b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
300b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
310b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
320b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
331fd87a68SDimitry Andric #include "llvm/IR/DebugInfo.h"
34c9157d92SDimitry Andric #include "llvm/IR/DebugProgramInstruction.h"
350b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
360b57cec5SDimitry Andric #include "llvm/IR/Function.h"
370b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
380b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
390b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
400b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
410b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
420b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
430b57cec5SDimitry Andric #include "llvm/IR/Module.h"
440b57cec5SDimitry Andric #include "llvm/IR/Type.h"
450b57cec5SDimitry Andric #include "llvm/IR/User.h"
460b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
471fd87a68SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
480b57cec5SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
490b57cec5SDimitry Andric #include <algorithm>
500b57cec5SDimitry Andric #include <cassert>
510b57cec5SDimitry Andric #include <iterator>
520b57cec5SDimitry Andric #include <utility>
530b57cec5SDimitry Andric #include <vector>
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric using namespace llvm;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric #define DEBUG_TYPE "mem2reg"
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
600b57cec5SDimitry Andric STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
610b57cec5SDimitry Andric STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
620b57cec5SDimitry Andric STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
630b57cec5SDimitry Andric 
isAllocaPromotable(const AllocaInst * AI)640b57cec5SDimitry Andric bool llvm::isAllocaPromotable(const AllocaInst *AI) {
650b57cec5SDimitry Andric   // Only allow direct and non-volatile loads and stores...
660b57cec5SDimitry Andric   for (const User *U : AI->users()) {
670b57cec5SDimitry Andric     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
680b57cec5SDimitry Andric       // Note that atomic loads can be transformed; atomic semantics do
690b57cec5SDimitry Andric       // not have any meaning for a local alloca.
7081ad6265SDimitry Andric       if (LI->isVolatile() || LI->getType() != AI->getAllocatedType())
710b57cec5SDimitry Andric         return false;
720b57cec5SDimitry Andric     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
73349cc55cSDimitry Andric       if (SI->getValueOperand() == AI ||
74349cc55cSDimitry Andric           SI->getValueOperand()->getType() != AI->getAllocatedType())
750b57cec5SDimitry Andric         return false; // Don't allow a store OF the AI, only INTO the AI.
760b57cec5SDimitry Andric       // Note that atomic stores can be transformed; atomic semantics do
770b57cec5SDimitry Andric       // not have any meaning for a local alloca.
780b57cec5SDimitry Andric       if (SI->isVolatile())
790b57cec5SDimitry Andric         return false;
800b57cec5SDimitry Andric     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
81e8d8bef9SDimitry Andric       if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
820b57cec5SDimitry Andric         return false;
830b57cec5SDimitry Andric     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
84e8d8bef9SDimitry Andric       if (!onlyUsedByLifetimeMarkersOrDroppableInsts(BCI))
850b57cec5SDimitry Andric         return false;
860b57cec5SDimitry Andric     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
870b57cec5SDimitry Andric       if (!GEPI->hasAllZeroIndices())
880b57cec5SDimitry Andric         return false;
89e8d8bef9SDimitry Andric       if (!onlyUsedByLifetimeMarkersOrDroppableInsts(GEPI))
90e8d8bef9SDimitry Andric         return false;
91e8d8bef9SDimitry Andric     } else if (const AddrSpaceCastInst *ASCI = dyn_cast<AddrSpaceCastInst>(U)) {
92e8d8bef9SDimitry Andric       if (!onlyUsedByLifetimeMarkers(ASCI))
930b57cec5SDimitry Andric         return false;
940b57cec5SDimitry Andric     } else {
950b57cec5SDimitry Andric       return false;
960b57cec5SDimitry Andric     }
970b57cec5SDimitry Andric   }
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   return true;
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric namespace {
1030b57cec5SDimitry Andric 
createDebugValue(DIBuilder & DIB,Value * NewValue,DILocalVariable * Variable,DIExpression * Expression,const DILocation * DI,DPValue * InsertBefore)104*a58f00eaSDimitry Andric static DPValue *createDebugValue(DIBuilder &DIB, Value *NewValue,
105*a58f00eaSDimitry Andric                                  DILocalVariable *Variable,
106*a58f00eaSDimitry Andric                                  DIExpression *Expression, const DILocation *DI,
107*a58f00eaSDimitry Andric                                  DPValue *InsertBefore) {
108*a58f00eaSDimitry Andric   (void)DIB;
109*a58f00eaSDimitry Andric   return DPValue::createDPValue(NewValue, Variable, Expression, DI,
110*a58f00eaSDimitry Andric                                 *InsertBefore);
111*a58f00eaSDimitry Andric }
createDebugValue(DIBuilder & DIB,Value * NewValue,DILocalVariable * Variable,DIExpression * Expression,const DILocation * DI,Instruction * InsertBefore)112*a58f00eaSDimitry Andric static DbgValueInst *createDebugValue(DIBuilder &DIB, Value *NewValue,
113*a58f00eaSDimitry Andric                                       DILocalVariable *Variable,
114*a58f00eaSDimitry Andric                                       DIExpression *Expression,
115*a58f00eaSDimitry Andric                                       const DILocation *DI,
116*a58f00eaSDimitry Andric                                       Instruction *InsertBefore) {
117*a58f00eaSDimitry Andric   return static_cast<DbgValueInst *>(DIB.insertDbgValueIntrinsic(
118*a58f00eaSDimitry Andric       NewValue, Variable, Expression, DI, InsertBefore));
119*a58f00eaSDimitry Andric }
120*a58f00eaSDimitry Andric 
121bdd1243dSDimitry Andric /// Helper for updating assignment tracking debug info when promoting allocas.
122bdd1243dSDimitry Andric class AssignmentTrackingInfo {
123bdd1243dSDimitry Andric   /// DbgAssignIntrinsics linked to the alloca with at most one per variable
124bdd1243dSDimitry Andric   /// fragment. (i.e. not be a comprehensive set if there are multiple
125bdd1243dSDimitry Andric   /// dbg.assigns for one variable fragment).
126bdd1243dSDimitry Andric   SmallVector<DbgVariableIntrinsic *> DbgAssigns;
127*a58f00eaSDimitry Andric   SmallVector<DPValue *> DPVAssigns;
128bdd1243dSDimitry Andric 
129bdd1243dSDimitry Andric public:
init(AllocaInst * AI)130bdd1243dSDimitry Andric   void init(AllocaInst *AI) {
131bdd1243dSDimitry Andric     SmallSet<DebugVariable, 2> Vars;
132bdd1243dSDimitry Andric     for (DbgAssignIntrinsic *DAI : at::getAssignmentMarkers(AI)) {
133bdd1243dSDimitry Andric       if (Vars.insert(DebugVariable(DAI)).second)
134bdd1243dSDimitry Andric         DbgAssigns.push_back(DAI);
135bdd1243dSDimitry Andric     }
136*a58f00eaSDimitry Andric     for (DPValue *DPV : at::getDPVAssignmentMarkers(AI)) {
137*a58f00eaSDimitry Andric       if (Vars.insert(DebugVariable(DPV)).second)
138*a58f00eaSDimitry Andric         DPVAssigns.push_back(DPV);
139*a58f00eaSDimitry Andric     }
140bdd1243dSDimitry Andric   }
141bdd1243dSDimitry Andric 
142bdd1243dSDimitry Andric   /// Update assignment tracking debug info given for the to-be-deleted store
143bdd1243dSDimitry Andric   /// \p ToDelete that stores to this alloca.
144*a58f00eaSDimitry Andric   void
updateForDeletedStore(StoreInst * ToDelete,DIBuilder & DIB,SmallSet<DbgAssignIntrinsic *,8> * DbgAssignsToDelete,SmallSet<DPValue *,8> * DPVAssignsToDelete) const145*a58f00eaSDimitry Andric   updateForDeletedStore(StoreInst *ToDelete, DIBuilder &DIB,
146*a58f00eaSDimitry Andric                         SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
147*a58f00eaSDimitry Andric                         SmallSet<DPValue *, 8> *DPVAssignsToDelete) const {
148bdd1243dSDimitry Andric     // There's nothing to do if the alloca doesn't have any variables using
149bdd1243dSDimitry Andric     // assignment tracking.
150*a58f00eaSDimitry Andric     if (DbgAssigns.empty() && DPVAssigns.empty())
151bdd1243dSDimitry Andric       return;
152bdd1243dSDimitry Andric 
153fe013be4SDimitry Andric     // Insert a dbg.value where the linked dbg.assign is and remember to delete
154fe013be4SDimitry Andric     // the dbg.assign later. Demoting to dbg.value isn't necessary for
155fe013be4SDimitry Andric     // correctness but does reduce compile time and memory usage by reducing
156fe013be4SDimitry Andric     // unnecessary function-local metadata. Remember that we've seen a
157fe013be4SDimitry Andric     // dbg.assign for each variable fragment for the untracked store handling
158fe013be4SDimitry Andric     // (after this loop).
159fe013be4SDimitry Andric     SmallSet<DebugVariableAggregate, 2> VarHasDbgAssignForStore;
160*a58f00eaSDimitry Andric     auto InsertValueForAssign = [&](auto *DbgAssign, auto *&AssignList) {
161*a58f00eaSDimitry Andric       VarHasDbgAssignForStore.insert(DebugVariableAggregate(DbgAssign));
162*a58f00eaSDimitry Andric       AssignList->insert(DbgAssign);
163*a58f00eaSDimitry Andric       createDebugValue(DIB, DbgAssign->getValue(), DbgAssign->getVariable(),
164*a58f00eaSDimitry Andric                        DbgAssign->getExpression(), DbgAssign->getDebugLoc(),
165*a58f00eaSDimitry Andric                        DbgAssign);
166*a58f00eaSDimitry Andric     };
167*a58f00eaSDimitry Andric     for (auto *Assign : at::getAssignmentMarkers(ToDelete))
168*a58f00eaSDimitry Andric       InsertValueForAssign(Assign, DbgAssignsToDelete);
169*a58f00eaSDimitry Andric     for (auto *Assign : at::getDPVAssignmentMarkers(ToDelete))
170*a58f00eaSDimitry Andric       InsertValueForAssign(Assign, DPVAssignsToDelete);
171bdd1243dSDimitry Andric 
172bdd1243dSDimitry Andric     // It's possible for variables using assignment tracking to have no
173bdd1243dSDimitry Andric     // dbg.assign linked to this store. These are variables in DbgAssigns that
174bdd1243dSDimitry Andric     // are missing from VarHasDbgAssignForStore. Since there isn't a dbg.assign
175bdd1243dSDimitry Andric     // to mark the assignment - and the store is going to be deleted - insert a
176bdd1243dSDimitry Andric     // dbg.value to do that now. An untracked store may be either one that
177bdd1243dSDimitry Andric     // cannot be represented using assignment tracking (non-const offset or
178bdd1243dSDimitry Andric     // size) or one that is trackable but has had its DIAssignID attachment
179bdd1243dSDimitry Andric     // dropped accidentally.
180*a58f00eaSDimitry Andric     auto ConvertUnlinkedAssignToValue = [&](auto *Assign) {
181*a58f00eaSDimitry Andric       if (VarHasDbgAssignForStore.contains(DebugVariableAggregate(Assign)))
182*a58f00eaSDimitry Andric         return;
183*a58f00eaSDimitry Andric       ConvertDebugDeclareToDebugValue(Assign, ToDelete, DIB);
184*a58f00eaSDimitry Andric     };
185*a58f00eaSDimitry Andric     for_each(DbgAssigns, ConvertUnlinkedAssignToValue);
186*a58f00eaSDimitry Andric     for_each(DPVAssigns, ConvertUnlinkedAssignToValue);
187bdd1243dSDimitry Andric   }
188bdd1243dSDimitry Andric 
189bdd1243dSDimitry Andric   /// Update assignment tracking debug info given for the newly inserted PHI \p
190bdd1243dSDimitry Andric   /// NewPhi.
updateForNewPhi(PHINode * NewPhi,DIBuilder & DIB) const191bdd1243dSDimitry Andric   void updateForNewPhi(PHINode *NewPhi, DIBuilder &DIB) const {
192bdd1243dSDimitry Andric     // Regardless of the position of dbg.assigns relative to stores, the
193bdd1243dSDimitry Andric     // incoming values into a new PHI should be the same for the (imaginary)
194bdd1243dSDimitry Andric     // debug-phi.
195bdd1243dSDimitry Andric     for (auto *DAI : DbgAssigns)
196bdd1243dSDimitry Andric       ConvertDebugDeclareToDebugValue(DAI, NewPhi, DIB);
197*a58f00eaSDimitry Andric     for (auto *DPV : DPVAssigns)
198*a58f00eaSDimitry Andric       ConvertDebugDeclareToDebugValue(DPV, NewPhi, DIB);
199bdd1243dSDimitry Andric   }
200bdd1243dSDimitry Andric 
clear()201*a58f00eaSDimitry Andric   void clear() {
202*a58f00eaSDimitry Andric     DbgAssigns.clear();
203*a58f00eaSDimitry Andric     DPVAssigns.clear();
204*a58f00eaSDimitry Andric   }
empty()205*a58f00eaSDimitry Andric   bool empty() { return DbgAssigns.empty() && DPVAssigns.empty(); }
206bdd1243dSDimitry Andric };
207bdd1243dSDimitry Andric 
2080b57cec5SDimitry Andric struct AllocaInfo {
209e8d8bef9SDimitry Andric   using DbgUserVec = SmallVector<DbgVariableIntrinsic *, 1>;
210c9157d92SDimitry Andric   using DPUserVec = SmallVector<DPValue *, 1>;
211e8d8bef9SDimitry Andric 
2120b57cec5SDimitry Andric   SmallVector<BasicBlock *, 32> DefiningBlocks;
2130b57cec5SDimitry Andric   SmallVector<BasicBlock *, 32> UsingBlocks;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   StoreInst *OnlyStore;
2160b57cec5SDimitry Andric   BasicBlock *OnlyBlock;
2170b57cec5SDimitry Andric   bool OnlyUsedInOneBlock;
2180b57cec5SDimitry Andric 
219bdd1243dSDimitry Andric   /// Debug users of the alloca - does not include dbg.assign intrinsics.
220e8d8bef9SDimitry Andric   DbgUserVec DbgUsers;
221c9157d92SDimitry Andric   DPUserVec DPUsers;
222bdd1243dSDimitry Andric   /// Helper to update assignment tracking debug info.
223bdd1243dSDimitry Andric   AssignmentTrackingInfo AssignmentTracking;
2240b57cec5SDimitry Andric 
clear__anon1dd4706b0111::AllocaInfo2250b57cec5SDimitry Andric   void clear() {
2260b57cec5SDimitry Andric     DefiningBlocks.clear();
2270b57cec5SDimitry Andric     UsingBlocks.clear();
2280b57cec5SDimitry Andric     OnlyStore = nullptr;
2290b57cec5SDimitry Andric     OnlyBlock = nullptr;
2300b57cec5SDimitry Andric     OnlyUsedInOneBlock = true;
231e8d8bef9SDimitry Andric     DbgUsers.clear();
232c9157d92SDimitry Andric     DPUsers.clear();
233bdd1243dSDimitry Andric     AssignmentTracking.clear();
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
2370b57cec5SDimitry Andric   /// by the rest of the pass to reason about the uses of this alloca.
AnalyzeAlloca__anon1dd4706b0111::AllocaInfo2380b57cec5SDimitry Andric   void AnalyzeAlloca(AllocaInst *AI) {
2390b57cec5SDimitry Andric     clear();
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric     // As we scan the uses of the alloca instruction, keep track of stores,
2420b57cec5SDimitry Andric     // and decide whether all of the loads and stores to the alloca are within
2430b57cec5SDimitry Andric     // the same basic block.
244e8d8bef9SDimitry Andric     for (User *U : AI->users()) {
245e8d8bef9SDimitry Andric       Instruction *User = cast<Instruction>(U);
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
2480b57cec5SDimitry Andric         // Remember the basic blocks which define new values for the alloca
2490b57cec5SDimitry Andric         DefiningBlocks.push_back(SI->getParent());
2500b57cec5SDimitry Andric         OnlyStore = SI;
2510b57cec5SDimitry Andric       } else {
2520b57cec5SDimitry Andric         LoadInst *LI = cast<LoadInst>(User);
2530b57cec5SDimitry Andric         // Otherwise it must be a load instruction, keep track of variable
2540b57cec5SDimitry Andric         // reads.
2550b57cec5SDimitry Andric         UsingBlocks.push_back(LI->getParent());
2560b57cec5SDimitry Andric       }
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric       if (OnlyUsedInOneBlock) {
2590b57cec5SDimitry Andric         if (!OnlyBlock)
2600b57cec5SDimitry Andric           OnlyBlock = User->getParent();
2610b57cec5SDimitry Andric         else if (OnlyBlock != User->getParent())
2620b57cec5SDimitry Andric           OnlyUsedInOneBlock = false;
2630b57cec5SDimitry Andric       }
2640b57cec5SDimitry Andric     }
265bdd1243dSDimitry Andric     DbgUserVec AllDbgUsers;
266*a58f00eaSDimitry Andric     SmallVector<DPValue *> AllDPUsers;
267*a58f00eaSDimitry Andric     findDbgUsers(AllDbgUsers, AI, &AllDPUsers);
268bdd1243dSDimitry Andric     std::copy_if(AllDbgUsers.begin(), AllDbgUsers.end(),
269bdd1243dSDimitry Andric                  std::back_inserter(DbgUsers), [](DbgVariableIntrinsic *DII) {
270bdd1243dSDimitry Andric                    return !isa<DbgAssignIntrinsic>(DII);
271bdd1243dSDimitry Andric                  });
272*a58f00eaSDimitry Andric     std::copy_if(AllDPUsers.begin(), AllDPUsers.end(),
273*a58f00eaSDimitry Andric                  std::back_inserter(DPUsers),
274*a58f00eaSDimitry Andric                  [](DPValue *DPV) { return !DPV->isDbgAssign(); });
275bdd1243dSDimitry Andric     AssignmentTracking.init(AI);
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric };
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric /// Data package used by RenamePass().
2800b57cec5SDimitry Andric struct RenamePassData {
2810b57cec5SDimitry Andric   using ValVector = std::vector<Value *>;
2820b57cec5SDimitry Andric   using LocationVector = std::vector<DebugLoc>;
2830b57cec5SDimitry Andric 
RenamePassData__anon1dd4706b0111::RenamePassData2840b57cec5SDimitry Andric   RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
2850b57cec5SDimitry Andric       : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   BasicBlock *BB;
2880b57cec5SDimitry Andric   BasicBlock *Pred;
2890b57cec5SDimitry Andric   ValVector Values;
2900b57cec5SDimitry Andric   LocationVector Locations;
2910b57cec5SDimitry Andric };
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric /// This assigns and keeps a per-bb relative ordering of load/store
2940b57cec5SDimitry Andric /// instructions in the block that directly load or store an alloca.
2950b57cec5SDimitry Andric ///
2960b57cec5SDimitry Andric /// This functionality is important because it avoids scanning large basic
2970b57cec5SDimitry Andric /// blocks multiple times when promoting many allocas in the same block.
2980b57cec5SDimitry Andric class LargeBlockInfo {
2990b57cec5SDimitry Andric   /// For each instruction that we track, keep the index of the
3000b57cec5SDimitry Andric   /// instruction.
3010b57cec5SDimitry Andric   ///
3020b57cec5SDimitry Andric   /// The index starts out as the number of the instruction from the start of
3030b57cec5SDimitry Andric   /// the block.
3040b57cec5SDimitry Andric   DenseMap<const Instruction *, unsigned> InstNumbers;
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric public:
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   /// This code only looks at accesses to allocas.
isInterestingInstruction(const Instruction * I)3090b57cec5SDimitry Andric   static bool isInterestingInstruction(const Instruction *I) {
3100b57cec5SDimitry Andric     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
3110b57cec5SDimitry Andric            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
3120b57cec5SDimitry Andric   }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   /// Get or calculate the index of the specified instruction.
getInstructionIndex(const Instruction * I)3150b57cec5SDimitry Andric   unsigned getInstructionIndex(const Instruction *I) {
3160b57cec5SDimitry Andric     assert(isInterestingInstruction(I) &&
3170b57cec5SDimitry Andric            "Not a load/store to/from an alloca?");
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric     // If we already have this instruction number, return it.
3200b57cec5SDimitry Andric     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
3210b57cec5SDimitry Andric     if (It != InstNumbers.end())
3220b57cec5SDimitry Andric       return It->second;
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric     // Scan the whole block to get the instruction.  This accumulates
3250b57cec5SDimitry Andric     // information for every interesting instruction in the block, in order to
3260b57cec5SDimitry Andric     // avoid gratuitus rescans.
3270b57cec5SDimitry Andric     const BasicBlock *BB = I->getParent();
3280b57cec5SDimitry Andric     unsigned InstNo = 0;
3290b57cec5SDimitry Andric     for (const Instruction &BBI : *BB)
3300b57cec5SDimitry Andric       if (isInterestingInstruction(&BBI))
3310b57cec5SDimitry Andric         InstNumbers[&BBI] = InstNo++;
3320b57cec5SDimitry Andric     It = InstNumbers.find(I);
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric     assert(It != InstNumbers.end() && "Didn't insert instruction?");
3350b57cec5SDimitry Andric     return It->second;
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric 
deleteValue(const Instruction * I)3380b57cec5SDimitry Andric   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
3390b57cec5SDimitry Andric 
clear()3400b57cec5SDimitry Andric   void clear() { InstNumbers.clear(); }
3410b57cec5SDimitry Andric };
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric struct PromoteMem2Reg {
3440b57cec5SDimitry Andric   /// The alloca instructions being promoted.
3450b57cec5SDimitry Andric   std::vector<AllocaInst *> Allocas;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   DominatorTree &DT;
3480b57cec5SDimitry Andric   DIBuilder DIB;
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
3510b57cec5SDimitry Andric   AssumptionCache *AC;
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   const SimplifyQuery SQ;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   /// Reverse mapping of Allocas.
3560b57cec5SDimitry Andric   DenseMap<AllocaInst *, unsigned> AllocaLookup;
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric   /// The PhiNodes we're adding.
3590b57cec5SDimitry Andric   ///
3600b57cec5SDimitry Andric   /// That map is used to simplify some Phi nodes as we iterate over it, so
3610b57cec5SDimitry Andric   /// it should have deterministic iterators.  We could use a MapVector, but
3620b57cec5SDimitry Andric   /// since we already maintain a map from BasicBlock* to a stable numbering
3630b57cec5SDimitry Andric   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
3640b57cec5SDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   /// For each PHI node, keep track of which entry in Allocas it corresponds
3670b57cec5SDimitry Andric   /// to.
3680b57cec5SDimitry Andric   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   /// For each alloca, we keep track of the dbg.declare intrinsic that
3710b57cec5SDimitry Andric   /// describes it, if any, so that we can convert it to a dbg.value
3720b57cec5SDimitry Andric   /// intrinsic if the alloca gets promoted.
373e8d8bef9SDimitry Andric   SmallVector<AllocaInfo::DbgUserVec, 8> AllocaDbgUsers;
374c9157d92SDimitry Andric   SmallVector<AllocaInfo::DPUserVec, 8> AllocaDPUsers;
3750b57cec5SDimitry Andric 
376bdd1243dSDimitry Andric   /// For each alloca, keep an instance of a helper class that gives us an easy
377bdd1243dSDimitry Andric   /// way to update assignment tracking debug info if the alloca is promoted.
378bdd1243dSDimitry Andric   SmallVector<AssignmentTrackingInfo, 8> AllocaATInfo;
379fe013be4SDimitry Andric   /// A set of dbg.assigns to delete because they've been demoted to
380fe013be4SDimitry Andric   /// dbg.values. Call cleanUpDbgAssigns to delete them.
381fe013be4SDimitry Andric   SmallSet<DbgAssignIntrinsic *, 8> DbgAssignsToDelete;
382*a58f00eaSDimitry Andric   SmallSet<DPValue *, 8> DPVAssignsToDelete;
383bdd1243dSDimitry Andric 
3840b57cec5SDimitry Andric   /// The set of basic blocks the renamer has already visited.
3850b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Visited;
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   /// Contains a stable numbering of basic blocks to avoid non-determinstic
3880b57cec5SDimitry Andric   /// behavior.
3890b57cec5SDimitry Andric   DenseMap<BasicBlock *, unsigned> BBNumbers;
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   /// Lazily compute the number of predecessors a block has.
3920b57cec5SDimitry Andric   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric public:
PromoteMem2Reg__anon1dd4706b0111::PromoteMem2Reg3950b57cec5SDimitry Andric   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
3960b57cec5SDimitry Andric                  AssumptionCache *AC)
3970b57cec5SDimitry Andric       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
3980b57cec5SDimitry Andric         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
3990b57cec5SDimitry Andric         AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
4000b57cec5SDimitry Andric                    nullptr, &DT, AC) {}
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   void run();
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric private:
RemoveFromAllocasList__anon1dd4706b0111::PromoteMem2Reg4050b57cec5SDimitry Andric   void RemoveFromAllocasList(unsigned &AllocaIdx) {
4060b57cec5SDimitry Andric     Allocas[AllocaIdx] = Allocas.back();
4070b57cec5SDimitry Andric     Allocas.pop_back();
4080b57cec5SDimitry Andric     --AllocaIdx;
4090b57cec5SDimitry Andric   }
4100b57cec5SDimitry Andric 
getNumPreds__anon1dd4706b0111::PromoteMem2Reg4110b57cec5SDimitry Andric   unsigned getNumPreds(const BasicBlock *BB) {
4120b57cec5SDimitry Andric     unsigned &NP = BBNumPreds[BB];
4130b57cec5SDimitry Andric     if (NP == 0)
4140b57cec5SDimitry Andric       NP = pred_size(BB) + 1;
4150b57cec5SDimitry Andric     return NP - 1;
4160b57cec5SDimitry Andric   }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
4190b57cec5SDimitry Andric                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
4200b57cec5SDimitry Andric                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
4210b57cec5SDimitry Andric   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
4220b57cec5SDimitry Andric                   RenamePassData::ValVector &IncVals,
4230b57cec5SDimitry Andric                   RenamePassData::LocationVector &IncLocs,
4240b57cec5SDimitry Andric                   std::vector<RenamePassData> &Worklist);
4250b57cec5SDimitry Andric   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
426fe013be4SDimitry Andric 
427fe013be4SDimitry Andric   /// Delete dbg.assigns that have been demoted to dbg.values.
cleanUpDbgAssigns__anon1dd4706b0111::PromoteMem2Reg428fe013be4SDimitry Andric   void cleanUpDbgAssigns() {
429fe013be4SDimitry Andric     for (auto *DAI : DbgAssignsToDelete)
430fe013be4SDimitry Andric       DAI->eraseFromParent();
431fe013be4SDimitry Andric     DbgAssignsToDelete.clear();
432*a58f00eaSDimitry Andric     for (auto *DPV : DPVAssignsToDelete)
433*a58f00eaSDimitry Andric       DPV->eraseFromParent();
434*a58f00eaSDimitry Andric     DPVAssignsToDelete.clear();
435fe013be4SDimitry Andric   }
4360b57cec5SDimitry Andric };
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric } // end anonymous namespace
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric /// Given a LoadInst LI this adds assume(LI != null) after it.
addAssumeNonNull(AssumptionCache * AC,LoadInst * LI)4410b57cec5SDimitry Andric static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
4420b57cec5SDimitry Andric   Function *AssumeIntrinsic =
4430b57cec5SDimitry Andric       Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
4440b57cec5SDimitry Andric   ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
4450b57cec5SDimitry Andric                                        Constant::getNullValue(LI->getType()));
4460b57cec5SDimitry Andric   LoadNotNull->insertAfter(LI);
4470b57cec5SDimitry Andric   CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
4480b57cec5SDimitry Andric   CI->insertAfter(LoadNotNull);
449fe6060f1SDimitry Andric   AC->registerAssumption(cast<AssumeInst>(CI));
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric 
convertMetadataToAssumes(LoadInst * LI,Value * Val,const DataLayout & DL,AssumptionCache * AC,const DominatorTree * DT)452bdd1243dSDimitry Andric static void convertMetadataToAssumes(LoadInst *LI, Value *Val,
453bdd1243dSDimitry Andric                                      const DataLayout &DL, AssumptionCache *AC,
454bdd1243dSDimitry Andric                                      const DominatorTree *DT) {
455bdd1243dSDimitry Andric   // If the load was marked as nonnull we don't want to lose that information
456bdd1243dSDimitry Andric   // when we erase this Load. So we preserve it with an assume. As !nonnull
457bdd1243dSDimitry Andric   // returns poison while assume violations are immediate undefined behavior,
458bdd1243dSDimitry Andric   // we can only do this if the value is known non-poison.
459bdd1243dSDimitry Andric   if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
460bdd1243dSDimitry Andric       LI->getMetadata(LLVMContext::MD_noundef) &&
461bdd1243dSDimitry Andric       !isKnownNonZero(Val, DL, 0, AC, LI, DT))
462bdd1243dSDimitry Andric     addAssumeNonNull(AC, LI);
463bdd1243dSDimitry Andric }
464bdd1243dSDimitry Andric 
removeIntrinsicUsers(AllocaInst * AI)465e8d8bef9SDimitry Andric static void removeIntrinsicUsers(AllocaInst *AI) {
4660b57cec5SDimitry Andric   // Knowing that this alloca is promotable, we know that it's safe to kill all
4670b57cec5SDimitry Andric   // instructions except for load and store.
4680b57cec5SDimitry Andric 
469fe6060f1SDimitry Andric   for (Use &U : llvm::make_early_inc_range(AI->uses())) {
470fe6060f1SDimitry Andric     Instruction *I = cast<Instruction>(U.getUser());
4710b57cec5SDimitry Andric     if (isa<LoadInst>(I) || isa<StoreInst>(I))
4720b57cec5SDimitry Andric       continue;
4730b57cec5SDimitry Andric 
474e8d8bef9SDimitry Andric     // Drop the use of AI in droppable instructions.
475e8d8bef9SDimitry Andric     if (I->isDroppable()) {
476e8d8bef9SDimitry Andric       I->dropDroppableUse(U);
477e8d8bef9SDimitry Andric       continue;
478e8d8bef9SDimitry Andric     }
479e8d8bef9SDimitry Andric 
4800b57cec5SDimitry Andric     if (!I->getType()->isVoidTy()) {
4810b57cec5SDimitry Andric       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
4820b57cec5SDimitry Andric       // Follow the use/def chain to erase them now instead of leaving it for
4830b57cec5SDimitry Andric       // dead code elimination later.
484fe6060f1SDimitry Andric       for (Use &UU : llvm::make_early_inc_range(I->uses())) {
485fe6060f1SDimitry Andric         Instruction *Inst = cast<Instruction>(UU.getUser());
486e8d8bef9SDimitry Andric 
487e8d8bef9SDimitry Andric         // Drop the use of I in droppable instructions.
488e8d8bef9SDimitry Andric         if (Inst->isDroppable()) {
489e8d8bef9SDimitry Andric           Inst->dropDroppableUse(UU);
490e8d8bef9SDimitry Andric           continue;
491e8d8bef9SDimitry Andric         }
4920b57cec5SDimitry Andric         Inst->eraseFromParent();
4930b57cec5SDimitry Andric       }
4940b57cec5SDimitry Andric     }
4950b57cec5SDimitry Andric     I->eraseFromParent();
4960b57cec5SDimitry Andric   }
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric /// Rewrite as many loads as possible given a single store.
5000b57cec5SDimitry Andric ///
5010b57cec5SDimitry Andric /// When there is only a single store, we can use the domtree to trivially
5020b57cec5SDimitry Andric /// replace all of the dominated loads with the stored value. Do so, and return
5030b57cec5SDimitry Andric /// true if this has successfully promoted the alloca entirely. If this returns
5040b57cec5SDimitry Andric /// false there were some loads which were not dominated by the single store
5050b57cec5SDimitry Andric /// and thus must be phi-ed with undef. We fall back to the standard alloca
5060b57cec5SDimitry Andric /// promotion algorithm in that case.
507*a58f00eaSDimitry Andric static bool
rewriteSingleStoreAlloca(AllocaInst * AI,AllocaInfo & Info,LargeBlockInfo & LBI,const DataLayout & DL,DominatorTree & DT,AssumptionCache * AC,SmallSet<DbgAssignIntrinsic *,8> * DbgAssignsToDelete,SmallSet<DPValue *,8> * DPVAssignsToDelete)508*a58f00eaSDimitry Andric rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI,
509*a58f00eaSDimitry Andric                          const DataLayout &DL, DominatorTree &DT,
510*a58f00eaSDimitry Andric                          AssumptionCache *AC,
511*a58f00eaSDimitry Andric                          SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
512*a58f00eaSDimitry Andric                          SmallSet<DPValue *, 8> *DPVAssignsToDelete) {
5130b57cec5SDimitry Andric   StoreInst *OnlyStore = Info.OnlyStore;
5140b57cec5SDimitry Andric   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
5150b57cec5SDimitry Andric   BasicBlock *StoreBB = OnlyStore->getParent();
5160b57cec5SDimitry Andric   int StoreIndex = -1;
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // Clear out UsingBlocks.  We will reconstruct it here if needed.
5190b57cec5SDimitry Andric   Info.UsingBlocks.clear();
5200b57cec5SDimitry Andric 
521e8d8bef9SDimitry Andric   for (User *U : make_early_inc_range(AI->users())) {
522e8d8bef9SDimitry Andric     Instruction *UserInst = cast<Instruction>(U);
5230b57cec5SDimitry Andric     if (UserInst == OnlyStore)
5240b57cec5SDimitry Andric       continue;
5250b57cec5SDimitry Andric     LoadInst *LI = cast<LoadInst>(UserInst);
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric     // Okay, if we have a load from the alloca, we want to replace it with the
5280b57cec5SDimitry Andric     // only value stored to the alloca.  We can do this if the value is
5290b57cec5SDimitry Andric     // dominated by the store.  If not, we use the rest of the mem2reg machinery
5300b57cec5SDimitry Andric     // to insert the phi nodes as needed.
5310b57cec5SDimitry Andric     if (!StoringGlobalVal) { // Non-instructions are always dominated.
5320b57cec5SDimitry Andric       if (LI->getParent() == StoreBB) {
5330b57cec5SDimitry Andric         // If we have a use that is in the same block as the store, compare the
5340b57cec5SDimitry Andric         // indices of the two instructions to see which one came first.  If the
5350b57cec5SDimitry Andric         // load came before the store, we can't handle it.
5360b57cec5SDimitry Andric         if (StoreIndex == -1)
5370b57cec5SDimitry Andric           StoreIndex = LBI.getInstructionIndex(OnlyStore);
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
5400b57cec5SDimitry Andric           // Can't handle this load, bail out.
5410b57cec5SDimitry Andric           Info.UsingBlocks.push_back(StoreBB);
5420b57cec5SDimitry Andric           continue;
5430b57cec5SDimitry Andric         }
5440b57cec5SDimitry Andric       } else if (!DT.dominates(StoreBB, LI->getParent())) {
5450b57cec5SDimitry Andric         // If the load and store are in different blocks, use BB dominance to
5460b57cec5SDimitry Andric         // check their relationships.  If the store doesn't dom the use, bail
5470b57cec5SDimitry Andric         // out.
5480b57cec5SDimitry Andric         Info.UsingBlocks.push_back(LI->getParent());
5490b57cec5SDimitry Andric         continue;
5500b57cec5SDimitry Andric       }
5510b57cec5SDimitry Andric     }
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric     // Otherwise, we *can* safely rewrite this load.
5540b57cec5SDimitry Andric     Value *ReplVal = OnlyStore->getOperand(0);
5550b57cec5SDimitry Andric     // If the replacement value is the load, this must occur in unreachable
5560b57cec5SDimitry Andric     // code.
5570b57cec5SDimitry Andric     if (ReplVal == LI)
558fe6060f1SDimitry Andric       ReplVal = PoisonValue::get(LI->getType());
5590b57cec5SDimitry Andric 
560bdd1243dSDimitry Andric     convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
5610b57cec5SDimitry Andric     LI->replaceAllUsesWith(ReplVal);
5620b57cec5SDimitry Andric     LI->eraseFromParent();
5630b57cec5SDimitry Andric     LBI.deleteValue(LI);
5640b57cec5SDimitry Andric   }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // Finally, after the scan, check to see if the store is all that is left.
5670b57cec5SDimitry Andric   if (!Info.UsingBlocks.empty())
5680b57cec5SDimitry Andric     return false; // If not, we'll have to fall back for the remainder.
5690b57cec5SDimitry Andric 
570bdd1243dSDimitry Andric   DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
571bdd1243dSDimitry Andric   // Update assignment tracking info for the store we're going to delete.
572*a58f00eaSDimitry Andric   Info.AssignmentTracking.updateForDeletedStore(
573*a58f00eaSDimitry Andric       Info.OnlyStore, DIB, DbgAssignsToDelete, DPVAssignsToDelete);
574bdd1243dSDimitry Andric 
5750b57cec5SDimitry Andric   // Record debuginfo for the store and remove the declaration's
5760b57cec5SDimitry Andric   // debuginfo.
577c9157d92SDimitry Andric   auto ConvertDebugInfoForStore = [&](auto &Container) {
578c9157d92SDimitry Andric     for (auto *DbgItem : Container) {
579c9157d92SDimitry Andric       if (DbgItem->isAddressOfVariable()) {
580c9157d92SDimitry Andric         ConvertDebugDeclareToDebugValue(DbgItem, Info.OnlyStore, DIB);
581c9157d92SDimitry Andric         DbgItem->eraseFromParent();
582c9157d92SDimitry Andric       } else if (DbgItem->getExpression()->startsWithDeref()) {
583c9157d92SDimitry Andric         DbgItem->eraseFromParent();
584e8d8bef9SDimitry Andric       }
5850b57cec5SDimitry Andric     }
586c9157d92SDimitry Andric   };
587c9157d92SDimitry Andric   ConvertDebugInfoForStore(Info.DbgUsers);
588c9157d92SDimitry Andric   ConvertDebugInfoForStore(Info.DPUsers);
589bdd1243dSDimitry Andric 
590bdd1243dSDimitry Andric   // Remove dbg.assigns linked to the alloca as these are now redundant.
591bdd1243dSDimitry Andric   at::deleteAssignmentMarkers(AI);
592bdd1243dSDimitry Andric 
5930b57cec5SDimitry Andric   // Remove the (now dead) store and alloca.
5940b57cec5SDimitry Andric   Info.OnlyStore->eraseFromParent();
5950b57cec5SDimitry Andric   LBI.deleteValue(Info.OnlyStore);
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   AI->eraseFromParent();
5980b57cec5SDimitry Andric   return true;
5990b57cec5SDimitry Andric }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric /// Many allocas are only used within a single basic block.  If this is the
6020b57cec5SDimitry Andric /// case, avoid traversing the CFG and inserting a lot of potentially useless
6030b57cec5SDimitry Andric /// PHI nodes by just performing a single linear pass over the basic block
6040b57cec5SDimitry Andric /// using the Alloca.
6050b57cec5SDimitry Andric ///
6060b57cec5SDimitry Andric /// If we cannot promote this alloca (because it is read before it is written),
6070b57cec5SDimitry Andric /// return false.  This is necessary in cases where, due to control flow, the
6080b57cec5SDimitry Andric /// alloca is undefined only on some control flow paths.  e.g. code like
6090b57cec5SDimitry Andric /// this is correct in LLVM IR:
6100b57cec5SDimitry Andric ///  // A is an alloca with no stores so far
6110b57cec5SDimitry Andric ///  for (...) {
6120b57cec5SDimitry Andric ///    int t = *A;
6130b57cec5SDimitry Andric ///    if (!first_iteration)
6140b57cec5SDimitry Andric ///      use(t);
6150b57cec5SDimitry Andric ///    *A = 42;
6160b57cec5SDimitry Andric ///  }
617*a58f00eaSDimitry Andric static bool
promoteSingleBlockAlloca(AllocaInst * AI,const AllocaInfo & Info,LargeBlockInfo & LBI,const DataLayout & DL,DominatorTree & DT,AssumptionCache * AC,SmallSet<DbgAssignIntrinsic *,8> * DbgAssignsToDelete,SmallSet<DPValue *,8> * DPVAssignsToDelete)618*a58f00eaSDimitry Andric promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
619*a58f00eaSDimitry Andric                          LargeBlockInfo &LBI, const DataLayout &DL,
620*a58f00eaSDimitry Andric                          DominatorTree &DT, AssumptionCache *AC,
621*a58f00eaSDimitry Andric                          SmallSet<DbgAssignIntrinsic *, 8> *DbgAssignsToDelete,
622*a58f00eaSDimitry Andric                          SmallSet<DPValue *, 8> *DPVAssignsToDelete) {
6230b57cec5SDimitry Andric   // The trickiest case to handle is when we have large blocks. Because of this,
6240b57cec5SDimitry Andric   // this code is optimized assuming that large blocks happen.  This does not
6250b57cec5SDimitry Andric   // significantly pessimize the small block case.  This uses LargeBlockInfo to
6260b57cec5SDimitry Andric   // make it efficient to get the index of various operations in the block.
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // Walk the use-def list of the alloca, getting the locations of all stores.
6290b57cec5SDimitry Andric   using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
6300b57cec5SDimitry Andric   StoresByIndexTy StoresByIndex;
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   for (User *U : AI->users())
6330b57cec5SDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(U))
6340b57cec5SDimitry Andric       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   // Sort the stores by their index, making it efficient to do a lookup with a
6370b57cec5SDimitry Andric   // binary search.
6380b57cec5SDimitry Andric   llvm::sort(StoresByIndex, less_first());
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // Walk all of the loads from this alloca, replacing them with the nearest
6410b57cec5SDimitry Andric   // store above them, if any.
642e8d8bef9SDimitry Andric   for (User *U : make_early_inc_range(AI->users())) {
643e8d8bef9SDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(U);
6440b57cec5SDimitry Andric     if (!LI)
6450b57cec5SDimitry Andric       continue;
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric     unsigned LoadIdx = LBI.getInstructionIndex(LI);
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric     // Find the nearest store that has a lower index than this load.
6500b57cec5SDimitry Andric     StoresByIndexTy::iterator I = llvm::lower_bound(
6510b57cec5SDimitry Andric         StoresByIndex,
6520b57cec5SDimitry Andric         std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
6530b57cec5SDimitry Andric         less_first());
654753f127fSDimitry Andric     Value *ReplVal;
6550b57cec5SDimitry Andric     if (I == StoresByIndex.begin()) {
6560b57cec5SDimitry Andric       if (StoresByIndex.empty())
6570b57cec5SDimitry Andric         // If there are no stores, the load takes the undef value.
658753f127fSDimitry Andric         ReplVal = UndefValue::get(LI->getType());
6590b57cec5SDimitry Andric       else
6600b57cec5SDimitry Andric         // There is no store before this load, bail out (load may be affected
6610b57cec5SDimitry Andric         // by the following stores - see main comment).
6620b57cec5SDimitry Andric         return false;
6630b57cec5SDimitry Andric     } else {
664753f127fSDimitry Andric       // Otherwise, there was a store before this load, the load takes its
665753f127fSDimitry Andric       // value.
666753f127fSDimitry Andric       ReplVal = std::prev(I)->second->getOperand(0);
667753f127fSDimitry Andric     }
668753f127fSDimitry Andric 
669bdd1243dSDimitry Andric     convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric     // If the replacement value is the load, this must occur in unreachable
6720b57cec5SDimitry Andric     // code.
6730b57cec5SDimitry Andric     if (ReplVal == LI)
674fe6060f1SDimitry Andric       ReplVal = PoisonValue::get(LI->getType());
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     LI->replaceAllUsesWith(ReplVal);
6770b57cec5SDimitry Andric     LI->eraseFromParent();
6780b57cec5SDimitry Andric     LBI.deleteValue(LI);
6790b57cec5SDimitry Andric   }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   // Remove the (now dead) stores and alloca.
682bdd1243dSDimitry Andric   DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
6830b57cec5SDimitry Andric   while (!AI->use_empty()) {
6840b57cec5SDimitry Andric     StoreInst *SI = cast<StoreInst>(AI->user_back());
685bdd1243dSDimitry Andric     // Update assignment tracking info for the store we're going to delete.
686*a58f00eaSDimitry Andric     Info.AssignmentTracking.updateForDeletedStore(SI, DIB, DbgAssignsToDelete,
687*a58f00eaSDimitry Andric                                                   DPVAssignsToDelete);
6880b57cec5SDimitry Andric     // Record debuginfo for the store before removing it.
689c9157d92SDimitry Andric     auto DbgUpdateForStore = [&](auto &Container) {
690c9157d92SDimitry Andric       for (auto *DbgItem : Container) {
691c9157d92SDimitry Andric         if (DbgItem->isAddressOfVariable()) {
692c9157d92SDimitry Andric           ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
6930b57cec5SDimitry Andric         }
694e8d8bef9SDimitry Andric       }
695c9157d92SDimitry Andric     };
696c9157d92SDimitry Andric     DbgUpdateForStore(Info.DbgUsers);
697c9157d92SDimitry Andric     DbgUpdateForStore(Info.DPUsers);
698c9157d92SDimitry Andric 
6990b57cec5SDimitry Andric     SI->eraseFromParent();
7000b57cec5SDimitry Andric     LBI.deleteValue(SI);
7010b57cec5SDimitry Andric   }
7020b57cec5SDimitry Andric 
703bdd1243dSDimitry Andric   // Remove dbg.assigns linked to the alloca as these are now redundant.
704bdd1243dSDimitry Andric   at::deleteAssignmentMarkers(AI);
7050b57cec5SDimitry Andric   AI->eraseFromParent();
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   // The alloca's debuginfo can be removed as well.
708c9157d92SDimitry Andric   auto DbgUpdateForAlloca = [&](auto &Container) {
709c9157d92SDimitry Andric     for (auto *DbgItem : Container)
710c9157d92SDimitry Andric       if (DbgItem->isAddressOfVariable() ||
711c9157d92SDimitry Andric           DbgItem->getExpression()->startsWithDeref())
712c9157d92SDimitry Andric         DbgItem->eraseFromParent();
713c9157d92SDimitry Andric   };
714c9157d92SDimitry Andric   DbgUpdateForAlloca(Info.DbgUsers);
715c9157d92SDimitry Andric   DbgUpdateForAlloca(Info.DPUsers);
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   ++NumLocalPromoted;
7180b57cec5SDimitry Andric   return true;
7190b57cec5SDimitry Andric }
7200b57cec5SDimitry Andric 
run()7210b57cec5SDimitry Andric void PromoteMem2Reg::run() {
7220b57cec5SDimitry Andric   Function &F = *DT.getRoot()->getParent();
7230b57cec5SDimitry Andric 
724e8d8bef9SDimitry Andric   AllocaDbgUsers.resize(Allocas.size());
725bdd1243dSDimitry Andric   AllocaATInfo.resize(Allocas.size());
726c9157d92SDimitry Andric   AllocaDPUsers.resize(Allocas.size());
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   AllocaInfo Info;
7290b57cec5SDimitry Andric   LargeBlockInfo LBI;
7300b57cec5SDimitry Andric   ForwardIDFCalculator IDF(DT);
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
7330b57cec5SDimitry Andric     AllocaInst *AI = Allocas[AllocaNum];
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
7360b57cec5SDimitry Andric     assert(AI->getParent()->getParent() == &F &&
7370b57cec5SDimitry Andric            "All allocas should be in the same function, which is same as DF!");
7380b57cec5SDimitry Andric 
739e8d8bef9SDimitry Andric     removeIntrinsicUsers(AI);
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric     if (AI->use_empty()) {
7420b57cec5SDimitry Andric       // If there are no uses of the alloca, just delete it now.
7430b57cec5SDimitry Andric       AI->eraseFromParent();
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric       // Remove the alloca from the Allocas list, since it has been processed
7460b57cec5SDimitry Andric       RemoveFromAllocasList(AllocaNum);
7470b57cec5SDimitry Andric       ++NumDeadAlloca;
7480b57cec5SDimitry Andric       continue;
7490b57cec5SDimitry Andric     }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric     // Calculate the set of read and write-locations for each alloca.  This is
7520b57cec5SDimitry Andric     // analogous to finding the 'uses' and 'definitions' of each variable.
7530b57cec5SDimitry Andric     Info.AnalyzeAlloca(AI);
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric     // If there is only a single store to this value, replace any loads of
7560b57cec5SDimitry Andric     // it that are directly dominated by the definition with the value stored.
7570b57cec5SDimitry Andric     if (Info.DefiningBlocks.size() == 1) {
758fe013be4SDimitry Andric       if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC,
759*a58f00eaSDimitry Andric                                    &DbgAssignsToDelete, &DPVAssignsToDelete)) {
7600b57cec5SDimitry Andric         // The alloca has been processed, move on.
7610b57cec5SDimitry Andric         RemoveFromAllocasList(AllocaNum);
7620b57cec5SDimitry Andric         ++NumSingleStore;
7630b57cec5SDimitry Andric         continue;
7640b57cec5SDimitry Andric       }
7650b57cec5SDimitry Andric     }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric     // If the alloca is only read and written in one basic block, just perform a
7680b57cec5SDimitry Andric     // linear sweep over the block to eliminate it.
7690b57cec5SDimitry Andric     if (Info.OnlyUsedInOneBlock &&
770fe013be4SDimitry Andric         promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC,
771*a58f00eaSDimitry Andric                                  &DbgAssignsToDelete, &DPVAssignsToDelete)) {
7720b57cec5SDimitry Andric       // The alloca has been processed, move on.
7730b57cec5SDimitry Andric       RemoveFromAllocasList(AllocaNum);
7740b57cec5SDimitry Andric       continue;
7750b57cec5SDimitry Andric     }
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric     // If we haven't computed a numbering for the BB's in the function, do so
7780b57cec5SDimitry Andric     // now.
7790b57cec5SDimitry Andric     if (BBNumbers.empty()) {
7800b57cec5SDimitry Andric       unsigned ID = 0;
7810b57cec5SDimitry Andric       for (auto &BB : F)
7820b57cec5SDimitry Andric         BBNumbers[&BB] = ID++;
7830b57cec5SDimitry Andric     }
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric     // Remember the dbg.declare intrinsic describing this alloca, if any.
786e8d8bef9SDimitry Andric     if (!Info.DbgUsers.empty())
787e8d8bef9SDimitry Andric       AllocaDbgUsers[AllocaNum] = Info.DbgUsers;
788bdd1243dSDimitry Andric     if (!Info.AssignmentTracking.empty())
789bdd1243dSDimitry Andric       AllocaATInfo[AllocaNum] = Info.AssignmentTracking;
790c9157d92SDimitry Andric     if (!Info.DPUsers.empty())
791c9157d92SDimitry Andric       AllocaDPUsers[AllocaNum] = Info.DPUsers;
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
7940b57cec5SDimitry Andric     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric     // Unique the set of defining blocks for efficient lookup.
7970b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
7980b57cec5SDimitry Andric                                             Info.DefiningBlocks.end());
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric     // Determine which blocks the value is live in.  These are blocks which lead
8010b57cec5SDimitry Andric     // to uses.
8020b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
8030b57cec5SDimitry Andric     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric     // At this point, we're committed to promoting the alloca using IDF's, and
8060b57cec5SDimitry Andric     // the standard SSA construction algorithm.  Determine which blocks need phi
8070b57cec5SDimitry Andric     // nodes and see if we can optimize out some work by avoiding insertion of
8080b57cec5SDimitry Andric     // dead phi nodes.
8090b57cec5SDimitry Andric     IDF.setLiveInBlocks(LiveInBlocks);
8100b57cec5SDimitry Andric     IDF.setDefiningBlocks(DefBlocks);
8110b57cec5SDimitry Andric     SmallVector<BasicBlock *, 32> PHIBlocks;
8120b57cec5SDimitry Andric     IDF.calculate(PHIBlocks);
8130b57cec5SDimitry Andric     llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
8140b57cec5SDimitry Andric       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
8150b57cec5SDimitry Andric     });
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric     unsigned CurrentVersion = 0;
8180b57cec5SDimitry Andric     for (BasicBlock *BB : PHIBlocks)
8190b57cec5SDimitry Andric       QueuePhiNode(BB, AllocaNum, CurrentVersion);
8200b57cec5SDimitry Andric   }
8210b57cec5SDimitry Andric 
822fe013be4SDimitry Andric   if (Allocas.empty()) {
823fe013be4SDimitry Andric     cleanUpDbgAssigns();
8240b57cec5SDimitry Andric     return; // All of the allocas must have been trivial!
825fe013be4SDimitry Andric   }
8260b57cec5SDimitry Andric   LBI.clear();
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   // Set the incoming values for the basic block to be null values for all of
8290b57cec5SDimitry Andric   // the alloca's.  We do this in case there is a load of a value that has not
8300b57cec5SDimitry Andric   // been stored yet.  In this case, it will get this null value.
8310b57cec5SDimitry Andric   RenamePassData::ValVector Values(Allocas.size());
8320b57cec5SDimitry Andric   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
8330b57cec5SDimitry Andric     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric   // When handling debug info, treat all incoming values as if they have unknown
8360b57cec5SDimitry Andric   // locations until proven otherwise.
8370b57cec5SDimitry Andric   RenamePassData::LocationVector Locations(Allocas.size());
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   // Walks all basic blocks in the function performing the SSA rename algorithm
8400b57cec5SDimitry Andric   // and inserting the phi nodes we marked as necessary
8410b57cec5SDimitry Andric   std::vector<RenamePassData> RenamePassWorkList;
8420b57cec5SDimitry Andric   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
8430b57cec5SDimitry Andric                                   std::move(Locations));
8440b57cec5SDimitry Andric   do {
8450b57cec5SDimitry Andric     RenamePassData RPD = std::move(RenamePassWorkList.back());
8460b57cec5SDimitry Andric     RenamePassWorkList.pop_back();
8470b57cec5SDimitry Andric     // RenamePass may add new worklist entries.
8480b57cec5SDimitry Andric     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
8490b57cec5SDimitry Andric   } while (!RenamePassWorkList.empty());
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
8520b57cec5SDimitry Andric   Visited.clear();
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   // Remove the allocas themselves from the function.
8550b57cec5SDimitry Andric   for (Instruction *A : Allocas) {
856bdd1243dSDimitry Andric     // Remove dbg.assigns linked to the alloca as these are now redundant.
857bdd1243dSDimitry Andric     at::deleteAssignmentMarkers(A);
8580b57cec5SDimitry Andric     // If there are any uses of the alloca instructions left, they must be in
8590b57cec5SDimitry Andric     // unreachable basic blocks that were not processed by walking the dominator
8600b57cec5SDimitry Andric     // tree. Just delete the users now.
8610b57cec5SDimitry Andric     if (!A->use_empty())
862fe6060f1SDimitry Andric       A->replaceAllUsesWith(PoisonValue::get(A->getType()));
8630b57cec5SDimitry Andric     A->eraseFromParent();
8640b57cec5SDimitry Andric   }
8650b57cec5SDimitry Andric 
86681ad6265SDimitry Andric   // Remove alloca's dbg.declare intrinsics from the function.
867c9157d92SDimitry Andric   auto RemoveDbgDeclares = [&](auto &Container) {
868c9157d92SDimitry Andric     for (auto &DbgUsers : Container) {
869c9157d92SDimitry Andric       for (auto *DbgItem : DbgUsers)
870c9157d92SDimitry Andric         if (DbgItem->isAddressOfVariable() ||
871c9157d92SDimitry Andric             DbgItem->getExpression()->startsWithDeref())
872c9157d92SDimitry Andric           DbgItem->eraseFromParent();
873e8d8bef9SDimitry Andric     }
874c9157d92SDimitry Andric   };
875c9157d92SDimitry Andric   RemoveDbgDeclares(AllocaDbgUsers);
876c9157d92SDimitry Andric   RemoveDbgDeclares(AllocaDPUsers);
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   // Loop over all of the PHI nodes and see if there are any that we can get
8790b57cec5SDimitry Andric   // rid of because they merge all of the same incoming values.  This can
8800b57cec5SDimitry Andric   // happen due to undef values coming into the PHI nodes.  This process is
8810b57cec5SDimitry Andric   // iterative, because eliminating one PHI node can cause others to be removed.
8820b57cec5SDimitry Andric   bool EliminatedAPHI = true;
8830b57cec5SDimitry Andric   while (EliminatedAPHI) {
8840b57cec5SDimitry Andric     EliminatedAPHI = false;
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
8870b57cec5SDimitry Andric     // simplify and RAUW them as we go.  If it was not, we could add uses to
8880b57cec5SDimitry Andric     // the values we replace with in a non-deterministic order, thus creating
8890b57cec5SDimitry Andric     // non-deterministic def->use chains.
8900b57cec5SDimitry Andric     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
8910b57cec5SDimitry Andric              I = NewPhiNodes.begin(),
8920b57cec5SDimitry Andric              E = NewPhiNodes.end();
8930b57cec5SDimitry Andric          I != E;) {
8940b57cec5SDimitry Andric       PHINode *PN = I->second;
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric       // If this PHI node merges one value and/or undefs, get the value.
89781ad6265SDimitry Andric       if (Value *V = simplifyInstruction(PN, SQ)) {
8980b57cec5SDimitry Andric         PN->replaceAllUsesWith(V);
8990b57cec5SDimitry Andric         PN->eraseFromParent();
9000b57cec5SDimitry Andric         NewPhiNodes.erase(I++);
9010b57cec5SDimitry Andric         EliminatedAPHI = true;
9020b57cec5SDimitry Andric         continue;
9030b57cec5SDimitry Andric       }
9040b57cec5SDimitry Andric       ++I;
9050b57cec5SDimitry Andric     }
9060b57cec5SDimitry Andric   }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   // At this point, the renamer has added entries to PHI nodes for all reachable
9090b57cec5SDimitry Andric   // code.  Unfortunately, there may be unreachable blocks which the renamer
9100b57cec5SDimitry Andric   // hasn't traversed.  If this is the case, the PHI nodes may not
9110b57cec5SDimitry Andric   // have incoming values for all predecessors.  Loop over all PHI nodes we have
912fe013be4SDimitry Andric   // created, inserting poison values if they are missing any incoming values.
9130b57cec5SDimitry Andric   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
9140b57cec5SDimitry Andric            I = NewPhiNodes.begin(),
9150b57cec5SDimitry Andric            E = NewPhiNodes.end();
9160b57cec5SDimitry Andric        I != E; ++I) {
9170b57cec5SDimitry Andric     // We want to do this once per basic block.  As such, only process a block
9180b57cec5SDimitry Andric     // when we find the PHI that is the first entry in the block.
9190b57cec5SDimitry Andric     PHINode *SomePHI = I->second;
9200b57cec5SDimitry Andric     BasicBlock *BB = SomePHI->getParent();
9210b57cec5SDimitry Andric     if (&BB->front() != SomePHI)
9220b57cec5SDimitry Andric       continue;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric     // Only do work here if there the PHI nodes are missing incoming values.  We
9250b57cec5SDimitry Andric     // know that all PHI nodes that were inserted in a block will have the same
9260b57cec5SDimitry Andric     // number of incoming values, so we can just check any of them.
9270b57cec5SDimitry Andric     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
9280b57cec5SDimitry Andric       continue;
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric     // Get the preds for BB.
931e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric     // Ok, now we know that all of the PHI nodes are missing entries for some
9340b57cec5SDimitry Andric     // basic blocks.  Start by sorting the incoming predecessors for efficient
9350b57cec5SDimitry Andric     // access.
9360b57cec5SDimitry Andric     auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
9370b57cec5SDimitry Andric       return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
9380b57cec5SDimitry Andric     };
9390b57cec5SDimitry Andric     llvm::sort(Preds, CompareBBNumbers);
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric     // Now we loop through all BB's which have entries in SomePHI and remove
9420b57cec5SDimitry Andric     // them from the Preds list.
9430b57cec5SDimitry Andric     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
9440b57cec5SDimitry Andric       // Do a log(n) search of the Preds list for the entry we want.
9450b57cec5SDimitry Andric       SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
9460b57cec5SDimitry Andric           Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
9470b57cec5SDimitry Andric       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
9480b57cec5SDimitry Andric              "PHI node has entry for a block which is not a predecessor!");
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric       // Remove the entry
9510b57cec5SDimitry Andric       Preds.erase(EntIt);
9520b57cec5SDimitry Andric     }
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric     // At this point, the blocks left in the preds list must have dummy
9550b57cec5SDimitry Andric     // entries inserted into every PHI nodes for the block.  Update all the phi
9560b57cec5SDimitry Andric     // nodes in this block that we are inserting (there could be phis before
9570b57cec5SDimitry Andric     // mem2reg runs).
9580b57cec5SDimitry Andric     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
9590b57cec5SDimitry Andric     BasicBlock::iterator BBI = BB->begin();
9600b57cec5SDimitry Andric     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
9610b57cec5SDimitry Andric            SomePHI->getNumIncomingValues() == NumBadPreds) {
962fe013be4SDimitry Andric       Value *PoisonVal = PoisonValue::get(SomePHI->getType());
9630b57cec5SDimitry Andric       for (BasicBlock *Pred : Preds)
964fe013be4SDimitry Andric         SomePHI->addIncoming(PoisonVal, Pred);
9650b57cec5SDimitry Andric     }
9660b57cec5SDimitry Andric   }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   NewPhiNodes.clear();
969fe013be4SDimitry Andric   cleanUpDbgAssigns();
9700b57cec5SDimitry Andric }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric /// Determine which blocks the value is live in.
9730b57cec5SDimitry Andric ///
9740b57cec5SDimitry Andric /// These are blocks which lead to uses.  Knowing this allows us to avoid
9750b57cec5SDimitry Andric /// inserting PHI nodes into blocks which don't lead to uses (thus, the
9760b57cec5SDimitry Andric /// inserted phi nodes would be dead).
ComputeLiveInBlocks(AllocaInst * AI,AllocaInfo & Info,const SmallPtrSetImpl<BasicBlock * > & DefBlocks,SmallPtrSetImpl<BasicBlock * > & LiveInBlocks)9770b57cec5SDimitry Andric void PromoteMem2Reg::ComputeLiveInBlocks(
9780b57cec5SDimitry Andric     AllocaInst *AI, AllocaInfo &Info,
9790b57cec5SDimitry Andric     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
9800b57cec5SDimitry Andric     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
9810b57cec5SDimitry Andric   // To determine liveness, we must iterate through the predecessors of blocks
9820b57cec5SDimitry Andric   // where the def is live.  Blocks are added to the worklist if we need to
9830b57cec5SDimitry Andric   // check their predecessors.  Start with all the using blocks.
9840b57cec5SDimitry Andric   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
9850b57cec5SDimitry Andric                                                     Info.UsingBlocks.end());
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   // If any of the using blocks is also a definition block, check to see if the
9880b57cec5SDimitry Andric   // definition occurs before or after the use.  If it happens before the use,
9890b57cec5SDimitry Andric   // the value isn't really live-in.
9900b57cec5SDimitry Andric   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
9910b57cec5SDimitry Andric     BasicBlock *BB = LiveInBlockWorklist[i];
9920b57cec5SDimitry Andric     if (!DefBlocks.count(BB))
9930b57cec5SDimitry Andric       continue;
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric     // Okay, this is a block that both uses and defines the value.  If the first
9960b57cec5SDimitry Andric     // reference to the alloca is a def (store), then we know it isn't live-in.
9970b57cec5SDimitry Andric     for (BasicBlock::iterator I = BB->begin();; ++I) {
9980b57cec5SDimitry Andric       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
9990b57cec5SDimitry Andric         if (SI->getOperand(1) != AI)
10000b57cec5SDimitry Andric           continue;
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric         // We found a store to the alloca before a load.  The alloca is not
10030b57cec5SDimitry Andric         // actually live-in here.
10040b57cec5SDimitry Andric         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
10050b57cec5SDimitry Andric         LiveInBlockWorklist.pop_back();
10060b57cec5SDimitry Andric         --i;
10070b57cec5SDimitry Andric         --e;
10080b57cec5SDimitry Andric         break;
10090b57cec5SDimitry Andric       }
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric       if (LoadInst *LI = dyn_cast<LoadInst>(I))
10120b57cec5SDimitry Andric         // Okay, we found a load before a store to the alloca.  It is actually
10130b57cec5SDimitry Andric         // live into this block.
10140b57cec5SDimitry Andric         if (LI->getOperand(0) == AI)
10150b57cec5SDimitry Andric           break;
10160b57cec5SDimitry Andric     }
10170b57cec5SDimitry Andric   }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   // Now that we have a set of blocks where the phi is live-in, recursively add
10200b57cec5SDimitry Andric   // their predecessors until we find the full region the value is live.
10210b57cec5SDimitry Andric   while (!LiveInBlockWorklist.empty()) {
10220b57cec5SDimitry Andric     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric     // The block really is live in here, insert it into the set.  If already in
10250b57cec5SDimitry Andric     // the set, then it has already been processed.
10260b57cec5SDimitry Andric     if (!LiveInBlocks.insert(BB).second)
10270b57cec5SDimitry Andric       continue;
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric     // Since the value is live into BB, it is either defined in a predecessor or
10300b57cec5SDimitry Andric     // live into it to.  Add the preds to the worklist unless they are a
10310b57cec5SDimitry Andric     // defining block.
10320b57cec5SDimitry Andric     for (BasicBlock *P : predecessors(BB)) {
10330b57cec5SDimitry Andric       // The value is not live into a predecessor if it defines the value.
10340b57cec5SDimitry Andric       if (DefBlocks.count(P))
10350b57cec5SDimitry Andric         continue;
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric       // Otherwise it is, add to the worklist.
10380b57cec5SDimitry Andric       LiveInBlockWorklist.push_back(P);
10390b57cec5SDimitry Andric     }
10400b57cec5SDimitry Andric   }
10410b57cec5SDimitry Andric }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric /// Queue a phi-node to be added to a basic-block for a specific Alloca.
10440b57cec5SDimitry Andric ///
10450b57cec5SDimitry Andric /// Returns true if there wasn't already a phi-node for that variable
QueuePhiNode(BasicBlock * BB,unsigned AllocaNo,unsigned & Version)10460b57cec5SDimitry Andric bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
10470b57cec5SDimitry Andric                                   unsigned &Version) {
10480b57cec5SDimitry Andric   // Look up the basic-block in question.
10490b57cec5SDimitry Andric   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric   // If the BB already has a phi node added for the i'th alloca then we're done!
10520b57cec5SDimitry Andric   if (PN)
10530b57cec5SDimitry Andric     return false;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   // Create a PhiNode using the dereferenced type... and add the phi-node to the
10560b57cec5SDimitry Andric   // BasicBlock.
10570b57cec5SDimitry Andric   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
1058c9157d92SDimitry Andric                        Allocas[AllocaNo]->getName() + "." + Twine(Version++));
1059c9157d92SDimitry Andric   PN->insertBefore(BB->begin());
10600b57cec5SDimitry Andric   ++NumPHIInsert;
10610b57cec5SDimitry Andric   PhiToAllocaMap[PN] = AllocaNo;
10620b57cec5SDimitry Andric   return true;
10630b57cec5SDimitry Andric }
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
10660b57cec5SDimitry Andric /// create a merged location incorporating \p DL, or to set \p DL directly.
updateForIncomingValueLocation(PHINode * PN,DebugLoc DL,bool ApplyMergedLoc)10670b57cec5SDimitry Andric static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
10680b57cec5SDimitry Andric                                            bool ApplyMergedLoc) {
10690b57cec5SDimitry Andric   if (ApplyMergedLoc)
10700b57cec5SDimitry Andric     PN->applyMergedLocation(PN->getDebugLoc(), DL);
10710b57cec5SDimitry Andric   else
10720b57cec5SDimitry Andric     PN->setDebugLoc(DL);
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric /// Recursively traverse the CFG of the function, renaming loads and
10760b57cec5SDimitry Andric /// stores to the allocas which we are promoting.
10770b57cec5SDimitry Andric ///
10780b57cec5SDimitry Andric /// IncomingVals indicates what value each Alloca contains on exit from the
10790b57cec5SDimitry Andric /// predecessor block Pred.
RenamePass(BasicBlock * BB,BasicBlock * Pred,RenamePassData::ValVector & IncomingVals,RenamePassData::LocationVector & IncomingLocs,std::vector<RenamePassData> & Worklist)10800b57cec5SDimitry Andric void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
10810b57cec5SDimitry Andric                                 RenamePassData::ValVector &IncomingVals,
10820b57cec5SDimitry Andric                                 RenamePassData::LocationVector &IncomingLocs,
10830b57cec5SDimitry Andric                                 std::vector<RenamePassData> &Worklist) {
10840b57cec5SDimitry Andric NextIteration:
10850b57cec5SDimitry Andric   // If we are inserting any phi nodes into this BB, they will already be in the
10860b57cec5SDimitry Andric   // block.
10870b57cec5SDimitry Andric   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
10880b57cec5SDimitry Andric     // If we have PHI nodes to update, compute the number of edges from Pred to
10890b57cec5SDimitry Andric     // BB.
10900b57cec5SDimitry Andric     if (PhiToAllocaMap.count(APN)) {
10910b57cec5SDimitry Andric       // We want to be able to distinguish between PHI nodes being inserted by
10920b57cec5SDimitry Andric       // this invocation of mem2reg from those phi nodes that already existed in
10930b57cec5SDimitry Andric       // the IR before mem2reg was run.  We determine that APN is being inserted
10940b57cec5SDimitry Andric       // because it is missing incoming edges.  All other PHI nodes being
10950b57cec5SDimitry Andric       // inserted by this pass of mem2reg will have the same number of incoming
10960b57cec5SDimitry Andric       // operands so far.  Remember this count.
10970b57cec5SDimitry Andric       unsigned NewPHINumOperands = APN->getNumOperands();
10980b57cec5SDimitry Andric 
1099e8d8bef9SDimitry Andric       unsigned NumEdges = llvm::count(successors(Pred), BB);
11000b57cec5SDimitry Andric       assert(NumEdges && "Must be at least one edge from Pred to BB!");
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric       // Add entries for all the phis.
11030b57cec5SDimitry Andric       BasicBlock::iterator PNI = BB->begin();
11040b57cec5SDimitry Andric       do {
11050b57cec5SDimitry Andric         unsigned AllocaNo = PhiToAllocaMap[APN];
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric         // Update the location of the phi node.
11080b57cec5SDimitry Andric         updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
11090b57cec5SDimitry Andric                                        APN->getNumIncomingValues() > 0);
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric         // Add N incoming values to the PHI node.
11120b57cec5SDimitry Andric         for (unsigned i = 0; i != NumEdges; ++i)
11130b57cec5SDimitry Andric           APN->addIncoming(IncomingVals[AllocaNo], Pred);
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric         // The currently active variable for this block is now the PHI.
11160b57cec5SDimitry Andric         IncomingVals[AllocaNo] = APN;
1117bdd1243dSDimitry Andric         AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
1118c9157d92SDimitry Andric         auto ConvertDbgDeclares = [&](auto &Container) {
1119c9157d92SDimitry Andric           for (auto *DbgItem : Container)
1120c9157d92SDimitry Andric             if (DbgItem->isAddressOfVariable())
1121c9157d92SDimitry Andric               ConvertDebugDeclareToDebugValue(DbgItem, APN, DIB);
1122c9157d92SDimitry Andric         };
1123c9157d92SDimitry Andric         ConvertDbgDeclares(AllocaDbgUsers[AllocaNo]);
1124c9157d92SDimitry Andric         ConvertDbgDeclares(AllocaDPUsers[AllocaNo]);
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric         // Get the next phi node.
11270b57cec5SDimitry Andric         ++PNI;
11280b57cec5SDimitry Andric         APN = dyn_cast<PHINode>(PNI);
11290b57cec5SDimitry Andric         if (!APN)
11300b57cec5SDimitry Andric           break;
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric         // Verify that it is missing entries.  If not, it is not being inserted
11330b57cec5SDimitry Andric         // by this mem2reg invocation so we want to ignore it.
11340b57cec5SDimitry Andric       } while (APN->getNumOperands() == NewPHINumOperands);
11350b57cec5SDimitry Andric     }
11360b57cec5SDimitry Andric   }
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   // Don't revisit blocks.
11390b57cec5SDimitry Andric   if (!Visited.insert(BB).second)
11400b57cec5SDimitry Andric     return;
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric   for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
11430b57cec5SDimitry Andric     Instruction *I = &*II++; // get the instruction, increment iterator
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
11460b57cec5SDimitry Andric       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
11470b57cec5SDimitry Andric       if (!Src)
11480b57cec5SDimitry Andric         continue;
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
11510b57cec5SDimitry Andric       if (AI == AllocaLookup.end())
11520b57cec5SDimitry Andric         continue;
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric       Value *V = IncomingVals[AI->second];
1155bdd1243dSDimitry Andric       convertMetadataToAssumes(LI, V, SQ.DL, AC, &DT);
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric       // Anything using the load now uses the current value.
11580b57cec5SDimitry Andric       LI->replaceAllUsesWith(V);
1159bdd1243dSDimitry Andric       LI->eraseFromParent();
11600b57cec5SDimitry Andric     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
11610b57cec5SDimitry Andric       // Delete this instruction and mark the name as the current holder of the
11620b57cec5SDimitry Andric       // value
11630b57cec5SDimitry Andric       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
11640b57cec5SDimitry Andric       if (!Dest)
11650b57cec5SDimitry Andric         continue;
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
11680b57cec5SDimitry Andric       if (ai == AllocaLookup.end())
11690b57cec5SDimitry Andric         continue;
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric       // what value were we writing?
11720b57cec5SDimitry Andric       unsigned AllocaNo = ai->second;
11730b57cec5SDimitry Andric       IncomingVals[AllocaNo] = SI->getOperand(0);
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric       // Record debuginfo for the store before removing it.
11760b57cec5SDimitry Andric       IncomingLocs[AllocaNo] = SI->getDebugLoc();
1177*a58f00eaSDimitry Andric       AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB, &DbgAssignsToDelete,
1178*a58f00eaSDimitry Andric                                                    &DPVAssignsToDelete);
1179c9157d92SDimitry Andric       auto ConvertDbgDeclares = [&](auto &Container) {
1180c9157d92SDimitry Andric         for (auto *DbgItem : Container)
1181c9157d92SDimitry Andric           if (DbgItem->isAddressOfVariable())
1182c9157d92SDimitry Andric             ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
1183c9157d92SDimitry Andric       };
1184c9157d92SDimitry Andric       ConvertDbgDeclares(AllocaDbgUsers[ai->second]);
1185c9157d92SDimitry Andric       ConvertDbgDeclares(AllocaDPUsers[ai->second]);
1186bdd1243dSDimitry Andric       SI->eraseFromParent();
11870b57cec5SDimitry Andric     }
11880b57cec5SDimitry Andric   }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric   // 'Recurse' to our successors.
11910b57cec5SDimitry Andric   succ_iterator I = succ_begin(BB), E = succ_end(BB);
11920b57cec5SDimitry Andric   if (I == E)
11930b57cec5SDimitry Andric     return;
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric   // Keep track of the successors so we don't visit the same successor twice
11960b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   // Handle the first successor without using the worklist.
11990b57cec5SDimitry Andric   VisitedSuccs.insert(*I);
12000b57cec5SDimitry Andric   Pred = BB;
12010b57cec5SDimitry Andric   BB = *I;
12020b57cec5SDimitry Andric   ++I;
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   for (; I != E; ++I)
12050b57cec5SDimitry Andric     if (VisitedSuccs.insert(*I).second)
12060b57cec5SDimitry Andric       Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   goto NextIteration;
12090b57cec5SDimitry Andric }
12100b57cec5SDimitry Andric 
PromoteMemToReg(ArrayRef<AllocaInst * > Allocas,DominatorTree & DT,AssumptionCache * AC)12110b57cec5SDimitry Andric void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
12120b57cec5SDimitry Andric                            AssumptionCache *AC) {
12130b57cec5SDimitry Andric   // If there is nothing to do, bail out...
12140b57cec5SDimitry Andric   if (Allocas.empty())
12150b57cec5SDimitry Andric     return;
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   PromoteMem2Reg(Allocas, DT, AC).run();
12180b57cec5SDimitry Andric }
1219