LLVM 24.0.0git
PromoteMemoryToRegister.cpp
Go to the documentation of this file.
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"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/Twine.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"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.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"
51#include <algorithm>
52#include <cassert>
53#include <iterator>
54#include <utility>
55#include <vector>
56
57using namespace llvm;
58
59#define DEBUG_TYPE "mem2reg"
60
61STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
62STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
63STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
64STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
65
67 // Only allow direct and non-volatile loads and stores...
68 // All loads and stores must use the same type (determined by the first one
69 // seen). We don't require the type to match the alloca's declared type.
70 Type *ExpectedType = nullptr;
71 for (const User *U : AI->users()) {
72 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
73 // Note that atomic loads can be transformed; atomic semantics do
74 // not have any meaning for a local alloca.
75 if (LI->isVolatile())
76 return false;
77 if (!ExpectedType)
78 ExpectedType = LI->getType();
79 else if (LI->getType() != ExpectedType)
80 return false;
81 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
82 if (SI->getValueOperand() == AI)
83 return false; // Don't allow a store OF the AI, only INTO the AI.
84 // Note that atomic stores can be transformed; atomic semantics do
85 // not have any meaning for a local alloca.
86 if (SI->isVolatile())
87 return false;
88 Type *StoreType = SI->getValueOperand()->getType();
89 if (!ExpectedType)
90 ExpectedType = StoreType;
91 else if (StoreType != ExpectedType)
92 return false;
93 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
94 if (!II->isLifetimeStartOrEnd() && !II->isDroppable() &&
95 II->getIntrinsicID() != Intrinsic::fake_use)
96 return false;
97 } else {
98 return false;
99 }
100 }
101
102 return true;
103}
104
105namespace {
106
107static void createDebugValue(DIBuilder &DIB, Value *NewValue,
108 DILocalVariable *Variable,
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;
116 *InsertBefore);
117}
118
119/// Helper for updating assignment tracking debug info when promoting allocas.
120class AssignmentTrackingInfo {
121 /// DbgAssignIntrinsics linked to the alloca with at most one per variable
122 /// fragment. (i.e. not be a comprehensive set if there are multiple
123 /// dbg.assigns for one variable fragment).
125
126public:
127 void init(AllocaInst *AI) {
128 SmallSet<DebugVariable, 2> Vars;
129 for (DbgVariableRecord *DVR : at::getDVRAssignmentMarkers(AI)) {
130 if (Vars.insert(DebugVariable(DVR)).second)
131 DVRAssigns.push_back(DVR);
132 }
133 }
134
135 /// Update assignment tracking debug info given for the to-be-deleted store
136 /// \p ToDelete that stores to this alloca.
137 void updateForDeletedStore(
138 StoreInst *ToDelete, DIBuilder &DIB,
139 SmallPtrSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) const {
140 // There's nothing to do if the alloca doesn't have any variables using
141 // assignment tracking.
142 if (DVRAssigns.empty())
143 return;
144
145 // Insert a dbg.value where the linked dbg.assign is and remember to delete
146 // the dbg.assign later. Demoting to dbg.value isn't necessary for
147 // correctness but does reduce compile time and memory usage by reducing
148 // unnecessary function-local metadata. Remember that we've seen a
149 // dbg.assign for each variable fragment for the untracked store handling
150 // (after this loop).
151 SmallSet<DebugVariableAggregate, 2> VarHasDbgAssignForStore;
152 auto InsertValueForAssign = [&](auto *DbgAssign, auto *&AssignList) {
153 VarHasDbgAssignForStore.insert(DebugVariableAggregate(DbgAssign));
154 AssignList->insert(DbgAssign);
155 createDebugValue(DIB, DbgAssign->getValue(), DbgAssign->getVariable(),
156 DbgAssign->getExpression(), DbgAssign->getDebugLoc(),
157 DbgAssign);
158 };
159 for (auto *Assign : at::getDVRAssignmentMarkers(ToDelete))
160 InsertValueForAssign(Assign, DVRAssignsToDelete);
161
162 // It's possible for variables using assignment tracking to have no
163 // dbg.assign linked to this store. These are variables in DVRAssigns that
164 // are missing from VarHasDbgAssignForStore. Since there isn't a dbg.assign
165 // to mark the assignment - and the store is going to be deleted - insert a
166 // dbg.value to do that now. An untracked store may be either one that
167 // cannot be represented using assignment tracking (non-const offset or
168 // size) or one that is trackable but has had its DIAssignID attachment
169 // dropped accidentally.
170 auto ConvertUnlinkedAssignToValue = [&](DbgVariableRecord *Assign) {
171 if (VarHasDbgAssignForStore.contains(DebugVariableAggregate(Assign)))
172 return;
173 ConvertDebugDeclareToDebugValue(Assign, ToDelete, DIB);
174 };
175 for_each(DVRAssigns, ConvertUnlinkedAssignToValue);
176 }
177
178 /// Update assignment tracking debug info given for the newly inserted PHI \p
179 /// NewPhi.
180 void updateForNewPhi(PHINode *NewPhi, DIBuilder &DIB) const {
181 // Regardless of the position of dbg.assigns relative to stores, the
182 // incoming values into a new PHI should be the same for the (imaginary)
183 // debug-phi.
184 for (auto *DVR : DVRAssigns)
185 ConvertDebugDeclareToDebugValue(DVR, NewPhi, DIB);
186 }
187
188 void clear() { DVRAssigns.clear(); }
189 bool empty() { return DVRAssigns.empty(); }
190};
191
192struct AllocaInfo {
193 using DPUserVec = SmallVector<DbgVariableRecord *, 1>;
194
195 SmallVector<BasicBlock *, 32> DefiningBlocks;
197
198 StoreInst *OnlyStore;
199 BasicBlock *OnlyBlock;
200 bool OnlyUsedInOneBlock;
201
202 /// The type used by all loads/stores of this alloca. This may differ from
203 /// the alloca's declared type if all accesses use a different type.
204 Type *ValueType;
205
206 /// Debug users of the alloca - does not include dbg.assign intrinsics.
207 DPUserVec DPUsers;
208 /// Helper to update assignment tracking debug info.
209 AssignmentTrackingInfo AssignmentTracking;
210
211 void clear() {
212 DefiningBlocks.clear();
213 UsingBlocks.clear();
214 OnlyStore = nullptr;
215 OnlyBlock = nullptr;
216 OnlyUsedInOneBlock = true;
217 ValueType = nullptr;
218 DPUsers.clear();
219 AssignmentTracking.clear();
220 }
221
222 /// Scan the uses of the specified alloca, filling in the AllocaInfo used
223 /// by the rest of the pass to reason about the uses of this alloca.
224 void AnalyzeAlloca(AllocaInst *AI) {
225 clear();
226
227 // As we scan the uses of the alloca instruction, keep track of stores,
228 // and decide whether all of the loads and stores to the alloca are within
229 // the same basic block.
230 for (Instruction *User : AI->users()) {
231 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
232 // Remember the basic blocks which define new values for the alloca
233 DefiningBlocks.push_back(SI->getParent());
234 OnlyStore = SI;
235 if (!ValueType)
236 ValueType = SI->getValueOperand()->getType();
237 else
238 assert(ValueType == SI->getValueOperand()->getType() &&
239 "All stores were checked to have used the same type");
240 } else {
241 LoadInst *LI = cast<LoadInst>(User);
242 // Otherwise it must be a load instruction, keep track of variable
243 // reads.
244 UsingBlocks.push_back(LI->getParent());
245 if (!ValueType)
246 ValueType = LI->getType();
247 else
248 assert(ValueType == LI->getType() &&
249 "All loads where checked to have used the same type");
250 }
251
252 if (OnlyUsedInOneBlock) {
253 if (!OnlyBlock)
254 OnlyBlock = User->getParent();
255 else if (OnlyBlock != User->getParent())
256 OnlyUsedInOneBlock = false;
257 }
258 }
260 findDbgUsers(AI, AllDPUsers);
261 std::copy_if(AllDPUsers.begin(), AllDPUsers.end(),
262 std::back_inserter(DPUsers),
263 [](DbgVariableRecord *DVR) { return !DVR->isDbgAssign(); });
264 AssignmentTracking.init(AI);
265 }
266};
267
268using DVRIndirectValuesAtStoreMap =
270using DVRIndirectValueLastStoreMap = DenseMap<DbgVariableRecord *, StoreInst *>;
271
272template <typename T> class VectorWithUndo {
275
276public:
277 void undo(size_t S) {
278 assert(S <= Undo.size());
279 while (S < Undo.size()) {
280 Vals[Undo.back().first] = Undo.back().second;
281 Undo.pop_back();
282 }
283 }
284
285 void resize(size_t Sz) { Vals.resize(Sz); }
286
287 size_t undoSize() const { return Undo.size(); }
288
289 const T &operator[](size_t Idx) const { return Vals[Idx]; }
290
291 void set(size_t Idx, const T &Val) {
292 if (Vals[Idx] == Val)
293 return;
294 Undo.emplace_back(Idx, Vals[Idx]);
295 Vals[Idx] = Val;
296 }
297
298 void init(size_t Idx, const T &Val) {
299 assert(Undo.empty());
300 Vals[Idx] = Val;
301 }
302};
303
304/// Data package used by RenamePass().
305struct RenamePassData {
306 RenamePassData(BasicBlock *B, BasicBlock *P, size_t V, size_t L)
307 : BB(B), Pred(P), UndoVals(V), UndoLocs(L) {}
308
309 BasicBlock *BB;
311
312 size_t UndoVals;
313 size_t UndoLocs;
314};
315
316/// This assigns and keeps a per-bb relative ordering of load/store
317/// instructions in the block that directly load or store an alloca.
318///
319/// This functionality is important because it avoids scanning large basic
320/// blocks multiple times when promoting many allocas in the same block.
321class LargeBlockInfo {
322 /// For each instruction that we track, keep the index of the
323 /// instruction.
324 ///
325 /// The index starts out as the number of the instruction from the start of
326 /// the block.
327 DenseMap<const Instruction *, unsigned> InstNumbers;
328
329public:
330
331 /// This code only looks at accesses to allocas.
332 static bool isInterestingInstruction(const Instruction *I) {
333 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
334 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
335 }
336
337 /// Get or calculate the index of the specified instruction.
338 unsigned getInstructionIndex(const Instruction *I) {
339 assert(isInterestingInstruction(I) &&
340 "Not a load/store to/from an alloca?");
341
342 // If we already have this instruction number, return it.
343 auto It = InstNumbers.find(I);
344 if (It != InstNumbers.end())
345 return It->second;
346
347 // Scan the whole block to get the instruction. This accumulates
348 // information for every interesting instruction in the block, in order to
349 // avoid gratuitus rescans.
350 const BasicBlock *BB = I->getParent();
351 unsigned InstNo = 0;
352 for (const Instruction &BBI : *BB)
353 if (isInterestingInstruction(&BBI))
354 InstNumbers[&BBI] = InstNo++;
355 It = InstNumbers.find(I);
356
357 assert(It != InstNumbers.end() && "Didn't insert instruction?");
358 return It->second;
359 }
360
361 void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
362
363 void clear() { InstNumbers.clear(); }
364};
365
366struct PromoteMem2Reg {
367 /// The alloca instructions being promoted.
368 std::vector<AllocaInst *> Allocas;
369
370 DominatorTree &DT;
371 DIBuilder DIB;
372
373 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
374 AssumptionCache *AC;
375
376 const SimplifyQuery SQ;
377
378 /// Reverse mapping of Allocas.
379 DenseMap<AllocaInst *, unsigned> AllocaLookup;
380
381 /// The PhiNodes we're adding.
382 ///
383 /// That map is used to simplify some Phi nodes as we iterate over it, so
384 /// it should have deterministic iterators. We could use a MapVector, but
385 /// since basic blocks have numbers, using these are more efficient.
386 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
387
388 /// For each PHI node, keep track of which entry in Allocas it corresponds
389 /// to.
390 DenseMap<PHINode *, unsigned> PhiToAllocaMap;
391
392 /// For each alloca, we keep track of the dbg.declare record that
393 /// describes it, if any, so that we can convert it to a dbg.value
394 /// record if the alloca gets promoted.
396
397 /// For each alloca, keep an instance of a helper class that gives us an easy
398 /// way to update assignment tracking debug info if the alloca is promoted.
400 /// For each alloca, the type used by all loads/stores of this alloca.
401 SmallVector<Type *, 8> AllocaValueTypes;
402 /// A set of dbg.assigns to delete because they've been demoted to
403 /// dbg.values. Call cleanUpDbgAssigns to delete them.
404 SmallPtrSet<DbgVariableRecord *, 8> DVRAssignsToDelete;
405
406 /// For each store to an alloca, the #dbg_values with a deref alive there.
407 DVRIndirectValuesAtStoreMap DVRIndirectValuesAtStore;
408 /// For each #dbg_value with a deref, the last store to its alloca before it,
409 /// in its block.
410 DVRIndirectValueLastStoreMap DVRIndirectValueLastStore;
411
412 /// The set of basic blocks the renamer has already visited.
413 BitVector Visited;
414
415 /// Lazily compute the number of predecessors a block has, indexed by block
416 /// number.
417 SmallVector<unsigned> BBNumPreds;
418
419 /// The state of incoming values for the current DFS step.
420 VectorWithUndo<Value *> IncomingVals;
421
422 /// The state of incoming locations for the current DFS step.
423 VectorWithUndo<DebugLoc> IncomingLocs;
424
425 // DFS work stack.
427
428 /// Whether the function has the no-signed-zeros-fp-math attribute set.
429 bool NoSignedZeros = false;
430
431public:
432 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
433 AssumptionCache *AC)
434 : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
435 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
436 AC(AC), SQ(DT.getRoot()->getDataLayout(),
437 nullptr, &DT, AC) {}
438
439 void run();
440
441private:
442 void RemoveFromAllocasList(unsigned &AllocaIdx) {
443 Allocas[AllocaIdx] = Allocas.back();
444 Allocas.pop_back();
445 --AllocaIdx;
446 }
447
448 unsigned getNumPreds(const BasicBlock *BB) {
449 // BBNumPreds is resized to getMaxBlockNumber() at the beginning.
450 unsigned &NP = BBNumPreds[BB->getNumber()];
451 if (NP == 0)
452 NP = pred_size(BB) + 1;
453 return NP - 1;
454 }
455
456 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
457 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
458 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
459 void collectDVRIndirectValuesAtStores();
460 void RenamePass(BasicBlock *BB, BasicBlock *Pred);
461 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
462
463 /// Delete dbg.assigns that have been demoted to dbg.values.
464 void cleanUpDbgAssigns() {
465 for (auto *DVR : DVRAssignsToDelete)
466 DVR->eraseFromParent();
467 DVRAssignsToDelete.clear();
468 }
469
470 void pushToWorklist(BasicBlock *BB, BasicBlock *Pred) {
471 Worklist.emplace_back(BB, Pred, IncomingVals.undoSize(),
472 IncomingLocs.undoSize());
473 }
474
475 RenamePassData popFromWorklist() {
476 RenamePassData R = Worklist.back();
477 Worklist.pop_back();
478 IncomingVals.undo(R.UndoVals);
479 IncomingLocs.undo(R.UndoLocs);
480 return R;
481 }
482};
483
484} // end anonymous namespace
485
486/// Given a LoadInst LI this adds assume(LI != null) after it.
488 Function *AssumeIntrinsic =
489 Intrinsic::getOrInsertDeclaration(LI->getModule(), Intrinsic::assume);
490 ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
492 LoadNotNull->insertAfter(LI->getIterator());
493 CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
494 CI->insertAfter(LoadNotNull->getIterator());
496}
497
499 const DataLayout &DL, AssumptionCache *AC,
500 const DominatorTree *DT) {
501 if (isa<UndefValue>(Val) && LI->hasMetadata(LLVMContext::MD_noundef)) {
502 // Insert non-terminator unreachable.
503 LLVMContext &Ctx = LI->getContext();
506 /*isVolatile=*/false, Align(1), LI->getIterator());
507 return;
508 }
509
510 // If the load was marked as nonnull we don't want to lose that information
511 // when we erase this Load. So we preserve it with an assume. As !nonnull
512 // returns poison while assume violations are immediate undefined behavior,
513 // we can only do this if the value is known non-poison.
514 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
515 LI->getMetadata(LLVMContext::MD_noundef) &&
516 !isKnownNonZero(Val, SimplifyQuery(DL, DT, AC, LI)))
517 addAssumeNonNull(AC, LI);
518}
519
521 // Knowing that this alloca is promotable, we know that it's safe to kill all
522 // instructions except for load and store.
523
524 // Determine the type used by loads/stores on this alloca. Per
525 // isAllocaPromotable, all loads/stores must use the same type, and GEP/
526 // bitcast/addrspacecast derived pointers cannot have load/store users, so
527 // loads/stores are always direct users of the alloca.
528 Type *PromotedType = nullptr;
529 for (User *U : AI->users()) {
530 if (auto *LI = dyn_cast<LoadInst>(U)) {
531 PromotedType = LI->getType();
532 break;
533 }
534 if (auto *SI = dyn_cast<StoreInst>(U)) {
535 PromotedType = SI->getValueOperand()->getType();
536 break;
537 }
538 }
539
540 for (Use &U : llvm::make_early_inc_range(AI->uses())) {
541 Instruction *I = cast<Instruction>(U.getUser());
543 continue;
544
545 // Drop the use of AI in droppable instructions.
546 if (I->isDroppable()) {
547 I->dropDroppableUse(U);
548 continue;
549 }
550
551 // If the alloca has no load/store users, PromotedType is null and the
552 // alloca will be deleted as dead, so no store is needed.
553 if (PromotedType)
554 if (auto *II = dyn_cast<IntrinsicInst>(I))
555 if (II->isLifetimeStartOrEnd()) {
556 auto *Store = new StoreInst(UndefValue::get(PromotedType), AI,
557 /*isVolatile=*/false, AI->getAlign(),
558 I->getIterator());
559 Store->setDebugLoc(II->getDebugLoc());
560 }
561
562 I->eraseFromParent();
563 }
564}
565
566/// Rewrite as many loads as possible given a single store.
567///
568/// When there is only a single store, we can use the domtree to trivially
569/// replace all of the dominated loads with the stored value. Do so, and return
570/// true if this has successfully promoted the alloca entirely. If this returns
571/// false there were some loads which were not dominated by the single store
572/// and thus must be phi-ed with undef. We fall back to the standard alloca
573/// promotion algorithm in that case.
575 AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI, const DataLayout &DL,
577 SmallPtrSet<DbgVariableRecord *, 8> *DVRAssignsToDelete) {
578 StoreInst *OnlyStore = Info.OnlyStore;
579 Value *ReplVal = OnlyStore->getOperand(0);
580 // Loads may either load the stored value or uninitialized memory (undef).
581 // If the stored value may be poison, then replacing an uninitialized memory
582 // load with it would be incorrect. If the store dominates the load, we know
583 // it is always initialized.
584 bool RequireDominatingStore =
585 isa<Instruction>(ReplVal) || !isGuaranteedNotToBePoison(ReplVal);
586 BasicBlock *StoreBB = OnlyStore->getParent();
587 int StoreIndex = -1;
588
589 // Clear out UsingBlocks. We will reconstruct it here if needed.
590 Info.UsingBlocks.clear();
591
592 for (Instruction *UserInst : make_early_inc_range(AI->users())) {
593 if (UserInst == OnlyStore)
594 continue;
595 LoadInst *LI = cast<LoadInst>(UserInst);
596
597 // Okay, if we have a load from the alloca, we want to replace it with the
598 // only value stored to the alloca. We can do this if the value is
599 // dominated by the store. If not, we use the rest of the mem2reg machinery
600 // to insert the phi nodes as needed.
601 if (RequireDominatingStore) {
602 if (LI->getParent() == StoreBB) {
603 // If we have a use that is in the same block as the store, compare the
604 // indices of the two instructions to see which one came first. If the
605 // load came before the store, we can't handle it.
606 if (StoreIndex == -1)
607 StoreIndex = LBI.getInstructionIndex(OnlyStore);
608
609 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
610 // Can't handle this load, bail out.
611 Info.UsingBlocks.push_back(StoreBB);
612 continue;
613 }
614 } else if (!DT.dominates(StoreBB, LI->getParent())) {
615 // If the load and store are in different blocks, use BB dominance to
616 // check their relationships. If the store doesn't dom the use, bail
617 // out.
618 Info.UsingBlocks.push_back(LI->getParent());
619 continue;
620 }
621 }
622
623 // Otherwise, we *can* safely rewrite this load.
624 // If the replacement value is the load, this must occur in unreachable
625 // code.
626 if (ReplVal == LI)
627 ReplVal = PoisonValue::get(LI->getType());
628
629 convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
630 LI->replaceAllUsesWith(ReplVal);
631 LI->eraseFromParent();
632 LBI.deleteValue(LI);
633 }
634
635 // Finally, after the scan, check to see if the store is all that is left.
636 if (!Info.UsingBlocks.empty())
637 return false; // If not, we'll have to fall back for the remainder.
638
639 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
640 // Update assignment tracking info for the store we're going to delete.
641 Info.AssignmentTracking.updateForDeletedStore(Info.OnlyStore, DIB,
642 DVRAssignsToDelete);
643
644 // Record debuginfo for the store and remove the declaration's
645 // debuginfo.
646 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
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 // Remove dbg.assigns linked to the alloca as these are now redundant.
661
662 // Remove the (now dead) store and alloca.
663 Info.OnlyStore->eraseFromParent();
664 LBI.deleteValue(Info.OnlyStore);
665
666 AI->eraseFromParent();
667 return true;
668}
669
670/// Many allocas are only used within a single basic block. If this is the
671/// case, avoid traversing the CFG and inserting a lot of potentially useless
672/// PHI nodes by just performing a single linear pass over the basic block
673/// using the Alloca.
674///
675/// If we cannot promote this alloca (because it is read before it is written),
676/// return false. This is necessary in cases where, due to control flow, the
677/// alloca is undefined only on some control flow paths. e.g. code like
678/// this is correct in LLVM IR:
679/// // A is an alloca with no stores so far
680/// for (...) {
681/// int t = *A;
682/// if (!first_iteration)
683/// use(t);
684/// *A = 42;
685/// }
687 AllocaInst *AI, const AllocaInfo &Info, LargeBlockInfo &LBI,
689 SmallPtrSet<DbgVariableRecord *, 8> *DVRAssignsToDelete,
690 const DVRIndirectValuesAtStoreMap &DVRIndirectValuesAtStore,
691 const DVRIndirectValueLastStoreMap &DVRIndirectValueLastStore) {
692 // The trickiest case to handle is when we have large blocks. Because of this,
693 // this code is optimized assuming that large blocks happen. This does not
694 // significantly pessimize the small block case. This uses LargeBlockInfo to
695 // make it efficient to get the index of various operations in the block.
696
697 // Walk the use-def list of the alloca, getting the locations of all stores.
698 using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
699 StoresByIndexTy StoresByIndex;
700
701 for (User *U : AI->users())
703 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
704
705 // Sort the stores by their index, making it efficient to do a lookup with a
706 // binary search.
707 llvm::sort(StoresByIndex, less_first());
708
709 // Walk all of the loads from this alloca, replacing them with the nearest
710 // store above them, if any.
711 for (User *U : make_early_inc_range(AI->users())) {
713 if (!LI)
714 continue;
715
716 unsigned LoadIdx = LBI.getInstructionIndex(LI);
717
718 // Find the nearest store that has a lower index than this load.
719 StoresByIndexTy::iterator I = llvm::lower_bound(
720 StoresByIndex,
721 std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
722 less_first());
723 Value *ReplVal;
724 if (I == StoresByIndex.begin()) {
725 if (StoresByIndex.empty())
726 // If there are no stores, the load takes the undef value.
727 ReplVal = UndefValue::get(LI->getType());
728 else
729 // There is no store before this load, bail out (load may be affected
730 // by the following stores - see main comment).
731 return false;
732 } else {
733 // Otherwise, there was a store before this load, the load takes its
734 // value.
735 ReplVal = std::prev(I)->second->getOperand(0);
736 }
737
738 convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
739
740 // If the replacement value is the load, this must occur in unreachable
741 // code.
742 if (ReplVal == LI)
743 ReplVal = PoisonValue::get(LI->getType());
744
745 LI->replaceAllUsesWith(ReplVal);
746 LI->eraseFromParent();
747 LBI.deleteValue(LI);
748 }
749
750 // Each #dbg_value with a deref takes the value of the last store to the
751 // alloca, with its deref stripped.
753 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
754 if (!DbgItem->isDbgValue() || !DbgItem->getExpression()->startsWithDeref())
755 continue;
756
757 StoreInst *SI = DVRIndirectValueLastStore.lookup(DbgItem);
758 // If there is no store to the alloca yet, or if the content is undef, the
759 // variable should keep its previous location.
760 Value *LastStoreValue = nullptr;
761 if (SI && (!isa<UndefValue>(SI->getValueOperand()) ||
762 isa<PoisonValue>(SI->getValueOperand()))) {
763 LastStoreValue = SI->getValueOperand();
764 }
765
766 // If the next instruction is a store, mark the record for removal to avoid
767 // a duplicate record, as the store will also create a record.
768 auto *Next = dyn_cast<StoreInst>(DbgItem->getInstruction());
769 if (Next && Next->getPointerOperand() == AI) {
770 LastStoreValue = nullptr;
771 }
772 DVRIndirectValues.push_back({DbgItem, LastStoreValue});
773 }
774
775 // Remove the (now dead) stores and alloca.
776 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
777 while (!AI->use_empty()) {
779 // Update assignment tracking info for the store we're going to delete.
780 Info.AssignmentTracking.updateForDeletedStore(SI, DIB, DVRAssignsToDelete);
781 // Record debuginfo for the store before removing it.
782 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
783 if (DbgItem->isAddressOfVariable()) {
784 ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
785 } else if (DbgItem->isDbgDeclareValue() &&
786 DbgItem->getExpression()->startsWithDeref()) {
787 // A #dbg_declare_value is converted to a #dbg_value at each store,
788 // with its deref stripped.
789 InsertDebugValueAtStoreLoc(DbgItem, SI, DIB);
790 }
791 }
792 // Each live #dbg_value is cloned at each store with its deref stripped.
793 for (DbgVariableRecord *DbgItem : DVRIndirectValuesAtStore.lookup(SI))
794 InsertDebugValueAtStoreLoc(DbgItem, SI, DIB);
795
796 SI->eraseFromParent();
797 LBI.deleteValue(SI);
798 }
799
800 // Remove dbg.assigns linked to the alloca as these are now redundant.
802 AI->eraseFromParent();
803
804 // The alloca's #dbg_declare records have been rewritten and can be deleted.
805 for (DbgVariableRecord *DbgItem : Info.DPUsers) {
806 if (DbgItem->isAddressOfVariable() ||
807 (DbgItem->isDbgDeclareValue() &&
808 DbgItem->getExpression()->startsWithDeref()))
809 DbgItem->eraseFromParent();
810 }
811 // Indirect #dbg_value records are rewritten to use the last store to the
812 // alloca, or removed if there is none.
813 for (auto [DbgItem, V] : DVRIndirectValues) {
814 if (!V) {
815 DbgItem->eraseFromParent();
816 continue;
817 }
820 V->getContext(), DbgItem->getExpression()
822 ->drop_front()));
823 }
824
825 ++NumLocalPromoted;
826 return true;
827}
828
829/// Collect which records are valid at each store, and which store reaches each
830/// record, walking each block once for all allocas.
831void PromoteMem2Reg::collectDVRIndirectValuesAtStores() {
832 // A #dbg_value with a deref can be cloned and rewritten at each store.
833 // Any other kind is left to be poisoned.
834 SmallPtrSet<DbgVariableRecord *, 8> DVRIndirectValues;
835 SmallSetVector<BasicBlock *, 4> BlocksToProcess;
836 for (AllocaInst *AI : Allocas)
837 for (DbgVariableRecord *DVR : findDVRValues(AI))
838 if (DVR->isDbgValue() && DVR->getExpression()->startsWithDeref()) {
839 DVRIndirectValues.insert(DVR);
840 BlocksToProcess.insert(DVR->getParent());
841 }
842
843 // Only promoteSingleBlockAlloca is supported, so each block is processed
844 // individually.
845 for (BasicBlock *BB : BlocksToProcess) {
846 // The records alive at this point, for each variable. There can be
847 // multiple if there are fragments.
848 SmallDenseMap<DebugVariableAggregate, SmallVector<DbgVariableRecord *, 1>>
849 LiveByVar;
850 // The records alive at this point, whose value use the alloca.
851 SmallDenseMap<Value *, SmallVector<DbgVariableRecord *, 1>> LiveByAlloca;
852 // The last store to each alloca before this point.
853 SmallDenseMap<Value *, StoreInst *> LastStore;
854 for (Instruction &I : *BB) {
855 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
856 // Only #dbg_values have a meaningful location.
857 if (!DVR.isDbgValue())
858 continue;
859 // Any overlapping previous record is no longer live.
860 auto &Live = LiveByVar[DebugVariableAggregate(&DVR)];
861 erase_if(Live, [&](DbgVariableRecord *L) {
862 if (!L->getExpression()->fragmentsOverlap(DVR.getExpression()))
863 return false;
864 erase(LiveByAlloca[L->getVariableLocationOp(0)], L);
865 return true;
866 });
867 // If this is one of our indirect records, mark it live.
868 if (DVRIndirectValues.contains(&DVR)) {
869 Live.push_back(&DVR);
870 Value *Ptr = DVR.getVariableLocationOp(0);
871 LiveByAlloca[Ptr].push_back(&DVR);
872 if (StoreInst *SI = LastStore.lookup(Ptr))
873 DVRIndirectValueLastStore[&DVR] = SI;
874 }
875 }
876 // Save the records alive at this point.
877 auto *SI = dyn_cast<StoreInst>(&I);
878 if (!SI)
879 continue;
880 LastStore[SI->getPointerOperand()] = SI;
881 // Copy the list of live records into the map, if it was tracked.
882 auto Live = LiveByAlloca.lookup(SI->getPointerOperand());
883 if (!Live.empty())
884 DVRIndirectValuesAtStore[SI] = std::move(Live);
885 }
886 }
887}
888
889void PromoteMem2Reg::run() {
890 Function &F = *DT.getRoot()->getParent();
891
892 AllocaATInfo.resize(Allocas.size());
893 AllocaDPUsers.resize(Allocas.size());
894 AllocaValueTypes.resize(Allocas.size());
895
896 AllocaInfo Info;
897 LargeBlockInfo LBI;
898 ForwardIDFCalculator IDF(DT);
899
900 NoSignedZeros = F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool();
901
902 // removeIntrinsicUsers inserts StoreInst(undef). A cache miss on
903 // LBI.getInstructionIndex lookup causes a full O(|BB|) basic block rescan.
904 // Doing all inserts in advance lets us capture all the new instructions in
905 // just a single rescan.
906 for (AllocaInst *AI : Allocas) {
907 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
908 assert(AI->getParent()->getParent() == &F &&
909 "All allocas should be in the same function, which is same as DF!");
911 }
912
913 collectDVRIndirectValuesAtStores();
914
915 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
916 AllocaInst *AI = Allocas[AllocaNum];
917
918 if (AI->use_empty()) {
919 // If there are no uses of the alloca, just delete it now.
920 AI->eraseFromParent();
921
922 // Remove the alloca from the Allocas list, since it has been processed
923 RemoveFromAllocasList(AllocaNum);
924 ++NumDeadAlloca;
925 continue;
926 }
927
928 // Calculate the set of read and write-locations for each alloca. This is
929 // analogous to finding the 'uses' and 'definitions' of each variable.
930 Info.AnalyzeAlloca(AI);
931
932 // If there is only a single store to this value, replace any loads of
933 // it that are directly dominated by the definition with the value stored.
934 if (Info.DefiningBlocks.size() == 1) {
935 if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC,
936 &DVRAssignsToDelete)) {
937 // The alloca has been processed, move on.
938 RemoveFromAllocasList(AllocaNum);
939 ++NumSingleStore;
940 continue;
941 }
942 }
943
944 // If the alloca is only read and written in one basic block, just perform a
945 // linear sweep over the block to eliminate it.
946 if (Info.OnlyUsedInOneBlock &&
947 promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC,
948 &DVRAssignsToDelete, DVRIndirectValuesAtStore,
949 DVRIndirectValueLastStore)) {
950 // The alloca has been processed, move on.
951 RemoveFromAllocasList(AllocaNum);
952 continue;
953 }
954
955 // Initialize BBNumPreds lazily
956 if (BBNumPreds.empty())
957 BBNumPreds.resize(F.getMaxBlockNumber());
958
959 // Remember the dbg.declare record describing this alloca, if any.
960 if (!Info.AssignmentTracking.empty())
961 AllocaATInfo[AllocaNum] = Info.AssignmentTracking;
962 if (!Info.DPUsers.empty())
963 AllocaDPUsers[AllocaNum] = Info.DPUsers;
964 AllocaValueTypes[AllocaNum] = Info.ValueType;
965
966 // Keep the reverse mapping of the 'Allocas' array for the rename pass.
967 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
968
969 // Unique the set of defining blocks for efficient lookup.
970 SmallPtrSet<BasicBlock *, 32> DefBlocks(llvm::from_range,
971 Info.DefiningBlocks);
972
973 // Determine which blocks the value is live in. These are blocks which lead
974 // to uses.
975 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
976 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
977
978 // At this point, we're committed to promoting the alloca using IDF's, and
979 // the standard SSA construction algorithm. Determine which blocks need phi
980 // nodes and see if we can optimize out some work by avoiding insertion of
981 // dead phi nodes.
982 IDF.setLiveInBlocks(LiveInBlocks);
983 IDF.setDefiningBlocks(DefBlocks);
985 IDF.calculate(PHIBlocks);
986 llvm::sort(PHIBlocks, [](BasicBlock *A, BasicBlock *B) {
987 return A->getNumber() < B->getNumber();
988 });
989
990 unsigned CurrentVersion = 0;
991 for (BasicBlock *BB : PHIBlocks)
992 QueuePhiNode(BB, AllocaNum, CurrentVersion);
993 }
994
995 if (Allocas.empty()) {
996 cleanUpDbgAssigns();
997 return; // All of the allocas must have been trivial!
998 }
999 LBI.clear();
1000
1001 // Set the incoming values for the basic block to be null values for all of
1002 // the alloca's. We do this in case there is a load of a value that has not
1003 // been stored yet. In this case, it will get this null value.
1004 IncomingVals.resize(Allocas.size());
1005 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
1006 IncomingVals.init(i, UndefValue::get(AllocaValueTypes[i]));
1007
1008 // When handling debug info, treat all incoming values as if they have
1009 // compiler-generated (empty) locations, representing the uninitialized
1010 // alloca, until proven otherwise.
1011 IncomingLocs.resize(Allocas.size());
1012 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
1013 IncomingLocs.init(i, DebugLoc::getCompilerGenerated());
1014
1015 // The renamer uses the Visited set to avoid infinite loops.
1016 Visited.resize(F.getMaxBlockNumber(), false);
1017
1018 // Add the entry block to the worklist, with a null predecessor.
1019 pushToWorklist(&F.front(), nullptr);
1020
1021 do {
1022 RenamePassData RPD = popFromWorklist();
1023 RenamePass(RPD.BB, RPD.Pred);
1024 } while (!Worklist.empty());
1025
1026 // Remove the allocas themselves from the function.
1027 for (Instruction *A : Allocas) {
1028 // Remove dbg.assigns linked to the alloca as these are now redundant.
1030 // If there are any uses of the alloca instructions left, they must be in
1031 // unreachable basic blocks that were not processed by walking the dominator
1032 // tree. Just delete the users now.
1033 if (!A->use_empty())
1034 A->replaceAllUsesWith(PoisonValue::get(A->getType()));
1035 A->eraseFromParent();
1036 }
1037
1038 // Remove alloca's dbg.declare intrinsics from the function.
1039 for (auto &DbgUsers : AllocaDPUsers) {
1040 for (DbgVariableRecord *DbgItem : DbgUsers)
1041 if (DbgItem->isAddressOfVariable() ||
1042 DbgItem->getExpression()->startsWithDeref())
1043 DbgItem->eraseFromParent();
1044 }
1045
1046 // Loop over all of the PHI nodes and see if there are any that we can get
1047 // rid of because they merge all of the same incoming values. This can
1048 // happen due to undef values coming into the PHI nodes. This process is
1049 // iterative, because eliminating one PHI node can cause others to be removed.
1050 bool EliminatedAPHI = true;
1051 while (EliminatedAPHI) {
1052 EliminatedAPHI = false;
1053
1054 // Iterating over NewPhiNodes is deterministic, so it is safe to try to
1055 // simplify and RAUW them as we go. If it was not, we could add uses to
1056 // the values we replace with in a non-deterministic order, thus creating
1057 // non-deterministic def->use chains.
1058 EliminatedAPHI = NewPhiNodes.remove_if([&](const auto &Entry) {
1059 PHINode *PN = Entry.second;
1060 // If this PHI node merges one value and/or undefs, get the value.
1061 if (Value *V = simplifyInstruction(PN, SQ)) {
1062 PN->replaceAllUsesWith(V);
1063 PN->eraseFromParent();
1064 return true;
1065 }
1066 return false;
1067 });
1068 }
1069
1070 // At this point, the renamer has added entries to PHI nodes for all reachable
1071 // code. Unfortunately, there may be unreachable blocks which the renamer
1072 // hasn't traversed. If this is the case, the PHI nodes may not
1073 // have incoming values for all predecessors. Loop over all PHI nodes we have
1074 // created, inserting poison values if they are missing any incoming values.
1075 for (const auto &PhiNode : NewPhiNodes) {
1076 // We want to do this once per basic block. As such, only process a block
1077 // when we find the PHI that is the first entry in the block.
1078 PHINode *SomePHI = PhiNode.second;
1079 BasicBlock *BB = SomePHI->getParent();
1080 if (&BB->front() != SomePHI)
1081 continue;
1082
1083 // Only do work here if there the PHI nodes are missing incoming values. We
1084 // know that all PHI nodes that were inserted in a block will have the same
1085 // number of incoming values, so we can just check any of them.
1086 if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
1087 continue;
1088
1089 // Get the preds for BB.
1090 SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
1091
1092 // Ok, now we know that all of the PHI nodes are missing entries for some
1093 // basic blocks. Start by sorting the incoming predecessors for efficient
1094 // access.
1095 auto CompareBBNumbers = [](BasicBlock *A, BasicBlock *B) {
1096 return A->getNumber() < B->getNumber();
1097 };
1098 llvm::sort(Preds, CompareBBNumbers);
1099
1100 // Now we loop through all BB's which have entries in SomePHI and remove
1101 // them from the Preds list.
1102 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
1103 // Do a log(n) search of the Preds list for the entry we want.
1105 Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
1106 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
1107 "PHI node has entry for a block which is not a predecessor!");
1108
1109 // Remove the entry
1110 Preds.erase(EntIt);
1111 }
1112
1113 // At this point, the blocks left in the preds list must have dummy
1114 // entries inserted into every PHI nodes for the block. Update all the phi
1115 // nodes in this block that we are inserting (there could be phis before
1116 // mem2reg runs).
1117 unsigned NumBadPreds = SomePHI->getNumIncomingValues();
1118 BasicBlock::iterator BBI = BB->begin();
1119 while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
1120 SomePHI->getNumIncomingValues() == NumBadPreds) {
1121 Value *PoisonVal = PoisonValue::get(SomePHI->getType());
1122 for (BasicBlock *Pred : Preds)
1123 SomePHI->addIncoming(PoisonVal, Pred);
1124 }
1125 }
1126
1127 NewPhiNodes.clear();
1128 cleanUpDbgAssigns();
1129}
1130
1131/// Determine which blocks the value is live in.
1132///
1133/// These are blocks which lead to uses. Knowing this allows us to avoid
1134/// inserting PHI nodes into blocks which don't lead to uses (thus, the
1135/// inserted phi nodes would be dead).
1136void PromoteMem2Reg::ComputeLiveInBlocks(
1137 AllocaInst *AI, AllocaInfo &Info,
1138 const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
1139 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
1140 // To determine liveness, we must iterate through the predecessors of blocks
1141 // where the def is live. Blocks are added to the worklist if we need to
1142 // check their predecessors. Start with all the using blocks.
1143 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
1144 Info.UsingBlocks.end());
1145
1146 // If any of the using blocks is also a definition block, check to see if the
1147 // definition occurs before or after the use. If it happens before the use,
1148 // the value isn't really live-in.
1149 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
1150 BasicBlock *BB = LiveInBlockWorklist[i];
1151 if (!DefBlocks.count(BB))
1152 continue;
1153
1154 // Okay, this is a block that both uses and defines the value. If the first
1155 // reference to the alloca is a def (store), then we know it isn't live-in.
1156 for (BasicBlock::iterator I = BB->begin();; ++I) {
1157 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1158 if (SI->getOperand(1) != AI)
1159 continue;
1160
1161 // We found a store to the alloca before a load. The alloca is not
1162 // actually live-in here.
1163 LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
1164 LiveInBlockWorklist.pop_back();
1165 --i;
1166 --e;
1167 break;
1168 }
1169
1170 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1171 // Okay, we found a load before a store to the alloca. It is actually
1172 // live into this block.
1173 if (LI->getOperand(0) == AI)
1174 break;
1175 }
1176 }
1177
1178 // Now that we have a set of blocks where the phi is live-in, recursively add
1179 // their predecessors until we find the full region the value is live.
1180 while (!LiveInBlockWorklist.empty()) {
1181 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1182
1183 // The block really is live in here, insert it into the set. If already in
1184 // the set, then it has already been processed.
1185 if (!LiveInBlocks.insert(BB).second)
1186 continue;
1187
1188 // Since the value is live into BB, it is either defined in a predecessor or
1189 // live into it to. Add the preds to the worklist unless they are a
1190 // defining block.
1191 for (BasicBlock *P : predecessors(BB)) {
1192 // The value is not live into a predecessor if it defines the value.
1193 if (DefBlocks.count(P))
1194 continue;
1195
1196 // Otherwise it is, add to the worklist.
1197 LiveInBlockWorklist.push_back(P);
1198 }
1199 }
1200}
1201
1202/// Queue a phi-node to be added to a basic-block for a specific Alloca.
1203///
1204/// Returns true if there wasn't already a phi-node for that variable
1205bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
1206 unsigned &Version) {
1207 // Look up the basic-block in question.
1208 PHINode *&PN = NewPhiNodes[std::make_pair(BB->getNumber(), AllocaNo)];
1209
1210 // If the BB already has a phi node added for the i'th alloca then we're done!
1211 if (PN)
1212 return false;
1213
1214 // Create a PhiNode using the type from loads/stores... and add the phi-node
1215 // to the BasicBlock.
1216 PN = PHINode::Create(AllocaValueTypes[AllocaNo], getNumPreds(BB),
1217 Allocas[AllocaNo]->getName() + "." + Twine(Version++));
1218 PN->insertBefore(BB->begin());
1219 ++NumPHIInsert;
1220 PhiToAllocaMap[PN] = AllocaNo;
1221 return true;
1222}
1223
1224/// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
1225/// create a merged location incorporating \p DL, or to set \p DL directly.
1227 bool ApplyMergedLoc) {
1228 if (ApplyMergedLoc)
1230 else
1231 PN->setDebugLoc(DL);
1232}
1233
1234/// Recursively traverse the CFG of the function, renaming loads and
1235/// stores to the allocas which we are promoting.
1236///
1237/// IncomingVals indicates what value each Alloca contains on exit from the
1238/// predecessor block Pred.
1239void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred) {
1240 // If we are inserting any phi nodes into this BB, they will already be in the
1241 // block.
1242 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
1243 // If we have PHI nodes to update, compute the number of edges from Pred to
1244 // BB.
1245 if (PhiToAllocaMap.count(APN)) {
1246 // We want to be able to distinguish between PHI nodes being inserted by
1247 // this invocation of mem2reg from those phi nodes that already existed in
1248 // the IR before mem2reg was run. We determine that APN is being inserted
1249 // because it is missing incoming edges. All other PHI nodes being
1250 // inserted by this pass of mem2reg will have the same number of incoming
1251 // operands so far. Remember this count.
1252 unsigned NewPHINumOperands = APN->getNumOperands();
1253
1254 unsigned NumEdges = llvm::count(successors(Pred), BB);
1255 assert(NumEdges && "Must be at least one edge from Pred to BB!");
1256
1257 // Add entries for all the phis.
1258 BasicBlock::iterator PNI = BB->begin();
1259 do {
1260 unsigned AllocaNo = PhiToAllocaMap[APN];
1261
1262 // Update the location of the phi node.
1263 updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
1264 APN->getNumIncomingValues() > 0);
1265
1266 // Add N incoming values to the PHI node.
1267 for (unsigned i = 0; i != NumEdges; ++i)
1268 APN->addIncoming(IncomingVals[AllocaNo], Pred);
1269
1270 // For the sequence `return X > 0.0 ? X : -X`, it is expected that this
1271 // results in fabs intrinsic. However, without no-signed-zeros(nsz) flag
1272 // on the phi node generated at this stage, fabs folding does not
1273 // happen. So, we try to infer nsz flag from the function attributes to
1274 // enable this fabs folding.
1275 if (isa<FPMathOperator>(APN) && NoSignedZeros)
1276 APN->setHasNoSignedZeros(true);
1277
1278 // The currently active variable for this block is now the PHI.
1279 IncomingVals.set(AllocaNo, APN);
1280 AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
1281 for (DbgVariableRecord *DbgItem : AllocaDPUsers[AllocaNo])
1282 if (DbgItem->isAddressOfVariable())
1283 ConvertDebugDeclareToDebugValue(DbgItem, APN, DIB);
1284
1285 // Get the next phi node.
1286 ++PNI;
1287 APN = dyn_cast<PHINode>(PNI);
1288 if (!APN)
1289 break;
1290
1291 // Verify that it is missing entries. If not, it is not being inserted
1292 // by this mem2reg invocation so we want to ignore it.
1293 } while (APN->getNumOperands() == NewPHINumOperands);
1294 }
1295 }
1296
1297 // Don't revisit blocks.
1298 if (Visited.test(BB->getNumber()))
1299 return;
1300 Visited.set(BB->getNumber());
1301
1302 for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
1303 Instruction *I = &*II++; // get the instruction, increment iterator
1304
1305 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1306 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
1307 if (!Src)
1308 continue;
1309
1310 auto AI = AllocaLookup.find(Src);
1311 if (AI == AllocaLookup.end())
1312 continue;
1313
1314 Value *V = IncomingVals[AI->second];
1315 convertMetadataToAssumes(LI, V, SQ.DL, AC, &DT);
1316
1317 // Anything using the load now uses the current value.
1318 LI->replaceAllUsesWith(V);
1319 LI->eraseFromParent();
1320 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1321 // Delete this instruction and mark the name as the current holder of the
1322 // value
1323 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
1324 if (!Dest)
1325 continue;
1326
1327 auto ai = AllocaLookup.find(Dest);
1328 if (ai == AllocaLookup.end())
1329 continue;
1330
1331 // what value were we writing?
1332 unsigned AllocaNo = ai->second;
1333 IncomingVals.set(AllocaNo, SI->getOperand(0));
1334
1335 // Record debuginfo for the store before removing it.
1336 IncomingLocs.set(AllocaNo, SI->getDebugLoc());
1337 AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB,
1338 &DVRAssignsToDelete);
1339 for (DbgVariableRecord *DbgItem : AllocaDPUsers[ai->second])
1340 if (DbgItem->isAddressOfVariable())
1341 ConvertDebugDeclareToDebugValue(DbgItem, SI, DIB);
1342 SI->eraseFromParent();
1343 }
1344 }
1345
1346 // 'Recurse' to our successors.
1347
1348 // Keep track of the successors so we don't visit the same successor twice
1349 SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
1350
1351 for (BasicBlock *S : reverse(successors(BB)))
1352 if (VisitedSuccs.insert(S).second)
1353 pushToWorklist(S, BB);
1354}
1355
1357 AssumptionCache *AC) {
1358 // If there is nothing to do, bail out...
1359 if (Allocas.empty())
1360 return;
1361
1362 PromoteMem2Reg(Allocas, DT, AC).run();
1363}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static const Function * getParent(const Value *V)
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static DeltaTreeNode * getRoot(void *Root)
This file defines the DenseMap class.
Hexagon Lower HLX Pair Allocas
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
static void convertMetadataToAssumes(LoadInst *LI, Value *Val, const DataLayout &DL, AssumptionCache *AC, const DominatorTree *DT)
static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info, LargeBlockInfo &LBI, const DataLayout &DL, DominatorTree &DT, AssumptionCache *AC, SmallPtrSet< DbgVariableRecord *, 8 > *DVRAssignsToDelete, const DVRIndirectValuesAtStoreMap &DVRIndirectValuesAtStore, const DVRIndirectValueLastStoreMap &DVRIndirectValueLastStore)
Many allocas are only used within a single basic block.
static void removeIntrinsicUsers(AllocaInst *AI)
static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL, bool ApplyMergedLoc)
Update the debug location of a phi.
static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, LargeBlockInfo &LBI, const DataLayout &DL, DominatorTree &DT, AssumptionCache *AC, SmallPtrSet< DbgVariableRecord *, 8 > *DVRAssignsToDelete)
Rewrite as many loads as possible given a single store.
static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI)
Given a LoadInst LI this adds assume(LI != null) after it.
static StringRef getName(Value *V)
static void ComputeLiveInBlocks(const SmallPtrSetImpl< BasicBlock * > &UsingBlocks, const SmallPtrSetImpl< BasicBlock * > &DefBlocks, SmallPtrSetImpl< BasicBlock * > &LiveInBlocks, PredIteratorCache &PredCache)
Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ ICMP_NE
not equal
Definition InstrTypes.h:762
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
DWARF expression.
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
LLVM_ABI std::optional< ArrayRef< uint64_t > > getSingleLocationExpressionElements() const
Returns a reference to the elements contained in this expression, skipping past the leading DW_OP_LLV...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI void eraseFromParent()
LLVM_ABI Instruction * getInstruction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
bool isValueOfVariable() const
Determine if this describes the value of a local variable.
bool isAddressOfVariable() const
Does this describe the address of a local variable.
void setRawLocation(Metadata *NewLocation)
Use of this should generally be avoided; instead, replaceVariableLocationOp and addVariableLocationOp...
void setExpression(DIExpression *NewExpr)
DIExpression * getExpression() const
static LLVM_ABI DbgVariableRecord * createDbgVariableRecord(Value *Location, DILocalVariable *DV, DIExpression *Expr, const DILocation *DI)
A debug info location.
Definition DebugLoc.h:127
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:155
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
Definition DenseMap.h:946
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Class representing an expression and its matching format.
This instruction compares its operands according to the predicate given to the constructor.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Instruction * user_back()
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
typename SuperClass::iterator iterator
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
Definition DebugInfo.h:209
LLVM_ABI void deleteAssignmentMarkers(const Instruction *Inst)
Delete the llvm.dbg.assign intrinsics linked to Inst.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
@ User
could "use" a pointer
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
LLVM_ABI void PromoteMemToReg(ArrayRef< AllocaInst * > Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition Local.cpp:1752
constexpr from_range_t from_range
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
Definition Local.cpp:1703
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRValues(Value *V)
As above, for DVRValues.
Definition DebugInfo.cpp:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IDFCalculator< false > ForwardIDFCalculator
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
auto predecessors(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
const DataLayout & DL
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455