Fix PR24469 resulting from r245025 and re-enable dead store elimination across basicb...
[oota-llvm.git] / lib / Transforms / Scalar / DeadStoreElimination.cpp
1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
12 //
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal.  Doing so would be pretty trivial.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/CFG.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
28 #include "llvm/Analysis/PostDominators.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 using namespace llvm;
43
44 #define DEBUG_TYPE "dse"
45
46 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
47 STATISTIC(NumFastStores, "Number of stores deleted");
48 STATISTIC(NumCrossBlockStores, "Number of cross block stores deleted");
49 STATISTIC(NumFastOther , "Number of other instrs removed");
50
51 namespace {
52   struct DSE : public FunctionPass {
53     AliasAnalysis *AA;
54     MemoryDependenceAnalysis *MD;
55     DominatorTree *DT;
56     PostDominatorTree *PDT;
57     const TargetLibraryInfo *TLI;
58     SmallVector<SmallVector<StoreInst *, 8>, 16> Candidates;
59     SetVector<StoreInst *> DeadStores;
60     SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32>
61         BackEdges;
62     DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> BackEdgesMap;
63     static char ID; // Pass identification, replacement for typeid
64     DSE()
65         : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr),
66           PDT(nullptr) {
67       initializeDSEPass(*PassRegistry::getPassRegistry());
68     }
69     // Return all stores in a given BasicBlock.
70     SmallVector<StoreInst *, 8> getStores(BasicBlock *BB) {
71       SmallVector<StoreInst *, 8> VecStores;
72       for (auto &BI : *BB) {
73         if (StoreInst *SI = dyn_cast<StoreInst>(&BI))
74           VecStores.push_back(SI);
75       }
76       return VecStores;
77     }
78
79     // Get dfs in/out on the PDT and populate Candidates store list which
80     // is used to find potential dead stores for a given block
81     void populateCandidateStores(Function &F) {
82       for (auto &I : F) {
83         DomTreeNode *DTNode = PDT->getNode(&I);
84         if (!DTNode)
85           continue;
86         int DFSIn = DTNode->getDFSNumIn();
87         SmallVector<StoreInst *, 8> VecStores = getStores(&I);
88         Candidates[DFSIn] = VecStores;
89       }
90     }
91
92     bool runOnFunction(Function &F) override {
93       if (skipOptnoneFunction(F))
94         return false;
95
96       AA = &getAnalysis<AliasAnalysis>();
97       MD = &getAnalysis<MemoryDependenceAnalysis>();
98       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
99       TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
100       PDT = &getAnalysis<PostDominatorTree>();
101       if (PDT->getRootNode()) {
102         int Count = PDT->getRootNode()->getDFSNumOut();
103         SmallVector<StoreInst *, 8> VecStores;
104         Candidates.resize(Count + 1);
105         Candidates.assign(Count + 1, VecStores);
106
107         // If we have more than 1 block try to populate candidate store.
108         if (Count > 1) {
109           populateCandidateStores(F);
110           FindFunctionBackedges(F, BackEdges);
111           for (auto I : BackEdges)
112             BackEdgesMap.insert(I);
113         }
114       }
115       bool Changed = false;
116       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
117         // Only check non-dead blocks.  Dead blocks may have strange pointer
118         // cycles that will confuse alias analysis.
119         if (DT->isReachableFromEntry(I))
120           Changed |= runOnBasicBlock(*I);
121
122       AA = nullptr; MD = nullptr; DT = nullptr;
123       return Changed;
124     }
125
126     bool runOnBasicBlock(BasicBlock &BB);
127     bool MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI);
128     bool HandleFree(CallInst *F);
129     bool handleEndBlock(BasicBlock &BB);
130     void RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
131                                SmallSetVector<Value *, 16> &DeadStackObjects,
132                                const DataLayout &DL);
133     void handleNonLocalStoreDeletion(StoreInst *SI, BasicBlock::iterator &BBI,
134                                      BasicBlock &CurBlock);
135     bool isSafeCandidateForDeletion(BasicBlock *SrcBlock, BasicBlock *SinkBlock,
136                                     StoreInst *SI);
137     void DeleteDeadInstruction(Instruction *I, MemoryDependenceAnalysis &MD,
138                                const TargetLibraryInfo &TLI,
139                                SmallSetVector<Value *, 16> *ValueSet = nullptr);
140     void getAnalysisUsage(AnalysisUsage &AU) const override {
141       AU.setPreservesCFG();
142       AU.addRequired<DominatorTreeWrapperPass>();
143       AU.addRequired<AliasAnalysis>();
144       AU.addRequired<MemoryDependenceAnalysis>();
145       AU.addRequired<PostDominatorTree>();
146       AU.addRequired<TargetLibraryInfoWrapperPass>();
147       AU.addPreserved<AliasAnalysis>();
148       AU.addPreserved<DominatorTreeWrapperPass>();
149       AU.addPreserved<MemoryDependenceAnalysis>();
150       AU.addPreserved<PostDominatorTree>();
151     }
152   };
153 }
154
155 char DSE::ID = 0;
156 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
157 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
158 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
159 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
160 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
161 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
162 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
163
164 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
165
166 //===----------------------------------------------------------------------===//
167 // Helper functions
168 //===----------------------------------------------------------------------===//
169
170 /// hasMemoryWrite - Does this instruction write some memory?  This only returns
171 /// true for things that we can analyze with other helpers below.
172 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) {
173   if (isa<StoreInst>(I))
174     return true;
175   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
176     switch (II->getIntrinsicID()) {
177     default:
178       return false;
179     case Intrinsic::memset:
180     case Intrinsic::memmove:
181     case Intrinsic::memcpy:
182     case Intrinsic::init_trampoline:
183     case Intrinsic::lifetime_end:
184       return true;
185     }
186   }
187   if (auto CS = CallSite(I)) {
188     if (Function *F = CS.getCalledFunction()) {
189       if (TLI.has(LibFunc::strcpy) &&
190           F->getName() == TLI.getName(LibFunc::strcpy)) {
191         return true;
192       }
193       if (TLI.has(LibFunc::strncpy) &&
194           F->getName() == TLI.getName(LibFunc::strncpy)) {
195         return true;
196       }
197       if (TLI.has(LibFunc::strcat) &&
198           F->getName() == TLI.getName(LibFunc::strcat)) {
199         return true;
200       }
201       if (TLI.has(LibFunc::strncat) &&
202           F->getName() == TLI.getName(LibFunc::strncat)) {
203         return true;
204       }
205     }
206   }
207   return false;
208 }
209
210 /// getLocForWrite - Return a Location stored to by the specified instruction.
211 /// If isRemovable returns true, this function and getLocForRead completely
212 /// describe the memory operations for this instruction.
213 static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
214   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
215     return MemoryLocation::get(SI);
216
217   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
218     // memcpy/memmove/memset.
219     MemoryLocation Loc = MemoryLocation::getForDest(MI);
220     return Loc;
221   }
222
223   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
224   if (!II)
225     return MemoryLocation();
226
227   switch (II->getIntrinsicID()) {
228   default:
229     return MemoryLocation(); // Unhandled intrinsic.
230   case Intrinsic::init_trampoline:
231     // FIXME: We don't know the size of the trampoline, so we can't really
232     // handle it here.
233     return MemoryLocation(II->getArgOperand(0));
234   case Intrinsic::lifetime_end: {
235     uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
236     return MemoryLocation(II->getArgOperand(1), Len);
237   }
238   }
239 }
240
241 /// getLocForRead - Return the location read by the specified "hasMemoryWrite"
242 /// instruction if any.
243 static MemoryLocation getLocForRead(Instruction *Inst,
244                                     const TargetLibraryInfo &TLI) {
245   assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case");
246
247   // The only instructions that both read and write are the mem transfer
248   // instructions (memcpy/memmove).
249   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
250     return MemoryLocation::getForSource(MTI);
251   return MemoryLocation();
252 }
253
254
255 /// isRemovable - If the value of this instruction and the memory it writes to
256 /// is unused, may we delete this instruction?
257 static bool isRemovable(Instruction *I) {
258   // Don't remove volatile/atomic stores.
259   if (StoreInst *SI = dyn_cast<StoreInst>(I))
260     return SI->isUnordered();
261
262   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
263     switch (II->getIntrinsicID()) {
264     default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
265     case Intrinsic::lifetime_end:
266       // Never remove dead lifetime_end's, e.g. because it is followed by a
267       // free.
268       return false;
269     case Intrinsic::init_trampoline:
270       // Always safe to remove init_trampoline.
271       return true;
272
273     case Intrinsic::memset:
274     case Intrinsic::memmove:
275     case Intrinsic::memcpy:
276       // Don't remove volatile memory intrinsics.
277       return !cast<MemIntrinsic>(II)->isVolatile();
278     }
279   }
280
281   if (auto CS = CallSite(I))
282     return CS.getInstruction()->use_empty();
283
284   return false;
285 }
286
287
288 /// isShortenable - Returns true if this instruction can be safely shortened in
289 /// length.
290 static bool isShortenable(Instruction *I) {
291   // Don't shorten stores for now
292   if (isa<StoreInst>(I))
293     return false;
294
295   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
296     switch (II->getIntrinsicID()) {
297       default: return false;
298       case Intrinsic::memset:
299       case Intrinsic::memcpy:
300         // Do shorten memory intrinsics.
301         return true;
302     }
303   }
304
305   // Don't shorten libcalls calls for now.
306
307   return false;
308 }
309
310 /// getStoredPointerOperand - Return the pointer that is being written to.
311 static Value *getStoredPointerOperand(Instruction *I) {
312   if (StoreInst *SI = dyn_cast<StoreInst>(I))
313     return SI->getPointerOperand();
314   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
315     return MI->getDest();
316
317   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
318     switch (II->getIntrinsicID()) {
319     default: llvm_unreachable("Unexpected intrinsic!");
320     case Intrinsic::init_trampoline:
321       return II->getArgOperand(0);
322     }
323   }
324
325   CallSite CS(I);
326   // All the supported functions so far happen to have dest as their first
327   // argument.
328   return CS.getArgument(0);
329 }
330
331 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
332                                const TargetLibraryInfo &TLI) {
333   uint64_t Size;
334   if (getObjectSize(V, Size, DL, &TLI))
335     return Size;
336   return MemoryLocation::UnknownSize;
337 }
338
339 namespace {
340   enum OverwriteResult
341   {
342     OverwriteComplete,
343     OverwriteEnd,
344     OverwriteUnknown
345   };
346 }
347
348 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location
349 /// completely overwrites a store to the 'Earlier' location.
350 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely
351 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined
352 static OverwriteResult isOverwrite(const MemoryLocation &Later,
353                                    const MemoryLocation &Earlier,
354                                    const DataLayout &DL,
355                                    const TargetLibraryInfo &TLI,
356                                    int64_t &EarlierOff, int64_t &LaterOff) {
357   const Value *P1 = Earlier.Ptr->stripPointerCasts();
358   const Value *P2 = Later.Ptr->stripPointerCasts();
359
360   // If the start pointers are the same, we just have to compare sizes to see if
361   // the later store was larger than the earlier store.
362   if (P1 == P2) {
363     // If we don't know the sizes of either access, then we can't do a
364     // comparison.
365     if (Later.Size == MemoryLocation::UnknownSize ||
366         Earlier.Size == MemoryLocation::UnknownSize)
367       return OverwriteUnknown;
368
369     // Make sure that the Later size is >= the Earlier size.
370     if (Later.Size >= Earlier.Size)
371       return OverwriteComplete;
372   }
373
374   // Otherwise, we have to have size information, and the later store has to be
375   // larger than the earlier one.
376   if (Later.Size == MemoryLocation::UnknownSize ||
377       Earlier.Size == MemoryLocation::UnknownSize)
378     return OverwriteUnknown;
379
380   // Check to see if the later store is to the entire object (either a global,
381   // an alloca, or a byval/inalloca argument).  If so, then it clearly
382   // overwrites any other store to the same object.
383   const Value *UO1 = GetUnderlyingObject(P1, DL),
384               *UO2 = GetUnderlyingObject(P2, DL);
385
386   // If we can't resolve the same pointers to the same object, then we can't
387   // analyze them at all.
388   if (UO1 != UO2)
389     return OverwriteUnknown;
390
391   // If the "Later" store is to a recognizable object, get its size.
392   uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
393   if (ObjectSize != MemoryLocation::UnknownSize)
394     if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
395       return OverwriteComplete;
396
397   // Okay, we have stores to two completely different pointers.  Try to
398   // decompose the pointer into a "base + constant_offset" form.  If the base
399   // pointers are equal, then we can reason about the two stores.
400   EarlierOff = 0;
401   LaterOff = 0;
402   const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
403   const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
404
405   // If the base pointers still differ, we have two completely different stores.
406   if (BP1 != BP2)
407     return OverwriteUnknown;
408
409   // The later store completely overlaps the earlier store if:
410   //
411   // 1. Both start at the same offset and the later one's size is greater than
412   //    or equal to the earlier one's, or
413   //
414   //      |--earlier--|
415   //      |--   later   --|
416   //
417   // 2. The earlier store has an offset greater than the later offset, but which
418   //    still lies completely within the later store.
419   //
420   //        |--earlier--|
421   //    |-----  later  ------|
422   //
423   // We have to be careful here as *Off is signed while *.Size is unsigned.
424   if (EarlierOff >= LaterOff &&
425       Later.Size >= Earlier.Size &&
426       uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
427     return OverwriteComplete;
428
429   // The other interesting case is if the later store overwrites the end of
430   // the earlier store
431   //
432   //      |--earlier--|
433   //                |--   later   --|
434   //
435   // In this case we may want to trim the size of earlier to avoid generating
436   // writes to addresses which will definitely be overwritten later
437   if (LaterOff > EarlierOff &&
438       LaterOff < int64_t(EarlierOff + Earlier.Size) &&
439       int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
440     return OverwriteEnd;
441
442   // Otherwise, they don't completely overlap.
443   return OverwriteUnknown;
444 }
445
446 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a
447 /// memory region into an identical pointer) then it doesn't actually make its
448 /// input dead in the traditional sense.  Consider this case:
449 ///
450 ///   memcpy(A <- B)
451 ///   memcpy(A <- A)
452 ///
453 /// In this case, the second store to A does not make the first store to A dead.
454 /// The usual situation isn't an explicit A<-A store like this (which can be
455 /// trivially removed) but a case where two pointers may alias.
456 ///
457 /// This function detects when it is unsafe to remove a dependent instruction
458 /// because the DSE inducing instruction may be a self-read.
459 static bool isPossibleSelfRead(Instruction *Inst,
460                                const MemoryLocation &InstStoreLoc,
461                                Instruction *DepWrite,
462                                const TargetLibraryInfo &TLI,
463                                AliasAnalysis &AA) {
464   // Self reads can only happen for instructions that read memory.  Get the
465   // location read.
466   MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
467   if (!InstReadLoc.Ptr) return false;  // Not a reading instruction.
468
469   // If the read and written loc obviously don't alias, it isn't a read.
470   if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
471
472   // Okay, 'Inst' may copy over itself.  However, we can still remove a the
473   // DepWrite instruction if we can prove that it reads from the same location
474   // as Inst.  This handles useful cases like:
475   //   memcpy(A <- B)
476   //   memcpy(A <- B)
477   // Here we don't know if A/B may alias, but we do know that B/B are must
478   // aliases, so removing the first memcpy is safe (assuming it writes <= #
479   // bytes as the second one.
480   MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
481
482   if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
483     return false;
484
485   // If DepWrite doesn't read memory or if we can't prove it is a must alias,
486   // then it can't be considered dead.
487   return true;
488 }
489
490
491 //===----------------------------------------------------------------------===//
492 // DSE Pass
493 //===----------------------------------------------------------------------===//
494
495 bool DSE::runOnBasicBlock(BasicBlock &BB) {
496   bool MadeChange = false;
497
498   // Do a top-down walk on the BB.
499   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
500     Instruction *Inst = BBI++;
501
502     // Handle 'free' calls specially.
503     if (CallInst *F = isFreeCall(Inst, TLI)) {
504       MadeChange |= HandleFree(F);
505       continue;
506     }
507
508     // If we find something that writes memory, get its memory dependence.
509     if (!hasMemoryWrite(Inst, *TLI))
510       continue;
511
512     // If we're storing the same value back to a pointer that we just
513     // loaded from, then the store can be removed.
514     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
515       if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
516         if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
517             isRemovable(SI) &&
518             MemoryIsNotModifiedBetween(DepLoad, SI)) {
519
520           DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n  "
521                        << "LOAD: " << *DepLoad << "\n  STORE: " << *SI << '\n');
522
523           // DeleteDeadInstruction can delete the current instruction.  Save BBI
524           // in case we need it.
525           WeakVH NextInst(BBI);
526
527           DeleteDeadInstruction(SI, *MD, *TLI);
528
529           if (!NextInst)  // Next instruction deleted.
530             BBI = BB.begin();
531           else if (BBI != BB.begin())  // Revisit this instruction if possible.
532             --BBI;
533           ++NumRedundantStores;
534           MadeChange = true;
535           continue;
536         }
537       }
538     }
539
540     MemDepResult InstDep = MD->getDependency(Inst);
541
542     if (!InstDep.isDef() && !InstDep.isClobber() && !InstDep.isNonLocal())
543       continue;
544     if (InstDep.isNonLocal()) {
545       if (!PDT->getRootNode())
546         continue;
547       if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
548         handleNonLocalStoreDeletion(SI, BBI, BB);
549       continue;
550     }
551
552     // Figure out what location is being stored to.
553     MemoryLocation Loc = getLocForWrite(Inst, *AA);
554
555     // If we didn't get a useful location, fail.
556     if (!Loc.Ptr)
557       continue;
558
559     while (InstDep.isDef() || InstDep.isClobber()) {
560       // Get the memory clobbered by the instruction we depend on.  MemDep will
561       // skip any instructions that 'Loc' clearly doesn't interact with.  If we
562       // end up depending on a may- or must-aliased load, then we can't optimize
563       // away the store and we bail out.  However, if we depend on on something
564       // that overwrites the memory location we *can* potentially optimize it.
565       //
566       // Find out what memory location the dependent instruction stores.
567       Instruction *DepWrite = InstDep.getInst();
568       MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA);
569       // If we didn't get a useful location, or if it isn't a size, bail out.
570       if (!DepLoc.Ptr)
571         break;
572
573       // If we find a write that is a) removable (i.e., non-volatile), b) is
574       // completely obliterated by the store to 'Loc', and c) which we know that
575       // 'Inst' doesn't load from, then we can remove it.
576       if (isRemovable(DepWrite) &&
577           !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
578         int64_t InstWriteOffset, DepWriteOffset;
579         const DataLayout &DL = BB.getModule()->getDataLayout();
580         OverwriteResult OR =
581             isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset);
582         if (OR == OverwriteComplete) {
583           DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: "
584                 << *DepWrite << "\n  KILLER: " << *Inst << '\n');
585
586           // Delete the store and now-dead instructions that feed it.
587           DeleteDeadInstruction(DepWrite, *MD, *TLI);
588           ++NumFastStores;
589           MadeChange = true;
590
591           // DeleteDeadInstruction can delete the current instruction in loop
592           // cases, reset BBI.
593           BBI = Inst;
594           if (BBI != BB.begin())
595             --BBI;
596           break;
597         } else if (OR == OverwriteEnd && isShortenable(DepWrite)) {
598           // TODO: base this on the target vector size so that if the earlier
599           // store was too small to get vector writes anyway then its likely
600           // a good idea to shorten it
601           // Power of 2 vector writes are probably always a bad idea to optimize
602           // as any store/memset/memcpy is likely using vector instructions so
603           // shortening it to not vector size is likely to be slower
604           MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
605           unsigned DepWriteAlign = DepIntrinsic->getAlignment();
606           if (llvm::isPowerOf2_64(InstWriteOffset) ||
607               ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
608
609             DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW END: "
610                   << *DepWrite << "\n  KILLER (offset "
611                   << InstWriteOffset << ", "
612                   << DepLoc.Size << ")"
613                   << *Inst << '\n');
614
615             Value* DepWriteLength = DepIntrinsic->getLength();
616             Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(),
617                                                     InstWriteOffset -
618                                                     DepWriteOffset);
619             DepIntrinsic->setLength(TrimmedLength);
620             MadeChange = true;
621           }
622         }
623       }
624
625       // If this is a may-aliased store that is clobbering the store value, we
626       // can keep searching past it for another must-aliased pointer that stores
627       // to the same location.  For example, in:
628       //   store -> P
629       //   store -> Q
630       //   store -> P
631       // we can remove the first store to P even though we don't know if P and Q
632       // alias.
633       if (DepWrite == &BB.front()) break;
634
635       // Can't look past this instruction if it might read 'Loc'.
636       if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref)
637         break;
638
639       InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
640     }
641   }
642
643   // If this block ends in a return, unwind, or unreachable, all allocas are
644   // dead at its end, which means stores to them are also dead.
645   if (BB.getTerminator()->getNumSuccessors() == 0)
646     MadeChange |= handleEndBlock(BB);
647
648   return MadeChange;
649 }
650
651 /// Returns true if the memory which is accessed by the store instruction is not
652 /// modified between the load and the store instruction.
653 /// Precondition: The store instruction must be dominated by the load
654 /// instruction.
655 bool DSE::MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI) {
656   SmallVector<BasicBlock *, 16> WorkList;
657   SmallPtrSet<BasicBlock *, 8> Visited;
658   BasicBlock::iterator LoadBBI(LI);
659   ++LoadBBI;
660   BasicBlock::iterator StoreBBI(SI);
661   BasicBlock *LoadBB = LI->getParent();
662   BasicBlock *StoreBB = SI->getParent();
663   MemoryLocation StoreLoc = MemoryLocation::get(SI);
664
665   // Start checking the store-block.
666   WorkList.push_back(StoreBB);
667   bool isFirstBlock = true;
668
669   // Check all blocks going backward until we reach the load-block.
670   while (!WorkList.empty()) {
671     BasicBlock *B = WorkList.pop_back_val();
672
673     // Ignore instructions before LI if this is the LoadBB.
674     BasicBlock::iterator BI = (B == LoadBB ? LoadBBI : B->begin());
675
676     BasicBlock::iterator EI;
677     if (isFirstBlock) {
678       // Ignore instructions after SI if this is the first visit of StoreBB.
679       assert(B == StoreBB && "first block is not the store block");
680       EI = StoreBBI;
681       isFirstBlock = false;
682     } else {
683       // It's not StoreBB or (in case of a loop) the second visit of StoreBB.
684       // In this case we also have to look at instructions after SI.
685       EI = B->end();
686     }
687     for (; BI != EI; ++BI) {
688       Instruction *I = BI;
689       if (I->mayWriteToMemory() && I != SI) {
690         auto Res = AA->getModRefInfo(I, StoreLoc);
691         if (Res != MRI_NoModRef)
692           return false;
693       }
694     }
695     if (B != LoadBB) {
696       assert(B != &LoadBB->getParent()->getEntryBlock() &&
697           "Should not hit the entry block because SI must be dominated by LI");
698       for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
699         if (!Visited.insert(*PredI).second)
700           continue;
701         WorkList.push_back(*PredI);
702       }
703     }
704   }
705   return true;
706 }
707
708 /// Find all blocks that will unconditionally lead to the block BB and append
709 /// them to F.
710 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
711                                    BasicBlock *BB, DominatorTree *DT) {
712   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
713     BasicBlock *Pred = *I;
714     if (Pred == BB) continue;
715     TerminatorInst *PredTI = Pred->getTerminator();
716     if (PredTI->getNumSuccessors() != 1)
717       continue;
718
719     if (DT->isReachableFromEntry(Pred))
720       Blocks.push_back(Pred);
721   }
722 }
723
724 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
725 /// and zero out all the operands of this instruction.  If any of them become
726 /// dead, delete them and the computation tree that feeds them.
727 /// If ValueSet is non-null, remove any deleted instructions from it as well.
728 void DSE::DeleteDeadInstruction(Instruction *I, MemoryDependenceAnalysis &MD,
729                                 const TargetLibraryInfo &TLI,
730                                 SmallSetVector<Value *, 16> *ValueSet) {
731   SmallVector<Instruction *, 32> NowDeadInsts;
732
733   NowDeadInsts.push_back(I);
734   --NumFastOther;
735
736   // Before we touch this instruction, remove it from memdep!
737   do {
738     Instruction *DeadInst = NowDeadInsts.pop_back_val();
739     ++NumFastOther;
740     if (StoreInst *SI = dyn_cast<StoreInst>(DeadInst))
741       DeadStores.insert(SI);
742
743     // This instruction is dead, zap it, in stages.  Start by removing it from
744     // MemDep, which needs to know the operands and needs it to be in the
745     // function.
746     MD.removeInstruction(DeadInst);
747
748     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
749       Value *Op = DeadInst->getOperand(op);
750       DeadInst->setOperand(op, nullptr);
751
752       // If this operand just became dead, add it to the NowDeadInsts list.
753       if (!Op->use_empty())
754         continue;
755
756       if (Instruction *OpI = dyn_cast<Instruction>(Op))
757         if (isInstructionTriviallyDead(OpI, &TLI))
758           NowDeadInsts.push_back(OpI);
759     }
760
761     DeadInst->eraseFromParent();
762
763     if (ValueSet)
764       ValueSet->remove(DeadInst);
765   } while (!NowDeadInsts.empty());
766 }
767
768 /// HandleFree - Handle frees of entire structures whose dependency is a store
769 /// to a field of that structure.
770 bool DSE::HandleFree(CallInst *F) {
771   bool MadeChange = false;
772
773   MemoryLocation Loc = MemoryLocation(F->getOperand(0));
774   SmallVector<BasicBlock *, 16> Blocks;
775   Blocks.push_back(F->getParent());
776   const DataLayout &DL = F->getModule()->getDataLayout();
777
778   while (!Blocks.empty()) {
779     BasicBlock *BB = Blocks.pop_back_val();
780     Instruction *InstPt = BB->getTerminator();
781     if (BB == F->getParent()) InstPt = F;
782
783     MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB);
784     while (Dep.isDef() || Dep.isClobber()) {
785       Instruction *Dependency = Dep.getInst();
786       if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency))
787         break;
788
789       Value *DepPointer =
790           GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
791
792       // Check for aliasing.
793       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
794         break;
795
796       Instruction *Next = std::next(BasicBlock::iterator(Dependency));
797
798       // DCE instructions only used to calculate that store
799       DeleteDeadInstruction(Dependency, *MD, *TLI);
800       ++NumFastStores;
801       MadeChange = true;
802
803       // Inst's old Dependency is now deleted. Compute the next dependency,
804       // which may also be dead, as in
805       //    s[0] = 0;
806       //    s[1] = 0; // This has just been deleted.
807       //    free(s);
808       Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
809     }
810
811     if (Dep.isNonLocal())
812       FindUnconditionalPreds(Blocks, BB, DT);
813   }
814
815   return MadeChange;
816 }
817
818 /// handleEndBlock - Remove dead stores to stack-allocated locations in the
819 /// function end block.  Ex:
820 /// %A = alloca i32
821 /// ...
822 /// store i32 1, i32* %A
823 /// ret void
824 bool DSE::handleEndBlock(BasicBlock &BB) {
825   bool MadeChange = false;
826
827   // Keep track of all of the stack objects that are dead at the end of the
828   // function.
829   SmallSetVector<Value*, 16> DeadStackObjects;
830
831   // Find all of the alloca'd pointers in the entry block.
832   BasicBlock *Entry = BB.getParent()->begin();
833   for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) {
834     if (isa<AllocaInst>(I))
835       DeadStackObjects.insert(I);
836
837     // Okay, so these are dead heap objects, but if the pointer never escapes
838     // then it's leaked by this function anyways.
839     else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true))
840       DeadStackObjects.insert(I);
841   }
842
843   // Treat byval or inalloca arguments the same, stores to them are dead at the
844   // end of the function.
845   for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
846        AE = BB.getParent()->arg_end(); AI != AE; ++AI)
847     if (AI->hasByValOrInAllocaAttr())
848       DeadStackObjects.insert(AI);
849
850   const DataLayout &DL = BB.getModule()->getDataLayout();
851
852   // Scan the basic block backwards
853   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
854     --BBI;
855
856     // If we find a store, check to see if it points into a dead stack value.
857     if (hasMemoryWrite(BBI, *TLI) && isRemovable(BBI)) {
858       // See through pointer-to-pointer bitcasts
859       SmallVector<Value *, 4> Pointers;
860       GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers, DL);
861
862       // Stores to stack values are valid candidates for removal.
863       bool AllDead = true;
864       for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
865            E = Pointers.end(); I != E; ++I)
866         if (!DeadStackObjects.count(*I)) {
867           AllDead = false;
868           break;
869         }
870
871       if (AllDead) {
872         Instruction *Dead = BBI++;
873
874         DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
875                      << *Dead << "\n  Objects: ";
876               for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
877                    E = Pointers.end(); I != E; ++I) {
878                 dbgs() << **I;
879                 if (std::next(I) != E)
880                   dbgs() << ", ";
881               }
882               dbgs() << '\n');
883
884         // DCE instructions only used to calculate that store.
885         DeleteDeadInstruction(Dead, *MD, *TLI, &DeadStackObjects);
886         ++NumFastStores;
887         MadeChange = true;
888         continue;
889       }
890     }
891
892     // Remove any dead non-memory-mutating instructions.
893     if (isInstructionTriviallyDead(BBI, TLI)) {
894       Instruction *Inst = BBI++;
895       DeleteDeadInstruction(Inst, *MD, *TLI, &DeadStackObjects);
896       ++NumFastOther;
897       MadeChange = true;
898       continue;
899     }
900
901     if (isa<AllocaInst>(BBI)) {
902       // Remove allocas from the list of dead stack objects; there can't be
903       // any references before the definition.
904       DeadStackObjects.remove(BBI);
905       continue;
906     }
907
908     if (auto CS = CallSite(BBI)) {
909       // Remove allocation function calls from the list of dead stack objects; 
910       // there can't be any references before the definition.
911       if (isAllocLikeFn(BBI, TLI))
912         DeadStackObjects.remove(BBI);
913
914       // If this call does not access memory, it can't be loading any of our
915       // pointers.
916       if (AA->doesNotAccessMemory(CS))
917         continue;
918
919       // If the call might load from any of our allocas, then any store above
920       // the call is live.
921       DeadStackObjects.remove_if([&](Value *I) {
922         // See if the call site touches the value.
923         ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI));
924
925         return A == MRI_ModRef || A == MRI_Ref;
926       });
927
928       // If all of the allocas were clobbered by the call then we're not going
929       // to find anything else to process.
930       if (DeadStackObjects.empty())
931         break;
932
933       continue;
934     }
935
936     MemoryLocation LoadedLoc;
937
938     // If we encounter a use of the pointer, it is no longer considered dead
939     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
940       if (!L->isUnordered()) // Be conservative with atomic/volatile load
941         break;
942       LoadedLoc = MemoryLocation::get(L);
943     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
944       LoadedLoc = MemoryLocation::get(V);
945     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
946       LoadedLoc = MemoryLocation::getForSource(MTI);
947     } else if (!BBI->mayReadFromMemory()) {
948       // Instruction doesn't read memory.  Note that stores that weren't removed
949       // above will hit this case.
950       continue;
951     } else {
952       // Unknown inst; assume it clobbers everything.
953       break;
954     }
955
956     // Remove any allocas from the DeadPointer set that are loaded, as this
957     // makes any stores above the access live.
958     RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL);
959
960     // If all of the allocas were clobbered by the access then we're not going
961     // to find anything else to process.
962     if (DeadStackObjects.empty())
963       break;
964   }
965
966   return MadeChange;
967 }
968
969 /// RemoveAccessedObjects - Check to see if the specified location may alias any
970 /// of the stack objects in the DeadStackObjects set.  If so, they become live
971 /// because the location is being loaded.
972 void DSE::RemoveAccessedObjects(const MemoryLocation &LoadedLoc,
973                                 SmallSetVector<Value *, 16> &DeadStackObjects,
974                                 const DataLayout &DL) {
975   const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
976
977   // A constant can't be in the dead pointer set.
978   if (isa<Constant>(UnderlyingPointer))
979     return;
980
981   // If the kill pointer can be easily reduced to an alloca, don't bother doing
982   // extraneous AA queries.
983   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
984     DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
985     return;
986   }
987
988   // Remove objects that could alias LoadedLoc.
989   DeadStackObjects.remove_if([&](Value *I) {
990     // See if the loaded location could alias the stack location.
991     MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
992     return !AA->isNoAlias(StackLoc, LoadedLoc);
993   });
994 }
995
996 /// isSafeCandidateForDeletion- Check all paths from the SrcBlock till
997 /// SinkBlock to see if Store 'SI' is safe to be remove.
998 /// Returns true if the candidate store SI is safe to delete
999 /// else returns false.
1000 bool DSE::isSafeCandidateForDeletion(BasicBlock *SrcBlock,
1001                                      BasicBlock *SinkBlock, StoreInst *SI) {
1002   SmallVector<BasicBlock *, 16> WorkList;
1003   SmallPtrSet<BasicBlock *, 8> Visited;
1004   BasicBlock::iterator BBI(SI);
1005
1006   // Check from the store till end of block and make sure we have no references
1007   // to memory stored by this Store Instruction.
1008   for (auto BI = ++BBI, BE = SrcBlock->end(); BI != BE; ++BI) {
1009     Instruction *I = BI;
1010     StoreInst *CSI = dyn_cast<StoreInst>(I);
1011     if (CSI) {
1012       AliasResult R =
1013           AA->alias(MemoryLocation::get(SI), MemoryLocation::get(CSI));
1014       if (R == MustAlias)
1015         return true;
1016     } else {
1017       ModRefInfo Res = AA->getModRefInfo(I, MemoryLocation::get(SI));
1018       if (Res != MRI_NoModRef)
1019         return false;
1020     }
1021   }
1022
1023   // Add successors of the block to stack and start DFS.
1024   for (succ_iterator I = succ_begin(SrcBlock), E = succ_end(SrcBlock); I != E;
1025        ++I) {
1026     if (!Visited.insert(*I).second)
1027       continue;
1028     // A path with backedge may not be safe. Conservatively mark
1029     // this store unsafe.
1030     if (BackEdgesMap.count(std::make_pair(SrcBlock, *I)))
1031       return false;
1032     WorkList.push_back(*I);
1033   }
1034
1035   while (!WorkList.empty()) {
1036     BasicBlock *B = WorkList.pop_back_val();
1037     auto BI = B->begin();
1038     auto BE = B->end();
1039     for (; BI != BE; ++BI) {
1040       Instruction *I = BI;
1041       StoreInst *CSI = dyn_cast<StoreInst>(I);
1042       if (CSI) {
1043         AliasResult R =
1044             AA->alias(MemoryLocation::get(SI), MemoryLocation::get(CSI));
1045         if (R == MustAlias)
1046           break;
1047       } else {
1048         ModRefInfo Res = AA->getModRefInfo(I, MemoryLocation::get(SI));
1049         if (Res != MRI_NoModRef)
1050           return false;
1051       }
1052     }
1053
1054     // If we reached the sink node or we found a block which has a stores that
1055     // overwrites the candidate block we need not look at their successors.
1056     if (B == SinkBlock || BI != BE)
1057       continue;
1058
1059     for (succ_iterator I = succ_begin(B), E = succ_end(B); I != E; ++I) {
1060       if (!Visited.insert(*I).second)
1061         continue;
1062       // A path with backedge may not be safe.Conservatively mark
1063       // this store unsafe.
1064       if (BackEdgesMap.count(std::make_pair(B, *I)))
1065         return false;
1066       WorkList.push_back(*I);
1067     }
1068   }
1069
1070   return true;
1071 }
1072
1073 /// handleNonLocalStoreDeletion - Handle non local dead store elimination.
1074 /// This works by finding candidate stores using PDT and then running DFS
1075 /// from candidate store block checking all paths to make sure the store is
1076 /// safe to delete.
1077 void DSE::handleNonLocalStoreDeletion(StoreInst *SI, BasicBlock::iterator &BBI,
1078                                       BasicBlock &CurBlock) {
1079   BasicBlock *BB = SI->getParent();
1080   Value *Pointer = SI->getPointerOperand();
1081   DomTreeNode *DTNode = PDT->getNode(BB);
1082   if (!DTNode)
1083     return;
1084
1085   int DFSNumIn = DTNode->getDFSNumIn();
1086   int DFSNumOut = DTNode->getDFSNumOut();
1087   for (int i = DFSNumIn + 1; i < DFSNumOut; ++i) {
1088     for (auto &I : Candidates[i]) {
1089       StoreInst *CandidateSI = I;
1090       if (DeadStores.count(CandidateSI))
1091         continue;
1092       Value *MemPtr = CandidateSI->getPointerOperand();
1093       if (!MemPtr)
1094         continue;
1095       if (Pointer->getType() != MemPtr->getType())
1096         continue;
1097       AliasResult R =
1098           AA->alias(MemoryLocation::get(SI), MemoryLocation::get(CandidateSI));
1099       if (R != MustAlias)
1100         continue;
1101       if (isSafeCandidateForDeletion(CandidateSI->getParent(), BB,
1102                                      CandidateSI)) {
1103         DeleteDeadInstruction(CandidateSI, *MD, *TLI);
1104         ++NumCrossBlockStores;
1105         // DeleteDeadInstruction can delete the current instruction in loop
1106         // cases, reset BBI.
1107         BBI = SI;
1108         if (BBI != CurBlock.begin())
1109           --BBI;
1110       }
1111     }
1112   }
1113 }