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