1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal. Doing so would be pretty trivial.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/GlobalsModRef.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Transforms/Utils/Local.h"
42 #define DEBUG_TYPE "dse"
44 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
45 STATISTIC(NumFastStores, "Number of stores deleted");
46 STATISTIC(NumFastOther , "Number of other instrs removed");
49 struct DSE : public FunctionPass {
51 MemoryDependenceAnalysis *MD;
53 const TargetLibraryInfo *TLI;
55 static char ID; // Pass identification, replacement for typeid
56 DSE() : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr) {
57 initializeDSEPass(*PassRegistry::getPassRegistry());
60 bool runOnFunction(Function &F) override {
61 if (skipOptnoneFunction(F))
64 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
65 MD = &getAnalysis<MemoryDependenceAnalysis>();
66 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
67 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
70 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
71 // Only check non-dead blocks. Dead blocks may have strange pointer
72 // cycles that will confuse alias analysis.
73 if (DT->isReachableFromEntry(I))
74 Changed |= runOnBasicBlock(*I);
76 AA = nullptr; MD = nullptr; DT = nullptr;
80 bool runOnBasicBlock(BasicBlock &BB);
81 bool MemoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI);
82 bool HandleFree(CallInst *F);
83 bool handleEndBlock(BasicBlock &BB);
84 void RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
85 SmallSetVector<Value *, 16> &DeadStackObjects,
86 const DataLayout &DL);
88 void getAnalysisUsage(AnalysisUsage &AU) const override {
90 AU.addRequired<DominatorTreeWrapperPass>();
91 AU.addRequired<AAResultsWrapperPass>();
92 AU.addRequired<MemoryDependenceAnalysis>();
93 AU.addRequired<TargetLibraryInfoWrapperPass>();
94 AU.addPreserved<DominatorTreeWrapperPass>();
95 AU.addPreserved<GlobalsAAWrapperPass>();
96 AU.addPreserved<MemoryDependenceAnalysis>();
102 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
103 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
104 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
105 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
106 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
107 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
108 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
110 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
116 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
117 /// and zero out all the operands of this instruction. If any of them become
118 /// dead, delete them and the computation tree that feeds them.
120 /// If ValueSet is non-null, remove any deleted instructions from it as well.
122 static void DeleteDeadInstruction(Instruction *I,
123 MemoryDependenceAnalysis &MD,
124 const TargetLibraryInfo &TLI,
125 SmallSetVector<Value*, 16> *ValueSet = nullptr) {
126 SmallVector<Instruction*, 32> NowDeadInsts;
128 NowDeadInsts.push_back(I);
131 // Before we touch this instruction, remove it from memdep!
133 Instruction *DeadInst = NowDeadInsts.pop_back_val();
136 // This instruction is dead, zap it, in stages. Start by removing it from
137 // MemDep, which needs to know the operands and needs it to be in the
139 MD.removeInstruction(DeadInst);
141 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
142 Value *Op = DeadInst->getOperand(op);
143 DeadInst->setOperand(op, nullptr);
145 // If this operand just became dead, add it to the NowDeadInsts list.
146 if (!Op->use_empty()) continue;
148 if (Instruction *OpI = dyn_cast<Instruction>(Op))
149 if (isInstructionTriviallyDead(OpI, &TLI))
150 NowDeadInsts.push_back(OpI);
153 DeadInst->eraseFromParent();
155 if (ValueSet) ValueSet->remove(DeadInst);
156 } while (!NowDeadInsts.empty());
160 /// hasMemoryWrite - Does this instruction write some memory? This only returns
161 /// true for things that we can analyze with other helpers below.
162 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) {
163 if (isa<StoreInst>(I))
165 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
166 switch (II->getIntrinsicID()) {
169 case Intrinsic::memset:
170 case Intrinsic::memmove:
171 case Intrinsic::memcpy:
172 case Intrinsic::init_trampoline:
173 case Intrinsic::lifetime_end:
177 if (auto CS = CallSite(I)) {
178 if (Function *F = CS.getCalledFunction()) {
179 if (TLI.has(LibFunc::strcpy) &&
180 F->getName() == TLI.getName(LibFunc::strcpy)) {
183 if (TLI.has(LibFunc::strncpy) &&
184 F->getName() == TLI.getName(LibFunc::strncpy)) {
187 if (TLI.has(LibFunc::strcat) &&
188 F->getName() == TLI.getName(LibFunc::strcat)) {
191 if (TLI.has(LibFunc::strncat) &&
192 F->getName() == TLI.getName(LibFunc::strncat)) {
200 /// getLocForWrite - Return a Location stored to by the specified instruction.
201 /// If isRemovable returns true, this function and getLocForRead completely
202 /// describe the memory operations for this instruction.
203 static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
204 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
205 return MemoryLocation::get(SI);
207 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
208 // memcpy/memmove/memset.
209 MemoryLocation Loc = MemoryLocation::getForDest(MI);
213 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
215 return MemoryLocation();
217 switch (II->getIntrinsicID()) {
219 return MemoryLocation(); // Unhandled intrinsic.
220 case Intrinsic::init_trampoline:
221 // FIXME: We don't know the size of the trampoline, so we can't really
223 return MemoryLocation(II->getArgOperand(0));
224 case Intrinsic::lifetime_end: {
225 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
226 return MemoryLocation(II->getArgOperand(1), Len);
231 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
232 /// instruction if any.
233 static MemoryLocation getLocForRead(Instruction *Inst,
234 const TargetLibraryInfo &TLI) {
235 assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case");
237 // The only instructions that both read and write are the mem transfer
238 // instructions (memcpy/memmove).
239 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
240 return MemoryLocation::getForSource(MTI);
241 return MemoryLocation();
245 /// isRemovable - If the value of this instruction and the memory it writes to
246 /// is unused, may we delete this instruction?
247 static bool isRemovable(Instruction *I) {
248 // Don't remove volatile/atomic stores.
249 if (StoreInst *SI = dyn_cast<StoreInst>(I))
250 return SI->isUnordered();
252 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
253 switch (II->getIntrinsicID()) {
254 default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
255 case Intrinsic::lifetime_end:
256 // Never remove dead lifetime_end's, e.g. because it is followed by a
259 case Intrinsic::init_trampoline:
260 // Always safe to remove init_trampoline.
263 case Intrinsic::memset:
264 case Intrinsic::memmove:
265 case Intrinsic::memcpy:
266 // Don't remove volatile memory intrinsics.
267 return !cast<MemIntrinsic>(II)->isVolatile();
271 if (auto CS = CallSite(I))
272 return CS.getInstruction()->use_empty();
278 /// isShortenable - Returns true if this instruction can be safely shortened in
280 static bool isShortenable(Instruction *I) {
281 // Don't shorten stores for now
282 if (isa<StoreInst>(I))
285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
286 switch (II->getIntrinsicID()) {
287 default: return false;
288 case Intrinsic::memset:
289 case Intrinsic::memcpy:
290 // Do shorten memory intrinsics.
295 // Don't shorten libcalls calls for now.
300 /// getStoredPointerOperand - Return the pointer that is being written to.
301 static Value *getStoredPointerOperand(Instruction *I) {
302 if (StoreInst *SI = dyn_cast<StoreInst>(I))
303 return SI->getPointerOperand();
304 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
305 return MI->getDest();
307 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
308 switch (II->getIntrinsicID()) {
309 default: llvm_unreachable("Unexpected intrinsic!");
310 case Intrinsic::init_trampoline:
311 return II->getArgOperand(0);
316 // All the supported functions so far happen to have dest as their first
318 return CS.getArgument(0);
321 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
322 const TargetLibraryInfo &TLI) {
324 if (getObjectSize(V, Size, DL, &TLI))
326 return MemoryLocation::UnknownSize;
338 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
339 /// completely overwrites a store to the 'Earlier' location.
340 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
341 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
342 static OverwriteResult isOverwrite(const MemoryLocation &Later,
343 const MemoryLocation &Earlier,
344 const DataLayout &DL,
345 const TargetLibraryInfo &TLI,
346 int64_t &EarlierOff, int64_t &LaterOff) {
347 const Value *P1 = Earlier.Ptr->stripPointerCasts();
348 const Value *P2 = Later.Ptr->stripPointerCasts();
350 // If the start pointers are the same, we just have to compare sizes to see if
351 // the later store was larger than the earlier store.
353 // If we don't know the sizes of either access, then we can't do a
355 if (Later.Size == MemoryLocation::UnknownSize ||
356 Earlier.Size == MemoryLocation::UnknownSize)
357 return OverwriteUnknown;
359 // Make sure that the Later size is >= the Earlier size.
360 if (Later.Size >= Earlier.Size)
361 return OverwriteComplete;
364 // Otherwise, we have to have size information, and the later store has to be
365 // larger than the earlier one.
366 if (Later.Size == MemoryLocation::UnknownSize ||
367 Earlier.Size == MemoryLocation::UnknownSize)
368 return OverwriteUnknown;
370 // Check to see if the later store is to the entire object (either a global,
371 // an alloca, or a byval/inalloca argument). If so, then it clearly
372 // overwrites any other store to the same object.
373 const Value *UO1 = GetUnderlyingObject(P1, DL),
374 *UO2 = GetUnderlyingObject(P2, DL);
376 // If we can't resolve the same pointers to the same object, then we can't
377 // analyze them at all.
379 return OverwriteUnknown;
381 // If the "Later" store is to a recognizable object, get its size.
382 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
383 if (ObjectSize != MemoryLocation::UnknownSize)
384 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
385 return OverwriteComplete;
387 // Okay, we have stores to two completely different pointers. Try to
388 // decompose the pointer into a "base + constant_offset" form. If the base
389 // pointers are equal, then we can reason about the two stores.
392 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
393 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
395 // If the base pointers still differ, we have two completely different stores.
397 return OverwriteUnknown;
399 // The later store completely overlaps the earlier store if:
401 // 1. Both start at the same offset and the later one's size is greater than
402 // or equal to the earlier one's, or
407 // 2. The earlier store has an offset greater than the later offset, but which
408 // still lies completely within the later store.
411 // |----- later ------|
413 // We have to be careful here as *Off is signed while *.Size is unsigned.
414 if (EarlierOff >= LaterOff &&
415 Later.Size >= Earlier.Size &&
416 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
417 return OverwriteComplete;
419 // The other interesting case is if the later store overwrites the end of
425 // In this case we may want to trim the size of earlier to avoid generating
426 // writes to addresses which will definitely be overwritten later
427 if (LaterOff > EarlierOff &&
428 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
429 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
432 // Otherwise, they don't completely overlap.
433 return OverwriteUnknown;
436 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
437 /// memory region into an identical pointer) then it doesn't actually make its
438 /// input dead in the traditional sense. Consider this case:
443 /// In this case, the second store to A does not make the first store to A dead.
444 /// The usual situation isn't an explicit A<-A store like this (which can be
445 /// trivially removed) but a case where two pointers may alias.
447 /// This function detects when it is unsafe to remove a dependent instruction
448 /// because the DSE inducing instruction may be a self-read.
449 static bool isPossibleSelfRead(Instruction *Inst,
450 const MemoryLocation &InstStoreLoc,
451 Instruction *DepWrite,
452 const TargetLibraryInfo &TLI,
454 // Self reads can only happen for instructions that read memory. Get the
456 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
457 if (!InstReadLoc.Ptr) return false; // Not a reading instruction.
459 // If the read and written loc obviously don't alias, it isn't a read.
460 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
462 // Okay, 'Inst' may copy over itself. However, we can still remove a the
463 // DepWrite instruction if we can prove that it reads from the same location
464 // as Inst. This handles useful cases like:
467 // Here we don't know if A/B may alias, but we do know that B/B are must
468 // aliases, so removing the first memcpy is safe (assuming it writes <= #
469 // bytes as the second one.
470 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
472 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
475 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
476 // then it can't be considered dead.
481 //===----------------------------------------------------------------------===//
483 //===----------------------------------------------------------------------===//
485 bool DSE::runOnBasicBlock(BasicBlock &BB) {
486 const DataLayout &DL = BB.getModule()->getDataLayout();
487 bool MadeChange = false;
489 // Do a top-down walk on the BB.
490 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
491 Instruction *Inst = BBI++;
493 // Handle 'free' calls specially.
494 if (CallInst *F = isFreeCall(Inst, TLI)) {
495 MadeChange |= HandleFree(F);
499 // If we find something that writes memory, get its memory dependence.
500 if (!hasMemoryWrite(Inst, *TLI))
503 // If we're storing the same value back to a pointer that we just
504 // loaded from, then the store can be removed.
505 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
507 auto RemoveDeadInstAndUpdateBBI = [&](Instruction *DeadInst) {
508 // DeleteDeadInstruction can delete the current instruction. Save BBI
509 // in case we need it.
510 WeakVH NextInst(BBI);
512 DeleteDeadInstruction(DeadInst, *MD, *TLI);
514 if (!NextInst) // Next instruction deleted.
516 else if (BBI != BB.begin()) // Revisit this instruction if possible.
518 ++NumRedundantStores;
522 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
523 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
525 MemoryIsNotModifiedBetween(DepLoad, SI)) {
527 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n "
528 << "LOAD: " << *DepLoad << "\n STORE: " << *SI << '\n');
530 RemoveDeadInstAndUpdateBBI(SI);
535 // Remove null stores into the calloc'ed objects
536 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
538 if (StoredConstant && StoredConstant->isNullValue() &&
540 Instruction *UnderlyingPointer = dyn_cast<Instruction>(
541 GetUnderlyingObject(SI->getPointerOperand(), DL));
543 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
544 MemoryIsNotModifiedBetween(UnderlyingPointer, SI)) {
546 << "DSE: Remove null store to the calloc'ed object:\n DEAD: "
547 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n');
549 RemoveDeadInstAndUpdateBBI(SI);
555 MemDepResult InstDep = MD->getDependency(Inst);
557 // Ignore any store where we can't find a local dependence.
558 // FIXME: cross-block DSE would be fun. :)
559 if (!InstDep.isDef() && !InstDep.isClobber())
562 // Figure out what location is being stored to.
563 MemoryLocation Loc = getLocForWrite(Inst, *AA);
565 // If we didn't get a useful location, fail.
569 while (InstDep.isDef() || InstDep.isClobber()) {
570 // Get the memory clobbered by the instruction we depend on. MemDep will
571 // skip any instructions that 'Loc' clearly doesn't interact with. If we
572 // end up depending on a may- or must-aliased load, then we can't optimize
573 // away the store and we bail out. However, if we depend on on something
574 // that overwrites the memory location we *can* potentially optimize it.
576 // Find out what memory location the dependent instruction stores.
577 Instruction *DepWrite = InstDep.getInst();
578 MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA);
579 // If we didn't get a useful location, or if it isn't a size, bail out.
583 // If we find a write that is a) removable (i.e., non-volatile), b) is
584 // completely obliterated by the store to 'Loc', and c) which we know that
585 // 'Inst' doesn't load from, then we can remove it.
586 if (isRemovable(DepWrite) &&
587 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
588 int64_t InstWriteOffset, DepWriteOffset;
590 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset);
591 if (OR == OverwriteComplete) {
592 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
593 << *DepWrite << "\n KILLER: " << *Inst << '\n');
595 // Delete the store and now-dead instructions that feed it.
596 DeleteDeadInstruction(DepWrite, *MD, *TLI);
600 // DeleteDeadInstruction can delete the current instruction in loop
603 if (BBI != BB.begin())
606 } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
607 // TODO: base this on the target vector size so that if the earlier
608 // store was too small to get vector writes anyway then its likely
609 // a good idea to shorten it
610 // Power of 2 vector writes are probably always a bad idea to optimize
611 // as any store/memset/memcpy is likely using vector instructions so
612 // shortening it to not vector size is likely to be slower
613 MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
614 unsigned DepWriteAlign = DepIntrinsic->getAlignment();
615 if (llvm::isPowerOf2_64(InstWriteOffset) ||
616 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
618 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW END: "
619 << *DepWrite << "\n KILLER (offset "
620 << InstWriteOffset << ", "
621 << DepLoc.Size << ")"
624 Value* DepWriteLength = DepIntrinsic->getLength();
625 Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
628 DepIntrinsic->setLength(TrimmedLength);
634 // If this is a may-aliased store that is clobbering the store value, we
635 // can keep searching past it for another must-aliased pointer that stores
636 // to the same location. For example, in:
640 // we can remove the first store to P even though we don't know if P and Q
642 if (DepWrite == &BB.front()) break;
644 // Can't look past this instruction if it might read 'Loc'.
645 if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref)
648 InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
652 // If this block ends in a return, unwind, or unreachable, all allocas are
653 // dead at its end, which means stores to them are also dead.
654 if (BB.getTerminator()->getNumSuccessors() == 0)
655 MadeChange |= handleEndBlock(BB);
660 /// Returns true if the memory which is accessed by the second instruction is not
661 /// modified between the first and the second instruction.
662 /// Precondition: Second instruction must be dominated by the first
664 bool DSE::MemoryIsNotModifiedBetween(Instruction *FirstI,
665 Instruction *SecondI) {
666 SmallVector<BasicBlock *, 16> WorkList;
667 SmallPtrSet<BasicBlock *, 8> Visited;
668 BasicBlock::iterator FirstBBI(FirstI);
670 BasicBlock::iterator SecondBBI(SecondI);
671 BasicBlock *FirstBB = FirstI->getParent();
672 BasicBlock *SecondBB = SecondI->getParent();
673 MemoryLocation MemLoc = MemoryLocation::get(SecondI);
675 // Start checking the store-block.
676 WorkList.push_back(SecondBB);
677 bool isFirstBlock = true;
679 // Check all blocks going backward until we reach the load-block.
680 while (!WorkList.empty()) {
681 BasicBlock *B = WorkList.pop_back_val();
683 // Ignore instructions before LI if this is the FirstBB.
684 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
686 BasicBlock::iterator EI;
688 // Ignore instructions after SI if this is the first visit of SecondBB.
689 assert(B == SecondBB && "first block is not the store block");
691 isFirstBlock = false;
693 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
694 // In this case we also have to look at instructions after SI.
697 for (; BI != EI; ++BI) {
699 if (I->mayWriteToMemory() && I != SecondI) {
700 auto Res = AA->getModRefInfo(I, MemLoc);
701 if (Res != MRI_NoModRef)
706 assert(B != &FirstBB->getParent()->getEntryBlock() &&
707 "Should not hit the entry block because SI must be dominated by LI");
708 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
709 if (!Visited.insert(*PredI).second)
711 WorkList.push_back(*PredI);
718 /// Find all blocks that will unconditionally lead to the block BB and append
720 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
721 BasicBlock *BB, DominatorTree *DT) {
722 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
723 BasicBlock *Pred = *I;
724 if (Pred == BB) continue;
725 TerminatorInst *PredTI = Pred->getTerminator();
726 if (PredTI->getNumSuccessors() != 1)
729 if (DT->isReachableFromEntry(Pred))
730 Blocks.push_back(Pred);
734 /// HandleFree - Handle frees of entire structures whose dependency is a store
735 /// to a field of that structure.
736 bool DSE::HandleFree(CallInst *F) {
737 bool MadeChange = false;
739 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
740 SmallVector<BasicBlock *, 16> Blocks;
741 Blocks.push_back(F->getParent());
742 const DataLayout &DL = F->getModule()->getDataLayout();
744 while (!Blocks.empty()) {
745 BasicBlock *BB = Blocks.pop_back_val();
746 Instruction *InstPt = BB->getTerminator();
747 if (BB == F->getParent()) InstPt = F;
749 MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
750 while (Dep.isDef() || Dep.isClobber()) {
751 Instruction *Dependency = Dep.getInst();
752 if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency))
756 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
758 // Check for aliasing.
759 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
762 Instruction *Next = std::next(BasicBlock::iterator(Dependency));
764 // DCE instructions only used to calculate that store
765 DeleteDeadInstruction(Dependency, *MD, *TLI);
769 // Inst's old Dependency is now deleted. Compute the next dependency,
770 // which may also be dead, as in
772 // s[1] = 0; // This has just been deleted.
774 Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
777 if (Dep.isNonLocal())
778 FindUnconditionalPreds(Blocks, BB, DT);
784 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
785 /// function end block. Ex:
788 /// store i32 1, i32* %A
790 bool DSE::handleEndBlock(BasicBlock &BB) {
791 bool MadeChange = false;
793 // Keep track of all of the stack objects that are dead at the end of the
795 SmallSetVector<Value*, 16> DeadStackObjects;
797 // Find all of the alloca'd pointers in the entry block.
798 BasicBlock *Entry = BB.getParent()->begin();
799 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
800 if (isa<AllocaInst>(I))
801 DeadStackObjects.insert(I);
803 // Okay, so these are dead heap objects, but if the pointer never escapes
804 // then it's leaked by this function anyways.
805 else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
806 DeadStackObjects.insert(I);
809 // Treat byval or inalloca arguments the same, stores to them are dead at the
810 // end of the function.
811 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
812 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
813 if (AI->hasByValOrInAllocaAttr())
814 DeadStackObjects.insert(AI);
816 const DataLayout &DL = BB.getModule()->getDataLayout();
818 // Scan the basic block backwards
819 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
822 // If we find a store, check to see if it points into a dead stack value.
823 if (hasMemoryWrite(BBI, *TLI) && isRemovable(BBI)) {
824 // See through pointer-to-pointer bitcasts
825 SmallVector<Value *, 4> Pointers;
826 GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers, DL);
828 // Stores to stack values are valid candidates for removal.
830 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
831 E = Pointers.end(); I != E; ++I)
832 if (!DeadStackObjects.count(*I)) {
838 Instruction *Dead = BBI++;
840 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
841 << *Dead << "\n Objects: ";
842 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
843 E = Pointers.end(); I != E; ++I) {
845 if (std::next(I) != E)
850 // DCE instructions only used to calculate that store.
851 DeleteDeadInstruction(Dead, *MD, *TLI, &DeadStackObjects);
858 // Remove any dead non-memory-mutating instructions.
859 if (isInstructionTriviallyDead(BBI, TLI)) {
860 Instruction *Inst = BBI++;
861 DeleteDeadInstruction(Inst, *MD, *TLI, &DeadStackObjects);
867 if (isa<AllocaInst>(BBI)) {
868 // Remove allocas from the list of dead stack objects; there can't be
869 // any references before the definition.
870 DeadStackObjects.remove(BBI);
874 if (auto CS = CallSite(BBI)) {
875 // Remove allocation function calls from the list of dead stack objects;
876 // there can't be any references before the definition.
877 if (isAllocLikeFn(BBI, TLI))
878 DeadStackObjects.remove(BBI);
880 // If this call does not access memory, it can't be loading any of our
882 if (AA->doesNotAccessMemory(CS))
885 // If the call might load from any of our allocas, then any store above
887 DeadStackObjects.remove_if([&](Value *I) {
888 // See if the call site touches the value.
889 ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI));
891 return A == MRI_ModRef || A == MRI_Ref;
894 // If all of the allocas were clobbered by the call then we're not going
895 // to find anything else to process.
896 if (DeadStackObjects.empty())
902 MemoryLocation LoadedLoc;
904 // If we encounter a use of the pointer, it is no longer considered dead
905 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
906 if (!L->isUnordered()) // Be conservative with atomic/volatile load
908 LoadedLoc = MemoryLocation::get(L);
909 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
910 LoadedLoc = MemoryLocation::get(V);
911 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
912 LoadedLoc = MemoryLocation::getForSource(MTI);
913 } else if (!BBI->mayReadFromMemory()) {
914 // Instruction doesn't read memory. Note that stores that weren't removed
915 // above will hit this case.
918 // Unknown inst; assume it clobbers everything.
922 // Remove any allocas from the DeadPointer set that are loaded, as this
923 // makes any stores above the access live.
924 RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL);
926 // If all of the allocas were clobbered by the access then we're not going
927 // to find anything else to process.
928 if (DeadStackObjects.empty())
935 /// RemoveAccessedObjects - Check to see if the specified location may alias any
936 /// of the stack objects in the DeadStackObjects set. If so, they become live
937 /// because the location is being loaded.
938 void DSE::RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
939 SmallSetVector<Value *, 16> &DeadStackObjects,
940 const DataLayout &DL) {
941 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
943 // A constant can't be in the dead pointer set.
944 if (isa<Constant>(UnderlyingPointer))
947 // If the kill pointer can be easily reduced to an alloca, don't bother doing
948 // extraneous AA queries.
949 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
950 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
954 // Remove objects that could alias LoadedLoc.
955 DeadStackObjects.remove_if([&](Value *I) {
956 // See if the loaded location could alias the stack location.
957 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
958 return !AA->isNoAlias(StackLoc, LoadedLoc);