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/DeadStoreElimination.h"
19 #include "llvm/ADT/DenseMap.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/GlobalsModRef.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include <map>
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "dse"
48 
49 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
50 STATISTIC(NumFastStores, "Number of stores deleted");
51 STATISTIC(NumFastOther , "Number of other instrs removed");
52 STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
53 STATISTIC(NumModifiedStores, "Number of stores modified");
54 
55 static cl::opt<bool>
56 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking",
57   cl::init(true), cl::Hidden,
58   cl::desc("Enable partial-overwrite tracking in DSE"));
59 
60 static cl::opt<bool>
61 EnablePartialStoreMerging("enable-dse-partial-store-merging",
62   cl::init(true), cl::Hidden,
63   cl::desc("Enable partial store merging in DSE"));
64 
65 
66 //===----------------------------------------------------------------------===//
67 // Helper functions
68 //===----------------------------------------------------------------------===//
69 typedef std::map<int64_t, int64_t> OverlapIntervalsTy;
70 typedef DenseMap<Instruction *, OverlapIntervalsTy> InstOverlapIntervalsTy;
71 
72 /// Delete this instruction.  Before we do, go through and zero out all the
73 /// operands of this instruction.  If any of them become dead, delete them and
74 /// the computation tree that feeds them.
75 /// If ValueSet is non-null, remove any deleted instructions from it as well.
76 static void
77 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI,
78                       MemoryDependenceResults &MD, const TargetLibraryInfo &TLI,
79                       InstOverlapIntervalsTy &IOL,
80                       DenseMap<Instruction*, size_t> *InstrOrdering,
81                       SmallSetVector<Value *, 16> *ValueSet = nullptr) {
82   SmallVector<Instruction*, 32> NowDeadInsts;
83 
84   NowDeadInsts.push_back(I);
85   --NumFastOther;
86 
87   // Keeping the iterator straight is a pain, so we let this routine tell the
88   // caller what the next instruction is after we're done mucking about.
89   BasicBlock::iterator NewIter = *BBI;
90 
91   // Before we touch this instruction, remove it from memdep!
92   do {
93     Instruction *DeadInst = NowDeadInsts.pop_back_val();
94     ++NumFastOther;
95 
96     // This instruction is dead, zap it, in stages.  Start by removing it from
97     // MemDep, which needs to know the operands and needs it to be in the
98     // function.
99     MD.removeInstruction(DeadInst);
100 
101     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
102       Value *Op = DeadInst->getOperand(op);
103       DeadInst->setOperand(op, nullptr);
104 
105       // If this operand just became dead, add it to the NowDeadInsts list.
106       if (!Op->use_empty()) continue;
107 
108       if (Instruction *OpI = dyn_cast<Instruction>(Op))
109         if (isInstructionTriviallyDead(OpI, &TLI))
110           NowDeadInsts.push_back(OpI);
111     }
112 
113     if (ValueSet) ValueSet->remove(DeadInst);
114     InstrOrdering->erase(DeadInst);
115     IOL.erase(DeadInst);
116 
117     if (NewIter == DeadInst->getIterator())
118       NewIter = DeadInst->eraseFromParent();
119     else
120       DeadInst->eraseFromParent();
121   } while (!NowDeadInsts.empty());
122   *BBI = NewIter;
123 }
124 
125 /// Does this instruction write some memory?  This only returns true for things
126 /// that we can analyze with other helpers below.
127 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) {
128   if (isa<StoreInst>(I))
129     return true;
130   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
131     switch (II->getIntrinsicID()) {
132     default:
133       return false;
134     case Intrinsic::memset:
135     case Intrinsic::memmove:
136     case Intrinsic::memcpy:
137     case Intrinsic::init_trampoline:
138     case Intrinsic::lifetime_end:
139       return true;
140     }
141   }
142   if (auto CS = CallSite(I)) {
143     if (Function *F = CS.getCalledFunction()) {
144       StringRef FnName = F->getName();
145       if (TLI.has(LibFunc_strcpy) && FnName == TLI.getName(LibFunc_strcpy))
146         return true;
147       if (TLI.has(LibFunc_strncpy) && FnName == TLI.getName(LibFunc_strncpy))
148         return true;
149       if (TLI.has(LibFunc_strcat) && FnName == TLI.getName(LibFunc_strcat))
150         return true;
151       if (TLI.has(LibFunc_strncat) && FnName == TLI.getName(LibFunc_strncat))
152         return true;
153     }
154   }
155   return false;
156 }
157 
158 /// Return a Location stored to by the specified instruction. If isRemovable
159 /// returns true, this function and getLocForRead completely describe the memory
160 /// operations for this instruction.
161 static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
162   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
163     return MemoryLocation::get(SI);
164 
165   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
166     // memcpy/memmove/memset.
167     MemoryLocation Loc = MemoryLocation::getForDest(MI);
168     return Loc;
169   }
170 
171   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
172   if (!II)
173     return MemoryLocation();
174 
175   switch (II->getIntrinsicID()) {
176   default:
177     return MemoryLocation(); // Unhandled intrinsic.
178   case Intrinsic::init_trampoline:
179     // FIXME: We don't know the size of the trampoline, so we can't really
180     // handle it here.
181     return MemoryLocation(II->getArgOperand(0));
182   case Intrinsic::lifetime_end: {
183     uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
184     return MemoryLocation(II->getArgOperand(1), Len);
185   }
186   }
187 }
188 
189 /// Return the location read by the specified "hasMemoryWrite" instruction if
190 /// any.
191 static MemoryLocation getLocForRead(Instruction *Inst,
192                                     const TargetLibraryInfo &TLI) {
193   assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case");
194 
195   // The only instructions that both read and write are the mem transfer
196   // instructions (memcpy/memmove).
197   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
198     return MemoryLocation::getForSource(MTI);
199   return MemoryLocation();
200 }
201 
202 /// If the value of this instruction and the memory it writes to is unused, may
203 /// we delete this instruction?
204 static bool isRemovable(Instruction *I) {
205   // Don't remove volatile/atomic stores.
206   if (StoreInst *SI = dyn_cast<StoreInst>(I))
207     return SI->isUnordered();
208 
209   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
210     switch (II->getIntrinsicID()) {
211     default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
212     case Intrinsic::lifetime_end:
213       // Never remove dead lifetime_end's, e.g. because it is followed by a
214       // free.
215       return false;
216     case Intrinsic::init_trampoline:
217       // Always safe to remove init_trampoline.
218       return true;
219 
220     case Intrinsic::memset:
221     case Intrinsic::memmove:
222     case Intrinsic::memcpy:
223       // Don't remove volatile memory intrinsics.
224       return !cast<MemIntrinsic>(II)->isVolatile();
225     }
226   }
227 
228   if (auto CS = CallSite(I))
229     return CS.getInstruction()->use_empty();
230 
231   return false;
232 }
233 
234 
235 /// Returns true if the end of this instruction can be safely shortened in
236 /// length.
237 static bool isShortenableAtTheEnd(Instruction *I) {
238   // Don't shorten stores for now
239   if (isa<StoreInst>(I))
240     return false;
241 
242   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
243     switch (II->getIntrinsicID()) {
244       default: return false;
245       case Intrinsic::memset:
246       case Intrinsic::memcpy:
247         // Do shorten memory intrinsics.
248         // FIXME: Add memmove if it's also safe to transform.
249         return true;
250     }
251   }
252 
253   // Don't shorten libcalls calls for now.
254 
255   return false;
256 }
257 
258 /// Returns true if the beginning of this instruction can be safely shortened
259 /// in length.
260 static bool isShortenableAtTheBeginning(Instruction *I) {
261   // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
262   // easily done by offsetting the source address.
263   IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
264   return II && II->getIntrinsicID() == Intrinsic::memset;
265 }
266 
267 /// Return the pointer that is being written to.
268 static Value *getStoredPointerOperand(Instruction *I) {
269   if (StoreInst *SI = dyn_cast<StoreInst>(I))
270     return SI->getPointerOperand();
271   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
272     return MI->getDest();
273 
274   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
275     switch (II->getIntrinsicID()) {
276     default: llvm_unreachable("Unexpected intrinsic!");
277     case Intrinsic::init_trampoline:
278       return II->getArgOperand(0);
279     }
280   }
281 
282   CallSite CS(I);
283   // All the supported functions so far happen to have dest as their first
284   // argument.
285   return CS.getArgument(0);
286 }
287 
288 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
289                                const TargetLibraryInfo &TLI) {
290   uint64_t Size;
291   if (getObjectSize(V, Size, DL, &TLI))
292     return Size;
293   return MemoryLocation::UnknownSize;
294 }
295 
296 namespace {
297 enum OverwriteResult {
298   OW_Begin,
299   OW_Complete,
300   OW_End,
301   OW_PartialEarlierWithFullLater,
302   OW_Unknown
303 };
304 }
305 
306 /// Return 'OW_Complete' if a store to the 'Later' location completely
307 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the
308 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the
309 /// beginning of the 'Earlier' location is overwritten by 'Later'.
310 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was
311 /// overwritten by a latter (smaller) store which doesn't write outside the big
312 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
313 static OverwriteResult isOverwrite(const MemoryLocation &Later,
314                                    const MemoryLocation &Earlier,
315                                    const DataLayout &DL,
316                                    const TargetLibraryInfo &TLI,
317                                    int64_t &EarlierOff, int64_t &LaterOff,
318                                    Instruction *DepWrite,
319                                    InstOverlapIntervalsTy &IOL) {
320   // If we don't know the sizes of either access, then we can't do a comparison.
321   if (Later.Size == MemoryLocation::UnknownSize ||
322       Earlier.Size == MemoryLocation::UnknownSize)
323     return OW_Unknown;
324 
325   const Value *P1 = Earlier.Ptr->stripPointerCasts();
326   const Value *P2 = Later.Ptr->stripPointerCasts();
327 
328   // If the start pointers are the same, we just have to compare sizes to see if
329   // the later store was larger than the earlier store.
330   if (P1 == P2) {
331     // Make sure that the Later size is >= the Earlier size.
332     if (Later.Size >= Earlier.Size)
333       return OW_Complete;
334   }
335 
336   // Check to see if the later store is to the entire object (either a global,
337   // an alloca, or a byval/inalloca argument).  If so, then it clearly
338   // overwrites any other store to the same object.
339   const Value *UO1 = GetUnderlyingObject(P1, DL),
340               *UO2 = GetUnderlyingObject(P2, DL);
341 
342   // If we can't resolve the same pointers to the same object, then we can't
343   // analyze them at all.
344   if (UO1 != UO2)
345     return OW_Unknown;
346 
347   // If the "Later" store is to a recognizable object, get its size.
348   uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
349   if (ObjectSize != MemoryLocation::UnknownSize)
350     if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
351       return OW_Complete;
352 
353   // Okay, we have stores to two completely different pointers.  Try to
354   // decompose the pointer into a "base + constant_offset" form.  If the base
355   // pointers are equal, then we can reason about the two stores.
356   EarlierOff = 0;
357   LaterOff = 0;
358   const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
359   const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
360 
361   // If the base pointers still differ, we have two completely different stores.
362   if (BP1 != BP2)
363     return OW_Unknown;
364 
365   // The later store completely overlaps the earlier store if:
366   //
367   // 1. Both start at the same offset and the later one's size is greater than
368   //    or equal to the earlier one's, or
369   //
370   //      |--earlier--|
371   //      |--   later   --|
372   //
373   // 2. The earlier store has an offset greater than the later offset, but which
374   //    still lies completely within the later store.
375   //
376   //        |--earlier--|
377   //    |-----  later  ------|
378   //
379   // We have to be careful here as *Off is signed while *.Size is unsigned.
380   if (EarlierOff >= LaterOff &&
381       Later.Size >= Earlier.Size &&
382       uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
383     return OW_Complete;
384 
385   // We may now overlap, although the overlap is not complete. There might also
386   // be other incomplete overlaps, and together, they might cover the complete
387   // earlier write.
388   // Note: The correctness of this logic depends on the fact that this function
389   // is not even called providing DepWrite when there are any intervening reads.
390   if (EnablePartialOverwriteTracking &&
391       LaterOff < int64_t(EarlierOff + Earlier.Size) &&
392       int64_t(LaterOff + Later.Size) >= EarlierOff) {
393 
394     // Insert our part of the overlap into the map.
395     auto &IM = IOL[DepWrite];
396     DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff << ", " <<
397                     int64_t(EarlierOff + Earlier.Size) << ") Later [" <<
398                     LaterOff << ", " << int64_t(LaterOff + Later.Size) << ")\n");
399 
400     // Make sure that we only insert non-overlapping intervals and combine
401     // adjacent intervals. The intervals are stored in the map with the ending
402     // offset as the key (in the half-open sense) and the starting offset as
403     // the value.
404     int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + Later.Size;
405 
406     // Find any intervals ending at, or after, LaterIntStart which start
407     // before LaterIntEnd.
408     auto ILI = IM.lower_bound(LaterIntStart);
409     if (ILI != IM.end() && ILI->second <= LaterIntEnd) {
410       // This existing interval is overlapped with the current store somewhere
411       // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing
412       // intervals and adjusting our start and end.
413       LaterIntStart = std::min(LaterIntStart, ILI->second);
414       LaterIntEnd = std::max(LaterIntEnd, ILI->first);
415       ILI = IM.erase(ILI);
416 
417       // Continue erasing and adjusting our end in case other previous
418       // intervals are also overlapped with the current store.
419       //
420       // |--- ealier 1 ---|  |--- ealier 2 ---|
421       //     |------- later---------|
422       //
423       while (ILI != IM.end() && ILI->second <= LaterIntEnd) {
424         assert(ILI->second > LaterIntStart && "Unexpected interval");
425         LaterIntEnd = std::max(LaterIntEnd, ILI->first);
426         ILI = IM.erase(ILI);
427       }
428     }
429 
430     IM[LaterIntEnd] = LaterIntStart;
431 
432     ILI = IM.begin();
433     if (ILI->second <= EarlierOff &&
434         ILI->first >= int64_t(EarlierOff + Earlier.Size)) {
435       DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" <<
436                       EarlierOff << ", " <<
437                       int64_t(EarlierOff + Earlier.Size) <<
438                       ") Composite Later [" <<
439                       ILI->second << ", " << ILI->first << ")\n");
440       ++NumCompletePartials;
441       return OW_Complete;
442     }
443   }
444 
445   // Check for an earlier store which writes to all the memory locations that
446   // the later store writes to.
447   if (EnablePartialStoreMerging && LaterOff >= EarlierOff &&
448       int64_t(EarlierOff + Earlier.Size) > LaterOff &&
449       uint64_t(LaterOff - EarlierOff) + Later.Size <= Earlier.Size) {
450     DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" << EarlierOff
451                  << ", " << int64_t(EarlierOff + Earlier.Size)
452                  << ") by a later store [" << LaterOff << ", "
453                  << int64_t(LaterOff + Later.Size) << ")\n");
454     // TODO: Maybe come up with a better name?
455     return OW_PartialEarlierWithFullLater;
456   }
457 
458   // Another interesting case is if the later store overwrites the end of the
459   // earlier store.
460   //
461   //      |--earlier--|
462   //                |--   later   --|
463   //
464   // In this case we may want to trim the size of earlier to avoid generating
465   // writes to addresses which will definitely be overwritten later
466   if (!EnablePartialOverwriteTracking &&
467       (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + Earlier.Size) &&
468        int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size)))
469     return OW_End;
470 
471   // Finally, we also need to check if the later store overwrites the beginning
472   // of the earlier store.
473   //
474   //                |--earlier--|
475   //      |--   later   --|
476   //
477   // In this case we may want to move the destination address and trim the size
478   // of earlier to avoid generating writes to addresses which will definitely
479   // be overwritten later.
480   if (!EnablePartialOverwriteTracking &&
481       (LaterOff <= EarlierOff && int64_t(LaterOff + Later.Size) > EarlierOff)) {
482     assert(int64_t(LaterOff + Later.Size) <
483                int64_t(EarlierOff + Earlier.Size) &&
484            "Expect to be handled as OW_Complete");
485     return OW_Begin;
486   }
487   // Otherwise, they don't completely overlap.
488   return OW_Unknown;
489 }
490 
491 /// If 'Inst' might be a self read (i.e. a noop copy of a
492 /// memory region into an identical pointer) then it doesn't actually make its
493 /// input dead in the traditional sense.  Consider this case:
494 ///
495 ///   memcpy(A <- B)
496 ///   memcpy(A <- A)
497 ///
498 /// In this case, the second store to A does not make the first store to A dead.
499 /// The usual situation isn't an explicit A<-A store like this (which can be
500 /// trivially removed) but a case where two pointers may alias.
501 ///
502 /// This function detects when it is unsafe to remove a dependent instruction
503 /// because the DSE inducing instruction may be a self-read.
504 static bool isPossibleSelfRead(Instruction *Inst,
505                                const MemoryLocation &InstStoreLoc,
506                                Instruction *DepWrite,
507                                const TargetLibraryInfo &TLI,
508                                AliasAnalysis &AA) {
509   // Self reads can only happen for instructions that read memory.  Get the
510   // location read.
511   MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
512   if (!InstReadLoc.Ptr) return false;  // Not a reading instruction.
513 
514   // If the read and written loc obviously don't alias, it isn't a read.
515   if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
516 
517   // Okay, 'Inst' may copy over itself.  However, we can still remove a the
518   // DepWrite instruction if we can prove that it reads from the same location
519   // as Inst.  This handles useful cases like:
520   //   memcpy(A <- B)
521   //   memcpy(A <- B)
522   // Here we don't know if A/B may alias, but we do know that B/B are must
523   // aliases, so removing the first memcpy is safe (assuming it writes <= #
524   // bytes as the second one.
525   MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
526 
527   if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
528     return false;
529 
530   // If DepWrite doesn't read memory or if we can't prove it is a must alias,
531   // then it can't be considered dead.
532   return true;
533 }
534 
535 /// Returns true if the memory which is accessed by the second instruction is not
536 /// modified between the first and the second instruction.
537 /// Precondition: Second instruction must be dominated by the first
538 /// instruction.
539 static bool memoryIsNotModifiedBetween(Instruction *FirstI,
540                                        Instruction *SecondI,
541                                        AliasAnalysis *AA) {
542   SmallVector<BasicBlock *, 16> WorkList;
543   SmallPtrSet<BasicBlock *, 8> Visited;
544   BasicBlock::iterator FirstBBI(FirstI);
545   ++FirstBBI;
546   BasicBlock::iterator SecondBBI(SecondI);
547   BasicBlock *FirstBB = FirstI->getParent();
548   BasicBlock *SecondBB = SecondI->getParent();
549   MemoryLocation MemLoc = MemoryLocation::get(SecondI);
550 
551   // Start checking the store-block.
552   WorkList.push_back(SecondBB);
553   bool isFirstBlock = true;
554 
555   // Check all blocks going backward until we reach the load-block.
556   while (!WorkList.empty()) {
557     BasicBlock *B = WorkList.pop_back_val();
558 
559     // Ignore instructions before LI if this is the FirstBB.
560     BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
561 
562     BasicBlock::iterator EI;
563     if (isFirstBlock) {
564       // Ignore instructions after SI if this is the first visit of SecondBB.
565       assert(B == SecondBB && "first block is not the store block");
566       EI = SecondBBI;
567       isFirstBlock = false;
568     } else {
569       // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
570       // In this case we also have to look at instructions after SI.
571       EI = B->end();
572     }
573     for (; BI != EI; ++BI) {
574       Instruction *I = &*BI;
575       if (I->mayWriteToMemory() && I != SecondI) {
576         auto Res = AA->getModRefInfo(I, MemLoc);
577         if (Res & MRI_Mod)
578           return false;
579       }
580     }
581     if (B != FirstBB) {
582       assert(B != &FirstBB->getParent()->getEntryBlock() &&
583           "Should not hit the entry block because SI must be dominated by LI");
584       for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
585         if (!Visited.insert(*PredI).second)
586           continue;
587         WorkList.push_back(*PredI);
588       }
589     }
590   }
591   return true;
592 }
593 
594 /// Find all blocks that will unconditionally lead to the block BB and append
595 /// them to F.
596 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
597                                    BasicBlock *BB, DominatorTree *DT) {
598   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
599     BasicBlock *Pred = *I;
600     if (Pred == BB) continue;
601     TerminatorInst *PredTI = Pred->getTerminator();
602     if (PredTI->getNumSuccessors() != 1)
603       continue;
604 
605     if (DT->isReachableFromEntry(Pred))
606       Blocks.push_back(Pred);
607   }
608 }
609 
610 /// Handle frees of entire structures whose dependency is a store
611 /// to a field of that structure.
612 static bool handleFree(CallInst *F, AliasAnalysis *AA,
613                        MemoryDependenceResults *MD, DominatorTree *DT,
614                        const TargetLibraryInfo *TLI,
615                        InstOverlapIntervalsTy &IOL,
616                        DenseMap<Instruction*, size_t> *InstrOrdering) {
617   bool MadeChange = false;
618 
619   MemoryLocation Loc = MemoryLocation(F->getOperand(0));
620   SmallVector<BasicBlock *, 16> Blocks;
621   Blocks.push_back(F->getParent());
622   const DataLayout &DL = F->getModule()->getDataLayout();
623 
624   while (!Blocks.empty()) {
625     BasicBlock *BB = Blocks.pop_back_val();
626     Instruction *InstPt = BB->getTerminator();
627     if (BB == F->getParent()) InstPt = F;
628 
629     MemDepResult Dep =
630         MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
631     while (Dep.isDef() || Dep.isClobber()) {
632       Instruction *Dependency = Dep.getInst();
633       if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency))
634         break;
635 
636       Value *DepPointer =
637           GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
638 
639       // Check for aliasing.
640       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
641         break;
642 
643       DEBUG(dbgs() << "DSE: Dead Store to soon to be freed memory:\n  DEAD: "
644                    << *Dependency << '\n');
645 
646       // DCE instructions only used to calculate that store.
647       BasicBlock::iterator BBI(Dependency);
648       deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, InstrOrdering);
649       ++NumFastStores;
650       MadeChange = true;
651 
652       // Inst's old Dependency is now deleted. Compute the next dependency,
653       // which may also be dead, as in
654       //    s[0] = 0;
655       //    s[1] = 0; // This has just been deleted.
656       //    free(s);
657       Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB);
658     }
659 
660     if (Dep.isNonLocal())
661       findUnconditionalPreds(Blocks, BB, DT);
662   }
663 
664   return MadeChange;
665 }
666 
667 /// Check to see if the specified location may alias any of the stack objects in
668 /// the DeadStackObjects set. If so, they become live because the location is
669 /// being loaded.
670 static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
671                                   SmallSetVector<Value *, 16> &DeadStackObjects,
672                                   const DataLayout &DL, AliasAnalysis *AA,
673                                   const TargetLibraryInfo *TLI) {
674   const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
675 
676   // A constant can't be in the dead pointer set.
677   if (isa<Constant>(UnderlyingPointer))
678     return;
679 
680   // If the kill pointer can be easily reduced to an alloca, don't bother doing
681   // extraneous AA queries.
682   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
683     DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
684     return;
685   }
686 
687   // Remove objects that could alias LoadedLoc.
688   DeadStackObjects.remove_if([&](Value *I) {
689     // See if the loaded location could alias the stack location.
690     MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
691     return !AA->isNoAlias(StackLoc, LoadedLoc);
692   });
693 }
694 
695 /// Remove dead stores to stack-allocated locations in the function end block.
696 /// Ex:
697 /// %A = alloca i32
698 /// ...
699 /// store i32 1, i32* %A
700 /// ret void
701 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
702                              MemoryDependenceResults *MD,
703                              const TargetLibraryInfo *TLI,
704                              InstOverlapIntervalsTy &IOL,
705                              DenseMap<Instruction*, size_t> *InstrOrdering) {
706   bool MadeChange = false;
707 
708   // Keep track of all of the stack objects that are dead at the end of the
709   // function.
710   SmallSetVector<Value*, 16> DeadStackObjects;
711 
712   // Find all of the alloca'd pointers in the entry block.
713   BasicBlock &Entry = BB.getParent()->front();
714   for (Instruction &I : Entry) {
715     if (isa<AllocaInst>(&I))
716       DeadStackObjects.insert(&I);
717 
718     // Okay, so these are dead heap objects, but if the pointer never escapes
719     // then it's leaked by this function anyways.
720     else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
721       DeadStackObjects.insert(&I);
722   }
723 
724   // Treat byval or inalloca arguments the same, stores to them are dead at the
725   // end of the function.
726   for (Argument &AI : BB.getParent()->args())
727     if (AI.hasByValOrInAllocaAttr())
728       DeadStackObjects.insert(&AI);
729 
730   const DataLayout &DL = BB.getModule()->getDataLayout();
731 
732   // Scan the basic block backwards
733   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
734     --BBI;
735 
736     // If we find a store, check to see if it points into a dead stack value.
737     if (hasMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
738       // See through pointer-to-pointer bitcasts
739       SmallVector<Value *, 4> Pointers;
740       GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL);
741 
742       // Stores to stack values are valid candidates for removal.
743       bool AllDead = true;
744       for (Value *Pointer : Pointers)
745         if (!DeadStackObjects.count(Pointer)) {
746           AllDead = false;
747           break;
748         }
749 
750       if (AllDead) {
751         Instruction *Dead = &*BBI;
752 
753         DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
754                      << *Dead << "\n  Objects: ";
755               for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
756                    E = Pointers.end(); I != E; ++I) {
757                 dbgs() << **I;
758                 if (std::next(I) != E)
759                   dbgs() << ", ";
760               }
761               dbgs() << '\n');
762 
763         // DCE instructions only used to calculate that store.
764         deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, InstrOrdering, &DeadStackObjects);
765         ++NumFastStores;
766         MadeChange = true;
767         continue;
768       }
769     }
770 
771     // Remove any dead non-memory-mutating instructions.
772     if (isInstructionTriviallyDead(&*BBI, TLI)) {
773       DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n  DEAD: "
774                    << *&*BBI << '\n');
775       deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, InstrOrdering, &DeadStackObjects);
776       ++NumFastOther;
777       MadeChange = true;
778       continue;
779     }
780 
781     if (isa<AllocaInst>(BBI)) {
782       // Remove allocas from the list of dead stack objects; there can't be
783       // any references before the definition.
784       DeadStackObjects.remove(&*BBI);
785       continue;
786     }
787 
788     if (auto CS = CallSite(&*BBI)) {
789       // Remove allocation function calls from the list of dead stack objects;
790       // there can't be any references before the definition.
791       if (isAllocLikeFn(&*BBI, TLI))
792         DeadStackObjects.remove(&*BBI);
793 
794       // If this call does not access memory, it can't be loading any of our
795       // pointers.
796       if (AA->doesNotAccessMemory(CS))
797         continue;
798 
799       // If the call might load from any of our allocas, then any store above
800       // the call is live.
801       DeadStackObjects.remove_if([&](Value *I) {
802         // See if the call site touches the value.
803         ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI));
804 
805         return A == MRI_ModRef || A == MRI_Ref;
806       });
807 
808       // If all of the allocas were clobbered by the call then we're not going
809       // to find anything else to process.
810       if (DeadStackObjects.empty())
811         break;
812 
813       continue;
814     }
815 
816     // We can remove the dead stores, irrespective of the fence and its ordering
817     // (release/acquire/seq_cst). Fences only constraints the ordering of
818     // already visible stores, it does not make a store visible to other
819     // threads. So, skipping over a fence does not change a store from being
820     // dead.
821     if (isa<FenceInst>(*BBI))
822       continue;
823 
824     MemoryLocation LoadedLoc;
825 
826     // If we encounter a use of the pointer, it is no longer considered dead
827     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
828       if (!L->isUnordered()) // Be conservative with atomic/volatile load
829         break;
830       LoadedLoc = MemoryLocation::get(L);
831     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
832       LoadedLoc = MemoryLocation::get(V);
833     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
834       LoadedLoc = MemoryLocation::getForSource(MTI);
835     } else if (!BBI->mayReadFromMemory()) {
836       // Instruction doesn't read memory.  Note that stores that weren't removed
837       // above will hit this case.
838       continue;
839     } else {
840       // Unknown inst; assume it clobbers everything.
841       break;
842     }
843 
844     // Remove any allocas from the DeadPointer set that are loaded, as this
845     // makes any stores above the access live.
846     removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI);
847 
848     // If all of the allocas were clobbered by the access then we're not going
849     // to find anything else to process.
850     if (DeadStackObjects.empty())
851       break;
852   }
853 
854   return MadeChange;
855 }
856 
857 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset,
858                          int64_t &EarlierSize, int64_t LaterOffset,
859                          int64_t LaterSize, bool IsOverwriteEnd) {
860   // TODO: base this on the target vector size so that if the earlier
861   // store was too small to get vector writes anyway then its likely
862   // a good idea to shorten it
863   // Power of 2 vector writes are probably always a bad idea to optimize
864   // as any store/memset/memcpy is likely using vector instructions so
865   // shortening it to not vector size is likely to be slower
866   MemIntrinsic *EarlierIntrinsic = cast<MemIntrinsic>(EarlierWrite);
867   unsigned EarlierWriteAlign = EarlierIntrinsic->getAlignment();
868   if (!IsOverwriteEnd)
869     LaterOffset = int64_t(LaterOffset + LaterSize);
870 
871   if (!(llvm::isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) &&
872       !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0))
873     return false;
874 
875   DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW "
876                << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *EarlierWrite
877                << "\n  KILLER (offset " << LaterOffset << ", " << EarlierSize
878                << ")\n");
879 
880   int64_t NewLength = IsOverwriteEnd
881                           ? LaterOffset - EarlierOffset
882                           : EarlierSize - (LaterOffset - EarlierOffset);
883 
884   Value *EarlierWriteLength = EarlierIntrinsic->getLength();
885   Value *TrimmedLength =
886       ConstantInt::get(EarlierWriteLength->getType(), NewLength);
887   EarlierIntrinsic->setLength(TrimmedLength);
888 
889   EarlierSize = NewLength;
890   if (!IsOverwriteEnd) {
891     int64_t OffsetMoved = (LaterOffset - EarlierOffset);
892     Value *Indices[1] = {
893         ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)};
894     GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
895         EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite);
896     EarlierIntrinsic->setDest(NewDestGEP);
897     EarlierOffset = EarlierOffset + OffsetMoved;
898   }
899   return true;
900 }
901 
902 static bool tryToShortenEnd(Instruction *EarlierWrite,
903                             OverlapIntervalsTy &IntervalMap,
904                             int64_t &EarlierStart, int64_t &EarlierSize) {
905   if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite))
906     return false;
907 
908   OverlapIntervalsTy::iterator OII = --IntervalMap.end();
909   int64_t LaterStart = OII->second;
910   int64_t LaterSize = OII->first - LaterStart;
911 
912   if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize &&
913       LaterStart + LaterSize >= EarlierStart + EarlierSize) {
914     if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
915                      LaterSize, true)) {
916       IntervalMap.erase(OII);
917       return true;
918     }
919   }
920   return false;
921 }
922 
923 static bool tryToShortenBegin(Instruction *EarlierWrite,
924                               OverlapIntervalsTy &IntervalMap,
925                               int64_t &EarlierStart, int64_t &EarlierSize) {
926   if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite))
927     return false;
928 
929   OverlapIntervalsTy::iterator OII = IntervalMap.begin();
930   int64_t LaterStart = OII->second;
931   int64_t LaterSize = OII->first - LaterStart;
932 
933   if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) {
934     assert(LaterStart + LaterSize < EarlierStart + EarlierSize &&
935            "Should have been handled as OW_Complete");
936     if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
937                      LaterSize, false)) {
938       IntervalMap.erase(OII);
939       return true;
940     }
941   }
942   return false;
943 }
944 
945 static bool removePartiallyOverlappedStores(AliasAnalysis *AA,
946                                             const DataLayout &DL,
947                                             InstOverlapIntervalsTy &IOL) {
948   bool Changed = false;
949   for (auto OI : IOL) {
950     Instruction *EarlierWrite = OI.first;
951     MemoryLocation Loc = getLocForWrite(EarlierWrite, *AA);
952     assert(isRemovable(EarlierWrite) && "Expect only removable instruction");
953     assert(Loc.Size != MemoryLocation::UnknownSize && "Unexpected mem loc");
954 
955     const Value *Ptr = Loc.Ptr->stripPointerCasts();
956     int64_t EarlierStart = 0;
957     int64_t EarlierSize = int64_t(Loc.Size);
958     GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL);
959     OverlapIntervalsTy &IntervalMap = OI.second;
960     Changed |=
961         tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
962     if (IntervalMap.empty())
963       continue;
964     Changed |=
965         tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
966   }
967   return Changed;
968 }
969 
970 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI,
971                                AliasAnalysis *AA, MemoryDependenceResults *MD,
972                                const DataLayout &DL,
973                                const TargetLibraryInfo *TLI,
974                                InstOverlapIntervalsTy &IOL,
975                                DenseMap<Instruction*, size_t> *InstrOrdering) {
976   // Must be a store instruction.
977   StoreInst *SI = dyn_cast<StoreInst>(Inst);
978   if (!SI)
979     return false;
980 
981   // If we're storing the same value back to a pointer that we just loaded from,
982   // then the store can be removed.
983   if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
984     if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
985         isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) {
986 
987       DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n  LOAD: "
988                    << *DepLoad << "\n  STORE: " << *SI << '\n');
989 
990       deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, InstrOrdering);
991       ++NumRedundantStores;
992       return true;
993     }
994   }
995 
996   // Remove null stores into the calloc'ed objects
997   Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
998   if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) {
999     Instruction *UnderlyingPointer =
1000         dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL));
1001 
1002     if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
1003         memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) {
1004       DEBUG(
1005           dbgs() << "DSE: Remove null store to the calloc'ed object:\n  DEAD: "
1006                  << *Inst << "\n  OBJECT: " << *UnderlyingPointer << '\n');
1007 
1008       deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, InstrOrdering);
1009       ++NumRedundantStores;
1010       return true;
1011     }
1012   }
1013   return false;
1014 }
1015 
1016 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
1017                                 MemoryDependenceResults *MD, DominatorTree *DT,
1018                                 const TargetLibraryInfo *TLI) {
1019   const DataLayout &DL = BB.getModule()->getDataLayout();
1020   bool MadeChange = false;
1021 
1022   // FIXME: Maybe change this to use some abstraction like OrderedBasicBlock?
1023   // The current OrderedBasicBlock can't deal with mutation at the moment.
1024   size_t LastThrowingInstIndex = 0;
1025   DenseMap<Instruction*, size_t> InstrOrdering;
1026   size_t InstrIndex = 1;
1027 
1028   // A map of interval maps representing partially-overwritten value parts.
1029   InstOverlapIntervalsTy IOL;
1030 
1031   // Do a top-down walk on the BB.
1032   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
1033     // Handle 'free' calls specially.
1034     if (CallInst *F = isFreeCall(&*BBI, TLI)) {
1035       MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, &InstrOrdering);
1036       // Increment BBI after handleFree has potentially deleted instructions.
1037       // This ensures we maintain a valid iterator.
1038       ++BBI;
1039       continue;
1040     }
1041 
1042     Instruction *Inst = &*BBI++;
1043 
1044     size_t CurInstNumber = InstrIndex++;
1045     InstrOrdering.insert(std::make_pair(Inst, CurInstNumber));
1046     if (Inst->mayThrow()) {
1047       LastThrowingInstIndex = CurInstNumber;
1048       continue;
1049     }
1050 
1051     // Check to see if Inst writes to memory.  If not, continue.
1052     if (!hasMemoryWrite(Inst, *TLI))
1053       continue;
1054 
1055     // eliminateNoopStore will update in iterator, if necessary.
1056     if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, &InstrOrdering)) {
1057       MadeChange = true;
1058       continue;
1059     }
1060 
1061     // If we find something that writes memory, get its memory dependence.
1062     MemDepResult InstDep = MD->getDependency(Inst);
1063 
1064     // Ignore any store where we can't find a local dependence.
1065     // FIXME: cross-block DSE would be fun. :)
1066     if (!InstDep.isDef() && !InstDep.isClobber())
1067       continue;
1068 
1069     // Figure out what location is being stored to.
1070     MemoryLocation Loc = getLocForWrite(Inst, *AA);
1071 
1072     // If we didn't get a useful location, fail.
1073     if (!Loc.Ptr)
1074       continue;
1075 
1076     // Loop until we find a store we can eliminate or a load that
1077     // invalidates the analysis. Without an upper bound on the number of
1078     // instructions examined, this analysis can become very time-consuming.
1079     // However, the potential gain diminishes as we process more instructions
1080     // without eliminating any of them. Therefore, we limit the number of
1081     // instructions we look at.
1082     auto Limit = MD->getDefaultBlockScanLimit();
1083     while (InstDep.isDef() || InstDep.isClobber()) {
1084       // Get the memory clobbered by the instruction we depend on.  MemDep will
1085       // skip any instructions that 'Loc' clearly doesn't interact with.  If we
1086       // end up depending on a may- or must-aliased load, then we can't optimize
1087       // away the store and we bail out.  However, if we depend on something
1088       // that overwrites the memory location we *can* potentially optimize it.
1089       //
1090       // Find out what memory location the dependent instruction stores.
1091       Instruction *DepWrite = InstDep.getInst();
1092       MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA);
1093       // If we didn't get a useful location, or if it isn't a size, bail out.
1094       if (!DepLoc.Ptr)
1095         break;
1096 
1097       // Make sure we don't look past a call which might throw. This is an
1098       // issue because MemoryDependenceAnalysis works in the wrong direction:
1099       // it finds instructions which dominate the current instruction, rather than
1100       // instructions which are post-dominated by the current instruction.
1101       //
1102       // If the underlying object is a non-escaping memory allocation, any store
1103       // to it is dead along the unwind edge. Otherwise, we need to preserve
1104       // the store.
1105       size_t DepIndex = InstrOrdering.lookup(DepWrite);
1106       assert(DepIndex && "Unexpected instruction");
1107       if (DepIndex <= LastThrowingInstIndex) {
1108         const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL);
1109         bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying);
1110         if (!IsStoreDeadOnUnwind) {
1111             // We're looking for a call to an allocation function
1112             // where the allocation doesn't escape before the last
1113             // throwing instruction; PointerMayBeCaptured
1114             // reasonably fast approximation.
1115             IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) &&
1116                 !PointerMayBeCaptured(Underlying, false, true);
1117         }
1118         if (!IsStoreDeadOnUnwind)
1119           break;
1120       }
1121 
1122       // If we find a write that is a) removable (i.e., non-volatile), b) is
1123       // completely obliterated by the store to 'Loc', and c) which we know that
1124       // 'Inst' doesn't load from, then we can remove it.
1125       // Also try to merge two stores if a later one only touches memory written
1126       // to by the earlier one.
1127       if (isRemovable(DepWrite) &&
1128           !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
1129         int64_t InstWriteOffset, DepWriteOffset;
1130         OverwriteResult OR =
1131             isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset,
1132                         DepWrite, IOL);
1133         if (OR == OW_Complete) {
1134           DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: "
1135                 << *DepWrite << "\n  KILLER: " << *Inst << '\n');
1136 
1137           // Delete the store and now-dead instructions that feed it.
1138           deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, &InstrOrdering);
1139           ++NumFastStores;
1140           MadeChange = true;
1141 
1142           // We erased DepWrite; start over.
1143           InstDep = MD->getDependency(Inst);
1144           continue;
1145         } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) ||
1146                    ((OR == OW_Begin &&
1147                      isShortenableAtTheBeginning(DepWrite)))) {
1148           assert(!EnablePartialOverwriteTracking && "Do not expect to perform "
1149                                                     "when partial-overwrite "
1150                                                     "tracking is enabled");
1151           int64_t EarlierSize = DepLoc.Size;
1152           int64_t LaterSize = Loc.Size;
1153           bool IsOverwriteEnd = (OR == OW_End);
1154           MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize,
1155                                     InstWriteOffset, LaterSize, IsOverwriteEnd);
1156         } else if (EnablePartialStoreMerging &&
1157                    OR == OW_PartialEarlierWithFullLater) {
1158           auto *Earlier = dyn_cast<StoreInst>(DepWrite);
1159           auto *Later = dyn_cast<StoreInst>(Inst);
1160           if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) &&
1161               Later && isa<ConstantInt>(Later->getValueOperand())) {
1162             // If the store we find is:
1163             //   a) partially overwritten by the store to 'Loc'
1164             //   b) the later store is fully contained in the earlier one and
1165             //   c) they both have a constant value
1166             // Merge the two stores, replacing the earlier store's value with a
1167             // merge of both values.
1168             // TODO: Deal with other constant types (vectors, etc), and probably
1169             // some mem intrinsics (if needed)
1170 
1171             APInt EarlierValue =
1172                 cast<ConstantInt>(Earlier->getValueOperand())->getValue();
1173             APInt LaterValue =
1174                 cast<ConstantInt>(Later->getValueOperand())->getValue();
1175             unsigned LaterBits = LaterValue.getBitWidth();
1176             assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth());
1177             LaterValue = LaterValue.zext(EarlierValue.getBitWidth());
1178 
1179             // Offset of the smaller store inside the larger store
1180             unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8;
1181             unsigned LShiftAmount =
1182                 DL.isBigEndian()
1183                     ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits
1184                     : BitOffsetDiff;
1185             APInt Mask =
1186                 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount,
1187                                   LShiftAmount + LaterBits);
1188             // Clear the bits we'll be replacing, then OR with the smaller
1189             // store, shifted appropriately.
1190             APInt Merged =
1191                 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount);
1192             DEBUG(dbgs() << "DSE: Merge Stores:\n  Earlier: " << *DepWrite
1193                          << "\n  Later: " << *Inst
1194                          << "\n  Merged Value: " << Merged << '\n');
1195 
1196             auto *SI = new StoreInst(
1197                 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged),
1198                 Earlier->getPointerOperand(), false, Earlier->getAlignment(),
1199                 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite);
1200 
1201             unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa,
1202                                    LLVMContext::MD_alias_scope,
1203                                    LLVMContext::MD_noalias,
1204                                    LLVMContext::MD_nontemporal};
1205             SI->copyMetadata(*DepWrite, MDToKeep);
1206             ++NumModifiedStores;
1207 
1208             // Remove earlier, wider, store
1209             size_t Idx = InstrOrdering.lookup(DepWrite);
1210             InstrOrdering.erase(DepWrite);
1211             InstrOrdering.insert(std::make_pair(SI, Idx));
1212 
1213             // Delete the old stores and now-dead instructions that feed them.
1214             deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, &InstrOrdering);
1215             deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1216                                   &InstrOrdering);
1217             MadeChange = true;
1218 
1219             // We erased DepWrite and Inst (Loc); start over.
1220             break;
1221           }
1222         }
1223       }
1224 
1225       // If this is a may-aliased store that is clobbering the store value, we
1226       // can keep searching past it for another must-aliased pointer that stores
1227       // to the same location.  For example, in:
1228       //   store -> P
1229       //   store -> Q
1230       //   store -> P
1231       // we can remove the first store to P even though we don't know if P and Q
1232       // alias.
1233       if (DepWrite == &BB.front()) break;
1234 
1235       // Can't look past this instruction if it might read 'Loc'.
1236       if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref)
1237         break;
1238 
1239       InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false,
1240                                              DepWrite->getIterator(), &BB,
1241                                              /*QueryInst=*/ nullptr, &Limit);
1242     }
1243   }
1244 
1245   if (EnablePartialOverwriteTracking)
1246     MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL);
1247 
1248   // If this block ends in a return, unwind, or unreachable, all allocas are
1249   // dead at its end, which means stores to them are also dead.
1250   if (BB.getTerminator()->getNumSuccessors() == 0)
1251     MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, &InstrOrdering);
1252 
1253   return MadeChange;
1254 }
1255 
1256 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
1257                                 MemoryDependenceResults *MD, DominatorTree *DT,
1258                                 const TargetLibraryInfo *TLI) {
1259   bool MadeChange = false;
1260   for (BasicBlock &BB : F)
1261     // Only check non-dead blocks.  Dead blocks may have strange pointer
1262     // cycles that will confuse alias analysis.
1263     if (DT->isReachableFromEntry(&BB))
1264       MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
1265 
1266   return MadeChange;
1267 }
1268 
1269 //===----------------------------------------------------------------------===//
1270 // DSE Pass
1271 //===----------------------------------------------------------------------===//
1272 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
1273   AliasAnalysis *AA = &AM.getResult<AAManager>(F);
1274   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1275   MemoryDependenceResults *MD = &AM.getResult<MemoryDependenceAnalysis>(F);
1276   const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1277 
1278   if (!eliminateDeadStores(F, AA, MD, DT, TLI))
1279     return PreservedAnalyses::all();
1280 
1281   PreservedAnalyses PA;
1282   PA.preserveSet<CFGAnalyses>();
1283   PA.preserve<GlobalsAA>();
1284   PA.preserve<MemoryDependenceAnalysis>();
1285   return PA;
1286 }
1287 
1288 namespace {
1289 /// A legacy pass for the legacy pass manager that wraps \c DSEPass.
1290 class DSELegacyPass : public FunctionPass {
1291 public:
1292   DSELegacyPass() : FunctionPass(ID) {
1293     initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
1294   }
1295 
1296   bool runOnFunction(Function &F) override {
1297     if (skipFunction(F))
1298       return false;
1299 
1300     DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1301     AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1302     MemoryDependenceResults *MD =
1303         &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1304     const TargetLibraryInfo *TLI =
1305         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1306 
1307     return eliminateDeadStores(F, AA, MD, DT, TLI);
1308   }
1309 
1310   void getAnalysisUsage(AnalysisUsage &AU) const override {
1311     AU.setPreservesCFG();
1312     AU.addRequired<DominatorTreeWrapperPass>();
1313     AU.addRequired<AAResultsWrapperPass>();
1314     AU.addRequired<MemoryDependenceWrapperPass>();
1315     AU.addRequired<TargetLibraryInfoWrapperPass>();
1316     AU.addPreserved<DominatorTreeWrapperPass>();
1317     AU.addPreserved<GlobalsAAWrapperPass>();
1318     AU.addPreserved<MemoryDependenceWrapperPass>();
1319   }
1320 
1321   static char ID; // Pass identification, replacement for typeid
1322 };
1323 } // end anonymous namespace
1324 
1325 char DSELegacyPass::ID = 0;
1326 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
1327                       false)
1328 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1329 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1330 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1331 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1332 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1333 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
1334                     false)
1335 
1336 FunctionPass *llvm::createDeadStoreEliminationPass() {
1337   return new DSELegacyPass();
1338 }
1339