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