1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a trivial dead store elimination that only considers
10 // basic-block local redundant stores.
11 //
12 // FIXME: This should eventually be extended to be a post-dominator tree
13 // traversal.  Doing so would be pretty trivial.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/GlobalsModRef.h"
30 #include "llvm/Analysis/MemoryBuiltins.h"
31 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/MemorySSA.h"
34 #include "llvm/Analysis/MemorySSAUpdater.h"
35 #include "llvm/Analysis/PostDominators.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/IR/Argument.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/InstIterator.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/PassManager.h"
54 #include "llvm/IR/PatternMatch.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/InitializePasses.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/DebugCounter.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Transforms/Scalar.h"
66 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
67 #include "llvm/Transforms/Utils/Local.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <iterator>
73 #include <map>
74 #include <utility>
75 
76 using namespace llvm;
77 using namespace PatternMatch;
78 
79 #define DEBUG_TYPE "dse"
80 
81 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE");
82 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
83 STATISTIC(NumFastStores, "Number of stores deleted");
84 STATISTIC(NumFastOther, "Number of other instrs removed");
85 STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
86 STATISTIC(NumModifiedStores, "Number of stores modified");
87 STATISTIC(NumCFGChecks, "Number of stores modified");
88 STATISTIC(NumCFGTries, "Number of stores modified");
89 STATISTIC(NumCFGSuccess, "Number of stores modified");
90 
91 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa",
92               "Controls which MemoryDefs are eliminated.");
93 
94 static cl::opt<bool>
95 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking",
96   cl::init(true), cl::Hidden,
97   cl::desc("Enable partial-overwrite tracking in DSE"));
98 
99 static cl::opt<bool>
100 EnablePartialStoreMerging("enable-dse-partial-store-merging",
101   cl::init(true), cl::Hidden,
102   cl::desc("Enable partial store merging in DSE"));
103 
104 static cl::opt<bool>
105     EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden,
106                     cl::desc("Use the new MemorySSA-backed DSE."));
107 
108 static cl::opt<unsigned>
109     MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden,
110                        cl::desc("The number of memory instructions to scan for "
111                                 "dead store elimination (default = 100)"));
112 
113 static cl::opt<unsigned> MemorySSADefsPerBlockLimit(
114     "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden,
115     cl::desc("The number of MemoryDefs we consider as candidates to eliminated "
116              "other stores per basic block (default = 5000)"));
117 
118 static cl::opt<unsigned> MemorySSAPathCheckLimit(
119     "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden,
120     cl::desc("The maximum number of blocks to check when trying to prove that "
121              "all paths to an exit go through a killing block (default = 50)"));
122 
123 //===----------------------------------------------------------------------===//
124 // Helper functions
125 //===----------------------------------------------------------------------===//
126 using OverlapIntervalsTy = std::map<int64_t, int64_t>;
127 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>;
128 
129 /// Delete this instruction.  Before we do, go through and zero out all the
130 /// operands of this instruction.  If any of them become dead, delete them and
131 /// the computation tree that feeds them.
132 /// If ValueSet is non-null, remove any deleted instructions from it as well.
133 static void
134 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI,
135                       MemoryDependenceResults &MD, const TargetLibraryInfo &TLI,
136                       InstOverlapIntervalsTy &IOL,
137                       MapVector<Instruction *, bool> &ThrowableInst,
138                       SmallSetVector<const Value *, 16> *ValueSet = nullptr) {
139   SmallVector<Instruction*, 32> NowDeadInsts;
140 
141   NowDeadInsts.push_back(I);
142   --NumFastOther;
143 
144   // Keeping the iterator straight is a pain, so we let this routine tell the
145   // caller what the next instruction is after we're done mucking about.
146   BasicBlock::iterator NewIter = *BBI;
147 
148   // Before we touch this instruction, remove it from memdep!
149   do {
150     Instruction *DeadInst = NowDeadInsts.pop_back_val();
151     // Mark the DeadInst as dead in the list of throwable instructions.
152     auto It = ThrowableInst.find(DeadInst);
153     if (It != ThrowableInst.end())
154       ThrowableInst[It->first] = false;
155     ++NumFastOther;
156 
157     // Try to preserve debug information attached to the dead instruction.
158     salvageDebugInfo(*DeadInst);
159     salvageKnowledge(DeadInst);
160 
161     // This instruction is dead, zap it, in stages.  Start by removing it from
162     // MemDep, which needs to know the operands and needs it to be in the
163     // function.
164     MD.removeInstruction(DeadInst);
165 
166     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
167       Value *Op = DeadInst->getOperand(op);
168       DeadInst->setOperand(op, nullptr);
169 
170       // If this operand just became dead, add it to the NowDeadInsts list.
171       if (!Op->use_empty()) continue;
172 
173       if (Instruction *OpI = dyn_cast<Instruction>(Op))
174         if (isInstructionTriviallyDead(OpI, &TLI))
175           NowDeadInsts.push_back(OpI);
176     }
177 
178     if (ValueSet) ValueSet->remove(DeadInst);
179     IOL.erase(DeadInst);
180 
181     if (NewIter == DeadInst->getIterator())
182       NewIter = DeadInst->eraseFromParent();
183     else
184       DeadInst->eraseFromParent();
185   } while (!NowDeadInsts.empty());
186   *BBI = NewIter;
187   // Pop dead entries from back of ThrowableInst till we find an alive entry.
188   while (!ThrowableInst.empty() && !ThrowableInst.back().second)
189     ThrowableInst.pop_back();
190 }
191 
192 /// Does this instruction write some memory?  This only returns true for things
193 /// that we can analyze with other helpers below.
194 static bool hasAnalyzableMemoryWrite(Instruction *I,
195                                      const TargetLibraryInfo &TLI) {
196   if (isa<StoreInst>(I))
197     return true;
198   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
199     switch (II->getIntrinsicID()) {
200     default:
201       return false;
202     case Intrinsic::memset:
203     case Intrinsic::memmove:
204     case Intrinsic::memcpy:
205     case Intrinsic::memcpy_element_unordered_atomic:
206     case Intrinsic::memmove_element_unordered_atomic:
207     case Intrinsic::memset_element_unordered_atomic:
208     case Intrinsic::init_trampoline:
209     case Intrinsic::lifetime_end:
210       return true;
211     }
212   }
213   if (auto *CB = dyn_cast<CallBase>(I)) {
214     LibFunc LF;
215     if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) {
216       switch (LF) {
217       case LibFunc_strcpy:
218       case LibFunc_strncpy:
219       case LibFunc_strcat:
220       case LibFunc_strncat:
221         return true;
222       default:
223         return false;
224       }
225     }
226   }
227   return false;
228 }
229 
230 /// Return a Location stored to by the specified instruction. If isRemovable
231 /// returns true, this function and getLocForRead completely describe the memory
232 /// operations for this instruction.
233 static MemoryLocation getLocForWrite(Instruction *Inst) {
234 
235   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
236     return MemoryLocation::get(SI);
237 
238   if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) {
239     // memcpy/memmove/memset.
240     MemoryLocation Loc = MemoryLocation::getForDest(MI);
241     return Loc;
242   }
243 
244   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
245     switch (II->getIntrinsicID()) {
246     default:
247       return MemoryLocation(); // Unhandled intrinsic.
248     case Intrinsic::init_trampoline:
249       return MemoryLocation(II->getArgOperand(0));
250     case Intrinsic::lifetime_end: {
251       uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
252       return MemoryLocation(II->getArgOperand(1), Len);
253     }
254     }
255   }
256   if (auto *CB = dyn_cast<CallBase>(Inst))
257     // All the supported TLI functions so far happen to have dest as their
258     // first argument.
259     return MemoryLocation(CB->getArgOperand(0));
260   return MemoryLocation();
261 }
262 
263 /// Return the location read by the specified "hasAnalyzableMemoryWrite"
264 /// instruction if any.
265 static MemoryLocation getLocForRead(Instruction *Inst,
266                                     const TargetLibraryInfo &TLI) {
267   assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case");
268 
269   // The only instructions that both read and write are the mem transfer
270   // instructions (memcpy/memmove).
271   if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst))
272     return MemoryLocation::getForSource(MTI);
273   return MemoryLocation();
274 }
275 
276 /// If the value of this instruction and the memory it writes to is unused, may
277 /// we delete this instruction?
278 static bool isRemovable(Instruction *I) {
279   // Don't remove volatile/atomic stores.
280   if (StoreInst *SI = dyn_cast<StoreInst>(I))
281     return SI->isUnordered();
282 
283   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
284     switch (II->getIntrinsicID()) {
285     default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate");
286     case Intrinsic::lifetime_end:
287       // Never remove dead lifetime_end's, e.g. because it is followed by a
288       // free.
289       return false;
290     case Intrinsic::init_trampoline:
291       // Always safe to remove init_trampoline.
292       return true;
293     case Intrinsic::memset:
294     case Intrinsic::memmove:
295     case Intrinsic::memcpy:
296       // Don't remove volatile memory intrinsics.
297       return !cast<MemIntrinsic>(II)->isVolatile();
298     case Intrinsic::memcpy_element_unordered_atomic:
299     case Intrinsic::memmove_element_unordered_atomic:
300     case Intrinsic::memset_element_unordered_atomic:
301       return true;
302     }
303   }
304 
305   // note: only get here for calls with analyzable writes - i.e. libcalls
306   if (auto *CB = dyn_cast<CallBase>(I))
307     return CB->use_empty();
308 
309   return false;
310 }
311 
312 /// Returns true if the end of this instruction can be safely shortened in
313 /// length.
314 static bool isShortenableAtTheEnd(Instruction *I) {
315   // Don't shorten stores for now
316   if (isa<StoreInst>(I))
317     return false;
318 
319   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
320     switch (II->getIntrinsicID()) {
321       default: return false;
322       case Intrinsic::memset:
323       case Intrinsic::memcpy:
324       case Intrinsic::memcpy_element_unordered_atomic:
325       case Intrinsic::memset_element_unordered_atomic:
326         // Do shorten memory intrinsics.
327         // FIXME: Add memmove if it's also safe to transform.
328         return true;
329     }
330   }
331 
332   // Don't shorten libcalls calls for now.
333 
334   return false;
335 }
336 
337 /// Returns true if the beginning of this instruction can be safely shortened
338 /// in length.
339 static bool isShortenableAtTheBeginning(Instruction *I) {
340   // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
341   // easily done by offsetting the source address.
342   return isa<AnyMemSetInst>(I);
343 }
344 
345 /// Return the pointer that is being written to.
346 static Value *getStoredPointerOperand(Instruction *I) {
347   //TODO: factor this to reuse getLocForWrite
348   MemoryLocation Loc = getLocForWrite(I);
349   assert(Loc.Ptr &&
350          "unable to find pointer written for analyzable instruction?");
351   // TODO: most APIs don't expect const Value *
352   return const_cast<Value*>(Loc.Ptr);
353 }
354 
355 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
356                                const TargetLibraryInfo &TLI,
357                                const Function *F) {
358   uint64_t Size;
359   ObjectSizeOpts Opts;
360   Opts.NullIsUnknownSize = NullPointerIsDefined(F);
361 
362   if (getObjectSize(V, Size, DL, &TLI, Opts))
363     return Size;
364   return MemoryLocation::UnknownSize;
365 }
366 
367 namespace {
368 
369 enum OverwriteResult {
370   OW_Begin,
371   OW_Complete,
372   OW_End,
373   OW_PartialEarlierWithFullLater,
374   OW_MaybePartial,
375   OW_Unknown
376 };
377 
378 } // end anonymous namespace
379 
380 /// Return 'OW_Complete' if a store to the 'Later' location completely
381 /// overwrites a store to the 'Earlier' location. Return OW_MaybePartial
382 /// if \p Later does not completely overwrite \p Earlier, but they both
383 /// write to the same underlying object. In that case, use isPartialOverwrite to
384 /// check if \p Later partially overwrites \p Earlier. Returns 'OW_Unknown' if
385 /// nothing can be determined.
386 static OverwriteResult isOverwrite(const MemoryLocation &Later,
387                                    const MemoryLocation &Earlier,
388                                    const DataLayout &DL,
389                                    const TargetLibraryInfo &TLI,
390                                    int64_t &EarlierOff, int64_t &LaterOff,
391                                    AliasAnalysis &AA, const Function *F) {
392   // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll
393   // get imprecise values here, though (except for unknown sizes).
394   if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise())
395     return OW_Unknown;
396 
397   const uint64_t LaterSize = Later.Size.getValue();
398   const uint64_t EarlierSize = Earlier.Size.getValue();
399 
400   const Value *P1 = Earlier.Ptr->stripPointerCasts();
401   const Value *P2 = Later.Ptr->stripPointerCasts();
402 
403   // If the start pointers are the same, we just have to compare sizes to see if
404   // the later store was larger than the earlier store.
405   if (P1 == P2 || AA.isMustAlias(P1, P2)) {
406     // Make sure that the Later size is >= the Earlier size.
407     if (LaterSize >= EarlierSize)
408       return OW_Complete;
409   }
410 
411   // Check to see if the later store is to the entire object (either a global,
412   // an alloca, or a byval/inalloca argument).  If so, then it clearly
413   // overwrites any other store to the same object.
414   const Value *UO1 = getUnderlyingObject(P1), *UO2 = getUnderlyingObject(P2);
415 
416   // If we can't resolve the same pointers to the same object, then we can't
417   // analyze them at all.
418   if (UO1 != UO2)
419     return OW_Unknown;
420 
421   // If the "Later" store is to a recognizable object, get its size.
422   uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F);
423   if (ObjectSize != MemoryLocation::UnknownSize)
424     if (ObjectSize == LaterSize && ObjectSize >= EarlierSize)
425       return OW_Complete;
426 
427   // Okay, we have stores to two completely different pointers.  Try to
428   // decompose the pointer into a "base + constant_offset" form.  If the base
429   // pointers are equal, then we can reason about the two stores.
430   EarlierOff = 0;
431   LaterOff = 0;
432   const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
433   const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
434 
435   // If the base pointers still differ, we have two completely different stores.
436   if (BP1 != BP2)
437     return OW_Unknown;
438 
439   // The later store completely overlaps the earlier store if:
440   //
441   // 1. Both start at the same offset and the later one's size is greater than
442   //    or equal to the earlier one's, or
443   //
444   //      |--earlier--|
445   //      |--   later   --|
446   //
447   // 2. The earlier store has an offset greater than the later offset, but which
448   //    still lies completely within the later store.
449   //
450   //        |--earlier--|
451   //    |-----  later  ------|
452   //
453   // We have to be careful here as *Off is signed while *.Size is unsigned.
454   if (EarlierOff >= LaterOff &&
455       LaterSize >= EarlierSize &&
456       uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize)
457     return OW_Complete;
458 
459   // Later may overwrite earlier completely with other partial writes.
460   return OW_MaybePartial;
461 }
462 
463 /// Return 'OW_Complete' if a store to the 'Later' location completely
464 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the
465 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the
466 /// beginning of the 'Earlier' location is overwritten by 'Later'.
467 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was
468 /// overwritten by a latter (smaller) store which doesn't write outside the big
469 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
470 /// NOTE: This function must only be called if both \p Later and \p Earlier
471 /// write to the same underlying object with valid \p EarlierOff and \p
472 /// LaterOff.
473 static OverwriteResult isPartialOverwrite(const MemoryLocation &Later,
474                                           const MemoryLocation &Earlier,
475                                           int64_t EarlierOff, int64_t LaterOff,
476                                           Instruction *DepWrite,
477                                           InstOverlapIntervalsTy &IOL) {
478   const uint64_t LaterSize = Later.Size.getValue();
479   const uint64_t EarlierSize = Earlier.Size.getValue();
480   // We may now overlap, although the overlap is not complete. There might also
481   // be other incomplete overlaps, and together, they might cover the complete
482   // earlier write.
483   // Note: The correctness of this logic depends on the fact that this function
484   // is not even called providing DepWrite when there are any intervening reads.
485   if (EnablePartialOverwriteTracking &&
486       LaterOff < int64_t(EarlierOff + EarlierSize) &&
487       int64_t(LaterOff + LaterSize) >= EarlierOff) {
488 
489     // Insert our part of the overlap into the map.
490     auto &IM = IOL[DepWrite];
491     LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff
492                       << ", " << int64_t(EarlierOff + EarlierSize)
493                       << ") Later [" << LaterOff << ", "
494                       << int64_t(LaterOff + LaterSize) << ")\n");
495 
496     // Make sure that we only insert non-overlapping intervals and combine
497     // adjacent intervals. The intervals are stored in the map with the ending
498     // offset as the key (in the half-open sense) and the starting offset as
499     // the value.
500     int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize;
501 
502     // Find any intervals ending at, or after, LaterIntStart which start
503     // before LaterIntEnd.
504     auto ILI = IM.lower_bound(LaterIntStart);
505     if (ILI != IM.end() && ILI->second <= LaterIntEnd) {
506       // This existing interval is overlapped with the current store somewhere
507       // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing
508       // intervals and adjusting our start and end.
509       LaterIntStart = std::min(LaterIntStart, ILI->second);
510       LaterIntEnd = std::max(LaterIntEnd, ILI->first);
511       ILI = IM.erase(ILI);
512 
513       // Continue erasing and adjusting our end in case other previous
514       // intervals are also overlapped with the current store.
515       //
516       // |--- ealier 1 ---|  |--- ealier 2 ---|
517       //     |------- later---------|
518       //
519       while (ILI != IM.end() && ILI->second <= LaterIntEnd) {
520         assert(ILI->second > LaterIntStart && "Unexpected interval");
521         LaterIntEnd = std::max(LaterIntEnd, ILI->first);
522         ILI = IM.erase(ILI);
523       }
524     }
525 
526     IM[LaterIntEnd] = LaterIntStart;
527 
528     ILI = IM.begin();
529     if (ILI->second <= EarlierOff &&
530         ILI->first >= int64_t(EarlierOff + EarlierSize)) {
531       LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier ["
532                         << EarlierOff << ", "
533                         << int64_t(EarlierOff + EarlierSize)
534                         << ") Composite Later [" << ILI->second << ", "
535                         << ILI->first << ")\n");
536       ++NumCompletePartials;
537       return OW_Complete;
538     }
539   }
540 
541   // Check for an earlier store which writes to all the memory locations that
542   // the later store writes to.
543   if (EnablePartialStoreMerging && LaterOff >= EarlierOff &&
544       int64_t(EarlierOff + EarlierSize) > LaterOff &&
545       uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) {
546     LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load ["
547                       << EarlierOff << ", "
548                       << int64_t(EarlierOff + EarlierSize)
549                       << ") by a later store [" << LaterOff << ", "
550                       << int64_t(LaterOff + LaterSize) << ")\n");
551     // TODO: Maybe come up with a better name?
552     return OW_PartialEarlierWithFullLater;
553   }
554 
555   // Another interesting case is if the later store overwrites the end of the
556   // earlier store.
557   //
558   //      |--earlier--|
559   //                |--   later   --|
560   //
561   // In this case we may want to trim the size of earlier to avoid generating
562   // writes to addresses which will definitely be overwritten later
563   if (!EnablePartialOverwriteTracking &&
564       (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) &&
565        int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize)))
566     return OW_End;
567 
568   // Finally, we also need to check if the later store overwrites the beginning
569   // of the earlier store.
570   //
571   //                |--earlier--|
572   //      |--   later   --|
573   //
574   // In this case we may want to move the destination address and trim the size
575   // of earlier to avoid generating writes to addresses which will definitely
576   // be overwritten later.
577   if (!EnablePartialOverwriteTracking &&
578       (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) {
579     assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) &&
580            "Expect to be handled as OW_Complete");
581     return OW_Begin;
582   }
583   // Otherwise, they don't completely overlap.
584   return OW_Unknown;
585 }
586 
587 /// If 'Inst' might be a self read (i.e. a noop copy of a
588 /// memory region into an identical pointer) then it doesn't actually make its
589 /// input dead in the traditional sense.  Consider this case:
590 ///
591 ///   memmove(A <- B)
592 ///   memmove(A <- A)
593 ///
594 /// In this case, the second store to A does not make the first store to A dead.
595 /// The usual situation isn't an explicit A<-A store like this (which can be
596 /// trivially removed) but a case where two pointers may alias.
597 ///
598 /// This function detects when it is unsafe to remove a dependent instruction
599 /// because the DSE inducing instruction may be a self-read.
600 static bool isPossibleSelfRead(Instruction *Inst,
601                                const MemoryLocation &InstStoreLoc,
602                                Instruction *DepWrite,
603                                const TargetLibraryInfo &TLI,
604                                AliasAnalysis &AA) {
605   // Self reads can only happen for instructions that read memory.  Get the
606   // location read.
607   MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
608   if (!InstReadLoc.Ptr)
609     return false; // Not a reading instruction.
610 
611   // If the read and written loc obviously don't alias, it isn't a read.
612   if (AA.isNoAlias(InstReadLoc, InstStoreLoc))
613     return false;
614 
615   if (isa<AnyMemCpyInst>(Inst)) {
616     // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763)
617     // but in practice memcpy(A <- B) either means that A and B are disjoint or
618     // are equal (i.e. there are not partial overlaps).  Given that, if we have:
619     //
620     //   memcpy/memmove(A <- B)  // DepWrite
621     //   memcpy(A <- B)  // Inst
622     //
623     // with Inst reading/writing a >= size than DepWrite, we can reason as
624     // follows:
625     //
626     //   - If A == B then both the copies are no-ops, so the DepWrite can be
627     //     removed.
628     //   - If A != B then A and B are disjoint locations in Inst.  Since
629     //     Inst.size >= DepWrite.size A and B are disjoint in DepWrite too.
630     //     Therefore DepWrite can be removed.
631     MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
632 
633     if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
634       return false;
635   }
636 
637   // If DepWrite doesn't read memory or if we can't prove it is a must alias,
638   // then it can't be considered dead.
639   return true;
640 }
641 
642 /// Returns true if the memory which is accessed by the second instruction is not
643 /// modified between the first and the second instruction.
644 /// Precondition: Second instruction must be dominated by the first
645 /// instruction.
646 static bool memoryIsNotModifiedBetween(Instruction *FirstI,
647                                        Instruction *SecondI,
648                                        AliasAnalysis *AA,
649                                        const DataLayout &DL,
650                                        DominatorTree *DT) {
651   // Do a backwards scan through the CFG from SecondI to FirstI. Look for
652   // instructions which can modify the memory location accessed by SecondI.
653   //
654   // While doing the walk keep track of the address to check. It might be
655   // different in different basic blocks due to PHI translation.
656   using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>;
657   SmallVector<BlockAddressPair, 16> WorkList;
658   // Keep track of the address we visited each block with. Bail out if we
659   // visit a block with different addresses.
660   DenseMap<BasicBlock *, Value *> Visited;
661 
662   BasicBlock::iterator FirstBBI(FirstI);
663   ++FirstBBI;
664   BasicBlock::iterator SecondBBI(SecondI);
665   BasicBlock *FirstBB = FirstI->getParent();
666   BasicBlock *SecondBB = SecondI->getParent();
667   MemoryLocation MemLoc = MemoryLocation::get(SecondI);
668   auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr);
669 
670   // Start checking the SecondBB.
671   WorkList.push_back(
672       std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr)));
673   bool isFirstBlock = true;
674 
675   // Check all blocks going backward until we reach the FirstBB.
676   while (!WorkList.empty()) {
677     BlockAddressPair Current = WorkList.pop_back_val();
678     BasicBlock *B = Current.first;
679     PHITransAddr &Addr = Current.second;
680     Value *Ptr = Addr.getAddr();
681 
682     // Ignore instructions before FirstI if this is the FirstBB.
683     BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
684 
685     BasicBlock::iterator EI;
686     if (isFirstBlock) {
687       // Ignore instructions after SecondI if this is the first visit of SecondBB.
688       assert(B == SecondBB && "first block is not the store block");
689       EI = SecondBBI;
690       isFirstBlock = false;
691     } else {
692       // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
693       // In this case we also have to look at instructions after SecondI.
694       EI = B->end();
695     }
696     for (; BI != EI; ++BI) {
697       Instruction *I = &*BI;
698       if (I->mayWriteToMemory() && I != SecondI)
699         if (isModSet(AA->getModRefInfo(I, MemLoc.getWithNewPtr(Ptr))))
700           return false;
701     }
702     if (B != FirstBB) {
703       assert(B != &FirstBB->getParent()->getEntryBlock() &&
704           "Should not hit the entry block because SI must be dominated by LI");
705       for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
706         PHITransAddr PredAddr = Addr;
707         if (PredAddr.NeedsPHITranslationFromBlock(B)) {
708           if (!PredAddr.IsPotentiallyPHITranslatable())
709             return false;
710           if (PredAddr.PHITranslateValue(B, *PredI, DT, false))
711             return false;
712         }
713         Value *TranslatedPtr = PredAddr.getAddr();
714         auto Inserted = Visited.insert(std::make_pair(*PredI, TranslatedPtr));
715         if (!Inserted.second) {
716           // We already visited this block before. If it was with a different
717           // address - bail out!
718           if (TranslatedPtr != Inserted.first->second)
719             return false;
720           // ... otherwise just skip it.
721           continue;
722         }
723         WorkList.push_back(std::make_pair(*PredI, PredAddr));
724       }
725     }
726   }
727   return true;
728 }
729 
730 /// Find all blocks that will unconditionally lead to the block BB and append
731 /// them to F.
732 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
733                                    BasicBlock *BB, DominatorTree *DT) {
734   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
735     BasicBlock *Pred = *I;
736     if (Pred == BB) continue;
737     Instruction *PredTI = Pred->getTerminator();
738     if (PredTI->getNumSuccessors() != 1)
739       continue;
740 
741     if (DT->isReachableFromEntry(Pred))
742       Blocks.push_back(Pred);
743   }
744 }
745 
746 /// Handle frees of entire structures whose dependency is a store
747 /// to a field of that structure.
748 static bool handleFree(CallInst *F, AliasAnalysis *AA,
749                        MemoryDependenceResults *MD, DominatorTree *DT,
750                        const TargetLibraryInfo *TLI,
751                        InstOverlapIntervalsTy &IOL,
752                        MapVector<Instruction *, bool> &ThrowableInst) {
753   bool MadeChange = false;
754 
755   MemoryLocation Loc = MemoryLocation(F->getOperand(0));
756   SmallVector<BasicBlock *, 16> Blocks;
757   Blocks.push_back(F->getParent());
758 
759   while (!Blocks.empty()) {
760     BasicBlock *BB = Blocks.pop_back_val();
761     Instruction *InstPt = BB->getTerminator();
762     if (BB == F->getParent()) InstPt = F;
763 
764     MemDepResult Dep =
765         MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
766     while (Dep.isDef() || Dep.isClobber()) {
767       Instruction *Dependency = Dep.getInst();
768       if (!hasAnalyzableMemoryWrite(Dependency, *TLI) ||
769           !isRemovable(Dependency))
770         break;
771 
772       Value *DepPointer =
773           getUnderlyingObject(getStoredPointerOperand(Dependency));
774 
775       // Check for aliasing.
776       if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
777         break;
778 
779       LLVM_DEBUG(
780           dbgs() << "DSE: Dead Store to soon to be freed memory:\n  DEAD: "
781                  << *Dependency << '\n');
782 
783       // DCE instructions only used to calculate that store.
784       BasicBlock::iterator BBI(Dependency);
785       deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL,
786                             ThrowableInst);
787       ++NumFastStores;
788       MadeChange = true;
789 
790       // Inst's old Dependency is now deleted. Compute the next dependency,
791       // which may also be dead, as in
792       //    s[0] = 0;
793       //    s[1] = 0; // This has just been deleted.
794       //    free(s);
795       Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB);
796     }
797 
798     if (Dep.isNonLocal())
799       findUnconditionalPreds(Blocks, BB, DT);
800   }
801 
802   return MadeChange;
803 }
804 
805 /// Check to see if the specified location may alias any of the stack objects in
806 /// the DeadStackObjects set. If so, they become live because the location is
807 /// being loaded.
808 static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
809                                   SmallSetVector<const Value *, 16> &DeadStackObjects,
810                                   const DataLayout &DL, AliasAnalysis *AA,
811                                   const TargetLibraryInfo *TLI,
812                                   const Function *F) {
813   const Value *UnderlyingPointer = getUnderlyingObject(LoadedLoc.Ptr);
814 
815   // A constant can't be in the dead pointer set.
816   if (isa<Constant>(UnderlyingPointer))
817     return;
818 
819   // If the kill pointer can be easily reduced to an alloca, don't bother doing
820   // extraneous AA queries.
821   if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
822     DeadStackObjects.remove(UnderlyingPointer);
823     return;
824   }
825 
826   // Remove objects that could alias LoadedLoc.
827   DeadStackObjects.remove_if([&](const Value *I) {
828     // See if the loaded location could alias the stack location.
829     MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F));
830     return !AA->isNoAlias(StackLoc, LoadedLoc);
831   });
832 }
833 
834 /// Remove dead stores to stack-allocated locations in the function end block.
835 /// Ex:
836 /// %A = alloca i32
837 /// ...
838 /// store i32 1, i32* %A
839 /// ret void
840 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
841                            MemoryDependenceResults *MD,
842                            const TargetLibraryInfo *TLI,
843                            InstOverlapIntervalsTy &IOL,
844                            MapVector<Instruction *, bool> &ThrowableInst) {
845   bool MadeChange = false;
846 
847   // Keep track of all of the stack objects that are dead at the end of the
848   // function.
849   SmallSetVector<const Value*, 16> DeadStackObjects;
850 
851   // Find all of the alloca'd pointers in the entry block.
852   BasicBlock &Entry = BB.getParent()->front();
853   for (Instruction &I : Entry) {
854     if (isa<AllocaInst>(&I))
855       DeadStackObjects.insert(&I);
856 
857     // Okay, so these are dead heap objects, but if the pointer never escapes
858     // then it's leaked by this function anyways.
859     else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
860       DeadStackObjects.insert(&I);
861   }
862 
863   // Treat byval or inalloca arguments the same, stores to them are dead at the
864   // end of the function.
865   for (Argument &AI : BB.getParent()->args())
866     if (AI.hasPassPointeeByValueCopyAttr())
867       DeadStackObjects.insert(&AI);
868 
869   const DataLayout &DL = BB.getModule()->getDataLayout();
870 
871   // Scan the basic block backwards
872   for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
873     --BBI;
874 
875     // If we find a store, check to see if it points into a dead stack value.
876     if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
877       // See through pointer-to-pointer bitcasts
878       SmallVector<const Value *, 4> Pointers;
879       getUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers);
880 
881       // Stores to stack values are valid candidates for removal.
882       bool AllDead = true;
883       for (const Value *Pointer : Pointers)
884         if (!DeadStackObjects.count(Pointer)) {
885           AllDead = false;
886           break;
887         }
888 
889       if (AllDead) {
890         Instruction *Dead = &*BBI;
891 
892         LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n  DEAD: "
893                           << *Dead << "\n  Objects: ";
894                    for (SmallVectorImpl<const Value *>::iterator I =
895                             Pointers.begin(),
896                         E = Pointers.end();
897                         I != E; ++I) {
898                      dbgs() << **I;
899                      if (std::next(I) != E)
900                        dbgs() << ", ";
901                    } dbgs()
902                    << '\n');
903 
904         // DCE instructions only used to calculate that store.
905         deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, ThrowableInst,
906                               &DeadStackObjects);
907         ++NumFastStores;
908         MadeChange = true;
909         continue;
910       }
911     }
912 
913     // Remove any dead non-memory-mutating instructions.
914     if (isInstructionTriviallyDead(&*BBI, TLI)) {
915       LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n  DEAD: "
916                         << *&*BBI << '\n');
917       deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, ThrowableInst,
918                             &DeadStackObjects);
919       ++NumFastOther;
920       MadeChange = true;
921       continue;
922     }
923 
924     if (isa<AllocaInst>(BBI)) {
925       // Remove allocas from the list of dead stack objects; there can't be
926       // any references before the definition.
927       DeadStackObjects.remove(&*BBI);
928       continue;
929     }
930 
931     if (auto *Call = dyn_cast<CallBase>(&*BBI)) {
932       // Remove allocation function calls from the list of dead stack objects;
933       // there can't be any references before the definition.
934       if (isAllocLikeFn(&*BBI, TLI))
935         DeadStackObjects.remove(&*BBI);
936 
937       // If this call does not access memory, it can't be loading any of our
938       // pointers.
939       if (AA->doesNotAccessMemory(Call))
940         continue;
941 
942       // If the call might load from any of our allocas, then any store above
943       // the call is live.
944       DeadStackObjects.remove_if([&](const Value *I) {
945         // See if the call site touches the value.
946         return isRefSet(AA->getModRefInfo(
947             Call, I, getPointerSize(I, DL, *TLI, BB.getParent())));
948       });
949 
950       // If all of the allocas were clobbered by the call then we're not going
951       // to find anything else to process.
952       if (DeadStackObjects.empty())
953         break;
954 
955       continue;
956     }
957 
958     // We can remove the dead stores, irrespective of the fence and its ordering
959     // (release/acquire/seq_cst). Fences only constraints the ordering of
960     // already visible stores, it does not make a store visible to other
961     // threads. So, skipping over a fence does not change a store from being
962     // dead.
963     if (isa<FenceInst>(*BBI))
964       continue;
965 
966     MemoryLocation LoadedLoc;
967 
968     // If we encounter a use of the pointer, it is no longer considered dead
969     if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
970       if (!L->isUnordered()) // Be conservative with atomic/volatile load
971         break;
972       LoadedLoc = MemoryLocation::get(L);
973     } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
974       LoadedLoc = MemoryLocation::get(V);
975     } else if (!BBI->mayReadFromMemory()) {
976       // Instruction doesn't read memory.  Note that stores that weren't removed
977       // above will hit this case.
978       continue;
979     } else {
980       // Unknown inst; assume it clobbers everything.
981       break;
982     }
983 
984     // Remove any allocas from the DeadPointer set that are loaded, as this
985     // makes any stores above the access live.
986     removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent());
987 
988     // If all of the allocas were clobbered by the access then we're not going
989     // to find anything else to process.
990     if (DeadStackObjects.empty())
991       break;
992   }
993 
994   return MadeChange;
995 }
996 
997 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset,
998                          int64_t &EarlierSize, int64_t LaterOffset,
999                          int64_t LaterSize, bool IsOverwriteEnd) {
1000   // TODO: base this on the target vector size so that if the earlier
1001   // store was too small to get vector writes anyway then its likely
1002   // a good idea to shorten it
1003   // Power of 2 vector writes are probably always a bad idea to optimize
1004   // as any store/memset/memcpy is likely using vector instructions so
1005   // shortening it to not vector size is likely to be slower
1006   auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite);
1007   unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment();
1008   if (!IsOverwriteEnd)
1009     LaterOffset = int64_t(LaterOffset + LaterSize);
1010 
1011   if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) &&
1012       !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0))
1013     return false;
1014 
1015   int64_t NewLength = IsOverwriteEnd
1016                           ? LaterOffset - EarlierOffset
1017                           : EarlierSize - (LaterOffset - EarlierOffset);
1018 
1019   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) {
1020     // When shortening an atomic memory intrinsic, the newly shortened
1021     // length must remain an integer multiple of the element size.
1022     const uint32_t ElementSize = AMI->getElementSizeInBytes();
1023     if (0 != NewLength % ElementSize)
1024       return false;
1025   }
1026 
1027   LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW "
1028                     << (IsOverwriteEnd ? "END" : "BEGIN") << ": "
1029                     << *EarlierWrite << "\n  KILLER (offset " << LaterOffset
1030                     << ", " << EarlierSize << ")\n");
1031 
1032   Value *EarlierWriteLength = EarlierIntrinsic->getLength();
1033   Value *TrimmedLength =
1034       ConstantInt::get(EarlierWriteLength->getType(), NewLength);
1035   EarlierIntrinsic->setLength(TrimmedLength);
1036 
1037   EarlierSize = NewLength;
1038   if (!IsOverwriteEnd) {
1039     int64_t OffsetMoved = (LaterOffset - EarlierOffset);
1040     Value *Indices[1] = {
1041         ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)};
1042     GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
1043         EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(),
1044         EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite);
1045     NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc());
1046     EarlierIntrinsic->setDest(NewDestGEP);
1047     EarlierOffset = EarlierOffset + OffsetMoved;
1048   }
1049   return true;
1050 }
1051 
1052 static bool tryToShortenEnd(Instruction *EarlierWrite,
1053                             OverlapIntervalsTy &IntervalMap,
1054                             int64_t &EarlierStart, int64_t &EarlierSize) {
1055   if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite))
1056     return false;
1057 
1058   OverlapIntervalsTy::iterator OII = --IntervalMap.end();
1059   int64_t LaterStart = OII->second;
1060   int64_t LaterSize = OII->first - LaterStart;
1061 
1062   if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize &&
1063       LaterStart + LaterSize >= EarlierStart + EarlierSize) {
1064     if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
1065                      LaterSize, true)) {
1066       IntervalMap.erase(OII);
1067       return true;
1068     }
1069   }
1070   return false;
1071 }
1072 
1073 static bool tryToShortenBegin(Instruction *EarlierWrite,
1074                               OverlapIntervalsTy &IntervalMap,
1075                               int64_t &EarlierStart, int64_t &EarlierSize) {
1076   if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite))
1077     return false;
1078 
1079   OverlapIntervalsTy::iterator OII = IntervalMap.begin();
1080   int64_t LaterStart = OII->second;
1081   int64_t LaterSize = OII->first - LaterStart;
1082 
1083   if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) {
1084     assert(LaterStart + LaterSize < EarlierStart + EarlierSize &&
1085            "Should have been handled as OW_Complete");
1086     if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
1087                      LaterSize, false)) {
1088       IntervalMap.erase(OII);
1089       return true;
1090     }
1091   }
1092   return false;
1093 }
1094 
1095 static bool removePartiallyOverlappedStores(const DataLayout &DL,
1096                                             InstOverlapIntervalsTy &IOL) {
1097   bool Changed = false;
1098   for (auto OI : IOL) {
1099     Instruction *EarlierWrite = OI.first;
1100     MemoryLocation Loc = getLocForWrite(EarlierWrite);
1101     assert(isRemovable(EarlierWrite) && "Expect only removable instruction");
1102 
1103     const Value *Ptr = Loc.Ptr->stripPointerCasts();
1104     int64_t EarlierStart = 0;
1105     int64_t EarlierSize = int64_t(Loc.Size.getValue());
1106     GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL);
1107     OverlapIntervalsTy &IntervalMap = OI.second;
1108     Changed |=
1109         tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
1110     if (IntervalMap.empty())
1111       continue;
1112     Changed |=
1113         tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
1114   }
1115   return Changed;
1116 }
1117 
1118 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI,
1119                                AliasAnalysis *AA, MemoryDependenceResults *MD,
1120                                const DataLayout &DL,
1121                                const TargetLibraryInfo *TLI,
1122                                InstOverlapIntervalsTy &IOL,
1123                                MapVector<Instruction *, bool> &ThrowableInst,
1124                                DominatorTree *DT) {
1125   // Must be a store instruction.
1126   StoreInst *SI = dyn_cast<StoreInst>(Inst);
1127   if (!SI)
1128     return false;
1129 
1130   // If we're storing the same value back to a pointer that we just loaded from,
1131   // then the store can be removed.
1132   if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
1133     if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
1134         isRemovable(SI) &&
1135         memoryIsNotModifiedBetween(DepLoad, SI, AA, DL, DT)) {
1136 
1137       LLVM_DEBUG(
1138           dbgs() << "DSE: Remove Store Of Load from same pointer:\n  LOAD: "
1139                  << *DepLoad << "\n  STORE: " << *SI << '\n');
1140 
1141       deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst);
1142       ++NumRedundantStores;
1143       return true;
1144     }
1145   }
1146 
1147   // Remove null stores into the calloc'ed objects
1148   Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
1149   if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) {
1150     Instruction *UnderlyingPointer =
1151         dyn_cast<Instruction>(getUnderlyingObject(SI->getPointerOperand()));
1152 
1153     if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
1154         memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA, DL, DT)) {
1155       LLVM_DEBUG(
1156           dbgs() << "DSE: Remove null store to the calloc'ed object:\n  DEAD: "
1157                  << *Inst << "\n  OBJECT: " << *UnderlyingPointer << '\n');
1158 
1159       deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst);
1160       ++NumRedundantStores;
1161       return true;
1162     }
1163   }
1164   return false;
1165 }
1166 
1167 static Constant *
1168 tryToMergePartialOverlappingStores(StoreInst *Earlier, StoreInst *Later,
1169                                    int64_t InstWriteOffset,
1170                                    int64_t DepWriteOffset, const DataLayout &DL,
1171                                    AliasAnalysis *AA, DominatorTree *DT) {
1172 
1173   if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) &&
1174       DL.typeSizeEqualsStoreSize(Earlier->getValueOperand()->getType()) &&
1175       Later && isa<ConstantInt>(Later->getValueOperand()) &&
1176       DL.typeSizeEqualsStoreSize(Later->getValueOperand()->getType()) &&
1177       memoryIsNotModifiedBetween(Earlier, Later, AA, DL, DT)) {
1178     // If the store we find is:
1179     //   a) partially overwritten by the store to 'Loc'
1180     //   b) the later store is fully contained in the earlier one and
1181     //   c) they both have a constant value
1182     //   d) none of the two stores need padding
1183     // Merge the two stores, replacing the earlier store's value with a
1184     // merge of both values.
1185     // TODO: Deal with other constant types (vectors, etc), and probably
1186     // some mem intrinsics (if needed)
1187 
1188     APInt EarlierValue =
1189         cast<ConstantInt>(Earlier->getValueOperand())->getValue();
1190     APInt LaterValue = cast<ConstantInt>(Later->getValueOperand())->getValue();
1191     unsigned LaterBits = LaterValue.getBitWidth();
1192     assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth());
1193     LaterValue = LaterValue.zext(EarlierValue.getBitWidth());
1194 
1195     // Offset of the smaller store inside the larger store
1196     unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8;
1197     unsigned LShiftAmount = DL.isBigEndian() ? EarlierValue.getBitWidth() -
1198                                                    BitOffsetDiff - LaterBits
1199                                              : BitOffsetDiff;
1200     APInt Mask = APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount,
1201                                    LShiftAmount + LaterBits);
1202     // Clear the bits we'll be replacing, then OR with the smaller
1203     // store, shifted appropriately.
1204     APInt Merged = (EarlierValue & ~Mask) | (LaterValue << LShiftAmount);
1205     LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n  Earlier: " << *Earlier
1206                       << "\n  Later: " << *Later
1207                       << "\n  Merged Value: " << Merged << '\n');
1208     return ConstantInt::get(Earlier->getValueOperand()->getType(), Merged);
1209   }
1210   return nullptr;
1211 }
1212 
1213 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
1214                                 MemoryDependenceResults *MD, DominatorTree *DT,
1215                                 const TargetLibraryInfo *TLI) {
1216   const DataLayout &DL = BB.getModule()->getDataLayout();
1217   bool MadeChange = false;
1218 
1219   MapVector<Instruction *, bool> ThrowableInst;
1220 
1221   // A map of interval maps representing partially-overwritten value parts.
1222   InstOverlapIntervalsTy IOL;
1223 
1224   // Do a top-down walk on the BB.
1225   for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
1226     // Handle 'free' calls specially.
1227     if (CallInst *F = isFreeCall(&*BBI, TLI)) {
1228       MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, ThrowableInst);
1229       // Increment BBI after handleFree has potentially deleted instructions.
1230       // This ensures we maintain a valid iterator.
1231       ++BBI;
1232       continue;
1233     }
1234 
1235     Instruction *Inst = &*BBI++;
1236 
1237     if (Inst->mayThrow()) {
1238       ThrowableInst[Inst] = true;
1239       continue;
1240     }
1241 
1242     // Check to see if Inst writes to memory.  If not, continue.
1243     if (!hasAnalyzableMemoryWrite(Inst, *TLI))
1244       continue;
1245 
1246     // eliminateNoopStore will update in iterator, if necessary.
1247     if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL,
1248                            ThrowableInst, DT)) {
1249       MadeChange = true;
1250       continue;
1251     }
1252 
1253     // If we find something that writes memory, get its memory dependence.
1254     MemDepResult InstDep = MD->getDependency(Inst);
1255 
1256     // Ignore any store where we can't find a local dependence.
1257     // FIXME: cross-block DSE would be fun. :)
1258     if (!InstDep.isDef() && !InstDep.isClobber())
1259       continue;
1260 
1261     // Figure out what location is being stored to.
1262     MemoryLocation Loc = getLocForWrite(Inst);
1263 
1264     // If we didn't get a useful location, fail.
1265     if (!Loc.Ptr)
1266       continue;
1267 
1268     // Loop until we find a store we can eliminate or a load that
1269     // invalidates the analysis. Without an upper bound on the number of
1270     // instructions examined, this analysis can become very time-consuming.
1271     // However, the potential gain diminishes as we process more instructions
1272     // without eliminating any of them. Therefore, we limit the number of
1273     // instructions we look at.
1274     auto Limit = MD->getDefaultBlockScanLimit();
1275     while (InstDep.isDef() || InstDep.isClobber()) {
1276       // Get the memory clobbered by the instruction we depend on.  MemDep will
1277       // skip any instructions that 'Loc' clearly doesn't interact with.  If we
1278       // end up depending on a may- or must-aliased load, then we can't optimize
1279       // away the store and we bail out.  However, if we depend on something
1280       // that overwrites the memory location we *can* potentially optimize it.
1281       //
1282       // Find out what memory location the dependent instruction stores.
1283       Instruction *DepWrite = InstDep.getInst();
1284       if (!hasAnalyzableMemoryWrite(DepWrite, *TLI))
1285         break;
1286       MemoryLocation DepLoc = getLocForWrite(DepWrite);
1287       // If we didn't get a useful location, or if it isn't a size, bail out.
1288       if (!DepLoc.Ptr)
1289         break;
1290 
1291       // Find the last throwable instruction not removed by call to
1292       // deleteDeadInstruction.
1293       Instruction *LastThrowing = nullptr;
1294       if (!ThrowableInst.empty())
1295         LastThrowing = ThrowableInst.back().first;
1296 
1297       // Make sure we don't look past a call which might throw. This is an
1298       // issue because MemoryDependenceAnalysis works in the wrong direction:
1299       // it finds instructions which dominate the current instruction, rather than
1300       // instructions which are post-dominated by the current instruction.
1301       //
1302       // If the underlying object is a non-escaping memory allocation, any store
1303       // to it is dead along the unwind edge. Otherwise, we need to preserve
1304       // the store.
1305       if (LastThrowing && DepWrite->comesBefore(LastThrowing)) {
1306         const Value *Underlying = getUnderlyingObject(DepLoc.Ptr);
1307         bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying);
1308         if (!IsStoreDeadOnUnwind) {
1309             // We're looking for a call to an allocation function
1310             // where the allocation doesn't escape before the last
1311             // throwing instruction; PointerMayBeCaptured
1312             // reasonably fast approximation.
1313             IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) &&
1314                 !PointerMayBeCaptured(Underlying, false, true);
1315         }
1316         if (!IsStoreDeadOnUnwind)
1317           break;
1318       }
1319 
1320       // If we find a write that is a) removable (i.e., non-volatile), b) is
1321       // completely obliterated by the store to 'Loc', and c) which we know that
1322       // 'Inst' doesn't load from, then we can remove it.
1323       // Also try to merge two stores if a later one only touches memory written
1324       // to by the earlier one.
1325       if (isRemovable(DepWrite) &&
1326           !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
1327         int64_t InstWriteOffset, DepWriteOffset;
1328         OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset,
1329                                          InstWriteOffset, *AA, BB.getParent());
1330         if (OR == OW_MaybePartial)
1331           OR = isPartialOverwrite(Loc, DepLoc, DepWriteOffset, InstWriteOffset,
1332                                   DepWrite, IOL);
1333 
1334         if (OR == OW_Complete) {
1335           LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *DepWrite
1336                             << "\n  KILLER: " << *Inst << '\n');
1337 
1338           // Delete the store and now-dead instructions that feed it.
1339           deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1340                                 ThrowableInst);
1341           ++NumFastStores;
1342           MadeChange = true;
1343 
1344           // We erased DepWrite; start over.
1345           InstDep = MD->getDependency(Inst);
1346           continue;
1347         } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) ||
1348                    ((OR == OW_Begin &&
1349                      isShortenableAtTheBeginning(DepWrite)))) {
1350           assert(!EnablePartialOverwriteTracking && "Do not expect to perform "
1351                                                     "when partial-overwrite "
1352                                                     "tracking is enabled");
1353           // The overwrite result is known, so these must be known, too.
1354           int64_t EarlierSize = DepLoc.Size.getValue();
1355           int64_t LaterSize = Loc.Size.getValue();
1356           bool IsOverwriteEnd = (OR == OW_End);
1357           MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize,
1358                                     InstWriteOffset, LaterSize, IsOverwriteEnd);
1359         } else if (EnablePartialStoreMerging &&
1360                    OR == OW_PartialEarlierWithFullLater) {
1361           auto *Earlier = dyn_cast<StoreInst>(DepWrite);
1362           auto *Later = dyn_cast<StoreInst>(Inst);
1363           if (Constant *C = tryToMergePartialOverlappingStores(
1364                   Earlier, Later, InstWriteOffset, DepWriteOffset, DL, AA,
1365                   DT)) {
1366             auto *SI = new StoreInst(
1367                 C, Earlier->getPointerOperand(), false, Earlier->getAlign(),
1368                 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite);
1369 
1370             unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa,
1371                                    LLVMContext::MD_alias_scope,
1372                                    LLVMContext::MD_noalias,
1373                                    LLVMContext::MD_nontemporal};
1374             SI->copyMetadata(*DepWrite, MDToKeep);
1375             ++NumModifiedStores;
1376 
1377             // Delete the old stores and now-dead instructions that feed them.
1378             deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL,
1379                                   ThrowableInst);
1380             deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1381                                   ThrowableInst);
1382             MadeChange = true;
1383 
1384             // We erased DepWrite and Inst (Loc); start over.
1385             break;
1386           }
1387         }
1388       }
1389 
1390       // If this is a may-aliased store that is clobbering the store value, we
1391       // can keep searching past it for another must-aliased pointer that stores
1392       // to the same location.  For example, in:
1393       //   store -> P
1394       //   store -> Q
1395       //   store -> P
1396       // we can remove the first store to P even though we don't know if P and Q
1397       // alias.
1398       if (DepWrite == &BB.front()) break;
1399 
1400       // Can't look past this instruction if it might read 'Loc'.
1401       if (isRefSet(AA->getModRefInfo(DepWrite, Loc)))
1402         break;
1403 
1404       InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false,
1405                                              DepWrite->getIterator(), &BB,
1406                                              /*QueryInst=*/ nullptr, &Limit);
1407     }
1408   }
1409 
1410   if (EnablePartialOverwriteTracking)
1411     MadeChange |= removePartiallyOverlappedStores(DL, IOL);
1412 
1413   // If this block ends in a return, unwind, or unreachable, all allocas are
1414   // dead at its end, which means stores to them are also dead.
1415   if (BB.getTerminator()->getNumSuccessors() == 0)
1416     MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, ThrowableInst);
1417 
1418   return MadeChange;
1419 }
1420 
1421 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
1422                                 MemoryDependenceResults *MD, DominatorTree *DT,
1423                                 const TargetLibraryInfo *TLI) {
1424   bool MadeChange = false;
1425   for (BasicBlock &BB : F)
1426     // Only check non-dead blocks.  Dead blocks may have strange pointer
1427     // cycles that will confuse alias analysis.
1428     if (DT->isReachableFromEntry(&BB))
1429       MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
1430 
1431   return MadeChange;
1432 }
1433 
1434 namespace {
1435 //=============================================================================
1436 // MemorySSA backed dead store elimination.
1437 //
1438 // The code below implements dead store elimination using MemorySSA. It uses
1439 // the following general approach: given a MemoryDef, walk upwards to find
1440 // clobbering MemoryDefs that may be killed by the starting def. Then check
1441 // that there are no uses that may read the location of the original MemoryDef
1442 // in between both MemoryDefs. A bit more concretely:
1443 //
1444 // For all MemoryDefs StartDef:
1445 // 1. Get the next dominating clobbering MemoryDef (DomAccess) by walking
1446 //    upwards.
1447 // 2. Check that there are no reads between DomAccess and the StartDef by
1448 //    checking all uses starting at DomAccess and walking until we see StartDef.
1449 // 3. For each found DomDef, check that:
1450 //   1. There are no barrier instructions between DomDef and StartDef (like
1451 //       throws or stores with ordering constraints).
1452 //   2. StartDef is executed whenever DomDef is executed.
1453 //   3. StartDef completely overwrites DomDef.
1454 // 4. Erase DomDef from the function and MemorySSA.
1455 
1456 // Returns true if \p M is an intrisnic that does not read or write memory.
1457 bool isNoopIntrinsic(MemoryUseOrDef *M) {
1458   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(M->getMemoryInst())) {
1459     switch (II->getIntrinsicID()) {
1460     case Intrinsic::lifetime_start:
1461     case Intrinsic::lifetime_end:
1462     case Intrinsic::invariant_end:
1463     case Intrinsic::launder_invariant_group:
1464     case Intrinsic::assume:
1465       return true;
1466     case Intrinsic::dbg_addr:
1467     case Intrinsic::dbg_declare:
1468     case Intrinsic::dbg_label:
1469     case Intrinsic::dbg_value:
1470       llvm_unreachable("Intrinsic should not be modeled in MemorySSA");
1471     default:
1472       return false;
1473     }
1474   }
1475   return false;
1476 }
1477 
1478 // Check if we can ignore \p D for DSE.
1479 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) {
1480   Instruction *DI = D->getMemoryInst();
1481   // Calls that only access inaccessible memory cannot read or write any memory
1482   // locations we consider for elimination.
1483   if (auto *CB = dyn_cast<CallBase>(DI))
1484     if (CB->onlyAccessesInaccessibleMemory())
1485       return true;
1486 
1487   // We can eliminate stores to locations not visible to the caller across
1488   // throwing instructions.
1489   if (DI->mayThrow() && !DefVisibleToCaller)
1490     return true;
1491 
1492   // We can remove the dead stores, irrespective of the fence and its ordering
1493   // (release/acquire/seq_cst). Fences only constraints the ordering of
1494   // already visible stores, it does not make a store visible to other
1495   // threads. So, skipping over a fence does not change a store from being
1496   // dead.
1497   if (isa<FenceInst>(DI))
1498     return true;
1499 
1500   // Skip intrinsics that do not really read or modify memory.
1501   if (isNoopIntrinsic(D))
1502     return true;
1503 
1504   return false;
1505 }
1506 
1507 struct DSEState {
1508   Function &F;
1509   AliasAnalysis &AA;
1510   MemorySSA &MSSA;
1511   DominatorTree &DT;
1512   PostDominatorTree &PDT;
1513   const TargetLibraryInfo &TLI;
1514 
1515   // All MemoryDefs that potentially could kill other MemDefs.
1516   SmallVector<MemoryDef *, 64> MemDefs;
1517   // Any that should be skipped as they are already deleted
1518   SmallPtrSet<MemoryAccess *, 4> SkipStores;
1519   // Keep track of all of the objects that are invisible to the caller before
1520   // the function returns.
1521   SmallPtrSet<const Value *, 16> InvisibleToCallerBeforeRet;
1522   // Keep track of all of the objects that are invisible to the caller after
1523   // the function returns.
1524   SmallPtrSet<const Value *, 16> InvisibleToCallerAfterRet;
1525   // Keep track of blocks with throwing instructions not modeled in MemorySSA.
1526   SmallPtrSet<BasicBlock *, 16> ThrowingBlocks;
1527   // Post-order numbers for each basic block. Used to figure out if memory
1528   // accesses are executed before another access.
1529   DenseMap<BasicBlock *, unsigned> PostOrderNumbers;
1530 
1531   /// Keep track of instructions (partly) overlapping with killing MemoryDefs per
1532   /// basic block.
1533   DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs;
1534 
1535   DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT,
1536            PostDominatorTree &PDT, const TargetLibraryInfo &TLI)
1537       : F(F), AA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI) {}
1538 
1539   static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA,
1540                       DominatorTree &DT, PostDominatorTree &PDT,
1541                       const TargetLibraryInfo &TLI) {
1542     DSEState State(F, AA, MSSA, DT, PDT, TLI);
1543     // Collect blocks with throwing instructions not modeled in MemorySSA and
1544     // alloc-like objects.
1545     unsigned PO = 0;
1546     for (BasicBlock *BB : post_order(&F)) {
1547       State.PostOrderNumbers[BB] = PO++;
1548       for (Instruction &I : *BB) {
1549         MemoryAccess *MA = MSSA.getMemoryAccess(&I);
1550         if (I.mayThrow() && !MA)
1551           State.ThrowingBlocks.insert(I.getParent());
1552 
1553         auto *MD = dyn_cast_or_null<MemoryDef>(MA);
1554         if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit &&
1555             (State.getLocForWriteEx(&I) || State.isMemTerminatorInst(&I)))
1556           State.MemDefs.push_back(MD);
1557 
1558         // Track whether alloca and alloca-like objects are visible in the
1559         // caller before and after the function returns. Alloca objects are
1560         // invalid in the caller, so they are neither visible before or after
1561         // the function returns.
1562         if (isa<AllocaInst>(&I)) {
1563           State.InvisibleToCallerBeforeRet.insert(&I);
1564           State.InvisibleToCallerAfterRet.insert(&I);
1565         }
1566 
1567         // For alloca-like objects we need to check if they are captured before
1568         // the function returns and if the return might capture the object.
1569         if (isAllocLikeFn(&I, &TLI)) {
1570           bool CapturesBeforeRet = PointerMayBeCaptured(&I, false, true);
1571           if (!CapturesBeforeRet) {
1572             State.InvisibleToCallerBeforeRet.insert(&I);
1573             if (!PointerMayBeCaptured(&I, true, false))
1574               State.InvisibleToCallerAfterRet.insert(&I);
1575           }
1576         }
1577       }
1578     }
1579 
1580     // Treat byval or inalloca arguments the same as Allocas, stores to them are
1581     // dead at the end of the function.
1582     for (Argument &AI : F.args())
1583       if (AI.hasPassPointeeByValueCopyAttr()) {
1584         // For byval, the caller doesn't know the address of the allocation.
1585         if (AI.hasByValAttr())
1586           State.InvisibleToCallerBeforeRet.insert(&AI);
1587         State.InvisibleToCallerAfterRet.insert(&AI);
1588       }
1589 
1590     return State;
1591   }
1592 
1593   Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const {
1594     if (!I->mayWriteToMemory())
1595       return None;
1596 
1597     if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I))
1598       return {MemoryLocation::getForDest(MTI)};
1599 
1600     if (auto *CB = dyn_cast<CallBase>(I)) {
1601       LibFunc LF;
1602       if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) {
1603         switch (LF) {
1604         case LibFunc_strcpy:
1605         case LibFunc_strncpy:
1606         case LibFunc_strcat:
1607         case LibFunc_strncat:
1608           return {MemoryLocation(CB->getArgOperand(0))};
1609         default:
1610           break;
1611         }
1612       }
1613       switch (CB->getIntrinsicID()) {
1614       case Intrinsic::init_trampoline:
1615         return {MemoryLocation(CB->getArgOperand(0))};
1616       default:
1617         break;
1618       }
1619       return None;
1620     }
1621 
1622     return MemoryLocation::getOrNone(I);
1623   }
1624 
1625   /// Returns true if \p Use completely overwrites \p DefLoc.
1626   bool isCompleteOverwrite(MemoryLocation DefLoc, Instruction *UseInst) const {
1627     // UseInst has a MemoryDef associated in MemorySSA. It's possible for a
1628     // MemoryDef to not write to memory, e.g. a volatile load is modeled as a
1629     // MemoryDef.
1630     if (!UseInst->mayWriteToMemory())
1631       return false;
1632 
1633     if (auto *CB = dyn_cast<CallBase>(UseInst))
1634       if (CB->onlyAccessesInaccessibleMemory())
1635         return false;
1636 
1637     int64_t InstWriteOffset, DepWriteOffset;
1638     auto CC = getLocForWriteEx(UseInst);
1639     const DataLayout &DL = F.getParent()->getDataLayout();
1640     return CC && isOverwrite(*CC, DefLoc, DL, TLI, DepWriteOffset,
1641                              InstWriteOffset, AA, &F) == OW_Complete;
1642   }
1643 
1644   /// Returns true if \p Def is not read before returning from the function.
1645   bool isWriteAtEndOfFunction(MemoryDef *Def) {
1646     LLVM_DEBUG(dbgs() << "  Check if def " << *Def << " ("
1647                       << *Def->getMemoryInst()
1648                       << ") is at the end the function \n");
1649 
1650     auto MaybeLoc = getLocForWriteEx(Def->getMemoryInst());
1651     if (!MaybeLoc) {
1652       LLVM_DEBUG(dbgs() << "  ... could not get location for write.\n");
1653       return false;
1654     }
1655 
1656     SmallVector<MemoryAccess *, 4> WorkList;
1657     SmallPtrSet<MemoryAccess *, 8> Visited;
1658     auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) {
1659       if (!Visited.insert(Acc).second)
1660         return;
1661       for (Use &U : Acc->uses())
1662         WorkList.push_back(cast<MemoryAccess>(U.getUser()));
1663     };
1664     PushMemUses(Def);
1665     for (unsigned I = 0; I < WorkList.size(); I++) {
1666       if (WorkList.size() >= MemorySSAScanLimit) {
1667         LLVM_DEBUG(dbgs() << "  ... hit exploration limit.\n");
1668         return false;
1669       }
1670 
1671       MemoryAccess *UseAccess = WorkList[I];
1672       if (isa<MemoryPhi>(UseAccess)) {
1673         PushMemUses(UseAccess);
1674         continue;
1675       }
1676 
1677       // TODO: Checking for aliasing is expensive. Consider reducing the amount
1678       // of times this is called and/or caching it.
1679       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1680       if (isReadClobber(*MaybeLoc, UseInst)) {
1681         LLVM_DEBUG(dbgs() << "  ... hit read clobber " << *UseInst << ".\n");
1682         return false;
1683       }
1684 
1685       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess))
1686         PushMemUses(UseDef);
1687     }
1688     return true;
1689   }
1690 
1691   /// If \p I is a memory  terminator like llvm.lifetime.end or free, return a
1692   /// pair with the MemoryLocation terminated by \p I and a boolean flag
1693   /// indicating whether \p I is a free-like call.
1694   Optional<std::pair<MemoryLocation, bool>>
1695   getLocForTerminator(Instruction *I) const {
1696     uint64_t Len;
1697     Value *Ptr;
1698     if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len),
1699                                                       m_Value(Ptr))))
1700       return {std::make_pair(MemoryLocation(Ptr, Len), false)};
1701 
1702     if (auto *CB = dyn_cast<CallBase>(I)) {
1703       if (isFreeCall(I, &TLI))
1704         return {std::make_pair(MemoryLocation(CB->getArgOperand(0)), true)};
1705     }
1706 
1707     return None;
1708   }
1709 
1710   /// Returns true if \p I is a memory terminator instruction like
1711   /// llvm.lifetime.end or free.
1712   bool isMemTerminatorInst(Instruction *I) const {
1713     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1714     return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) ||
1715            isFreeCall(I, &TLI);
1716   }
1717 
1718   /// Returns true if \p MaybeTerm is a memory terminator for the same
1719   /// underlying object as \p DefLoc.
1720   bool isMemTerminator(MemoryLocation DefLoc, Instruction *MaybeTerm) const {
1721     Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc =
1722         getLocForTerminator(MaybeTerm);
1723 
1724     if (!MaybeTermLoc)
1725       return false;
1726 
1727     // If the terminator is a free-like call, all accesses to the underlying
1728     // object can be considered terminated.
1729     if (MaybeTermLoc->second) {
1730       DataLayout DL = MaybeTerm->getParent()->getModule()->getDataLayout();
1731       DefLoc = MemoryLocation(getUnderlyingObject(DefLoc.Ptr));
1732     }
1733     return AA.isMustAlias(MaybeTermLoc->first, DefLoc);
1734   }
1735 
1736   // Returns true if \p Use may read from \p DefLoc.
1737   bool isReadClobber(MemoryLocation DefLoc, Instruction *UseInst) const {
1738     if (!UseInst->mayReadFromMemory())
1739       return false;
1740 
1741     if (auto *CB = dyn_cast<CallBase>(UseInst))
1742       if (CB->onlyAccessesInaccessibleMemory())
1743         return false;
1744 
1745     ModRefInfo MR = AA.getModRefInfo(UseInst, DefLoc);
1746     // If necessary, perform additional analysis.
1747     if (isRefSet(MR))
1748       MR = AA.callCapturesBefore(UseInst, DefLoc, &DT);
1749     return isRefSet(MR);
1750   }
1751 
1752   // Find a MemoryDef writing to \p DefLoc and dominating \p Current, with no
1753   // read access between them or on any other path to a function exit block if
1754   // \p DefLoc is not accessible after the function returns. If there is no such
1755   // MemoryDef, return None. The returned value may not (completely) overwrite
1756   // \p DefLoc. Currently we bail out when we encounter an aliasing MemoryUse
1757   // (read).
1758   Optional<MemoryAccess *>
1759   getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *Current,
1760                   MemoryLocation DefLoc, bool DefVisibleToCallerBeforeRet,
1761                   bool DefVisibleToCallerAfterRet, unsigned &ScanLimit) const {
1762     if (ScanLimit == 0) {
1763       LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1764       return None;
1765     }
1766 
1767     MemoryAccess *DomAccess;
1768     bool StepAgain;
1769     LLVM_DEBUG(dbgs() << "  trying to get dominating access for " << *Current
1770                       << "\n");
1771     // Find the next clobbering Mod access for DefLoc, starting at Current.
1772     do {
1773       StepAgain = false;
1774       // Reached TOP.
1775       if (MSSA.isLiveOnEntryDef(Current))
1776         return None;
1777 
1778       if (isa<MemoryPhi>(Current)) {
1779         DomAccess = Current;
1780         break;
1781       }
1782       MemoryUseOrDef *CurrentUD = cast<MemoryUseOrDef>(Current);
1783       // Look for access that clobber DefLoc.
1784       DomAccess = MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(CurrentUD,
1785                                                                       DefLoc);
1786       if (MSSA.isLiveOnEntryDef(DomAccess))
1787         return None;
1788 
1789       if (isa<MemoryPhi>(DomAccess))
1790         break;
1791 
1792       // Check if we can skip DomDef for DSE.
1793       MemoryDef *DomDef = dyn_cast<MemoryDef>(DomAccess);
1794       if (DomDef && canSkipDef(DomDef, DefVisibleToCallerBeforeRet)) {
1795         StepAgain = true;
1796         Current = DomDef->getDefiningAccess();
1797       }
1798 
1799     } while (StepAgain);
1800 
1801     // Accesses to objects accessible after the function returns can only be
1802     // eliminated if the access is killed along all paths to the exit. Collect
1803     // the blocks with killing (=completely overwriting MemoryDefs) and check if
1804     // they cover all paths from DomAccess to any function exit.
1805     SmallPtrSet<Instruction *, 16> KillingDefs;
1806     KillingDefs.insert(KillingDef->getMemoryInst());
1807     LLVM_DEBUG({
1808       dbgs() << "  Checking for reads of " << *DomAccess;
1809       if (isa<MemoryDef>(DomAccess))
1810         dbgs() << " (" << *cast<MemoryDef>(DomAccess)->getMemoryInst() << ")\n";
1811       else
1812         dbgs() << ")\n";
1813     });
1814 
1815     SmallSetVector<MemoryAccess *, 32> WorkList;
1816     auto PushMemUses = [&WorkList](MemoryAccess *Acc) {
1817       for (Use &U : Acc->uses())
1818         WorkList.insert(cast<MemoryAccess>(U.getUser()));
1819     };
1820     PushMemUses(DomAccess);
1821 
1822     // Check if DomDef may be read.
1823     for (unsigned I = 0; I < WorkList.size(); I++) {
1824       MemoryAccess *UseAccess = WorkList[I];
1825 
1826       LLVM_DEBUG(dbgs() << "   " << *UseAccess);
1827       // Bail out if the number of accesses to check exceeds the scan limit.
1828       if (ScanLimit < (WorkList.size() - I)) {
1829         LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1830         return None;
1831       }
1832       --ScanLimit;
1833 
1834       if (isa<MemoryPhi>(UseAccess)) {
1835         if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) {
1836               return DT.properlyDominates(KI->getParent(),
1837                                           UseAccess->getBlock());
1838             })) {
1839           LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n");
1840           continue;
1841         }
1842         LLVM_DEBUG(dbgs() << "\n    ... adding PHI uses\n");
1843         PushMemUses(UseAccess);
1844         continue;
1845       }
1846 
1847       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1848       LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n");
1849 
1850       if (any_of(KillingDefs, [this, UseInst](Instruction *KI) {
1851             return DT.dominates(KI, UseInst);
1852           })) {
1853         LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n");
1854         continue;
1855       }
1856 
1857       if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess))) {
1858         LLVM_DEBUG(dbgs() << "    ... adding uses of intrinsic\n");
1859         PushMemUses(UseAccess);
1860         continue;
1861       }
1862 
1863       // A memory terminator kills all preceeding MemoryDefs and all succeeding
1864       // MemoryAccesses. We do not have to check it's users.
1865       if (isMemTerminator(DefLoc, UseInst))
1866         continue;
1867 
1868       // Uses which may read the original MemoryDef mean we cannot eliminate the
1869       // original MD. Stop walk.
1870       if (isReadClobber(DefLoc, UseInst)) {
1871         LLVM_DEBUG(dbgs() << "    ... found read clobber\n");
1872         return None;
1873       }
1874 
1875       // For the KillingDef and DomAccess we only have to check if it reads the
1876       // memory location.
1877       // TODO: It would probably be better to check for self-reads before
1878       // calling the function.
1879       if (KillingDef == UseAccess || DomAccess == UseAccess) {
1880         LLVM_DEBUG(dbgs() << "    ... skipping killing def/dom access\n");
1881         continue;
1882       }
1883 
1884       // Check all uses for MemoryDefs, except for defs completely overwriting
1885       // the original location. Otherwise we have to check uses of *all*
1886       // MemoryDefs we discover, including non-aliasing ones. Otherwise we might
1887       // miss cases like the following
1888       //   1 = Def(LoE) ; <----- DomDef stores [0,1]
1889       //   2 = Def(1)   ; (2, 1) = NoAlias,   stores [2,3]
1890       //   Use(2)       ; MayAlias 2 *and* 1, loads [0, 3].
1891       //                  (The Use points to the *first* Def it may alias)
1892       //   3 = Def(1)   ; <---- Current  (3, 2) = NoAlias, (3,1) = MayAlias,
1893       //                  stores [0,1]
1894       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) {
1895         if (isCompleteOverwrite(DefLoc, UseInst)) {
1896           if (DefVisibleToCallerAfterRet && UseAccess != DomAccess) {
1897             BasicBlock *MaybeKillingBlock = UseInst->getParent();
1898             if (PostOrderNumbers.find(MaybeKillingBlock)->second <
1899                 PostOrderNumbers.find(DomAccess->getBlock())->second) {
1900 
1901               LLVM_DEBUG(dbgs()
1902                          << "    ... found killing def " << *UseInst << "\n");
1903               KillingDefs.insert(UseInst);
1904             }
1905           }
1906         } else
1907           PushMemUses(UseDef);
1908       }
1909     }
1910 
1911     // For accesses to locations visible after the function returns, make sure
1912     // that the location is killed (=overwritten) along all paths from DomAccess
1913     // to the exit.
1914     if (DefVisibleToCallerAfterRet) {
1915       SmallPtrSet<BasicBlock *, 16> KillingBlocks;
1916       for (Instruction *KD : KillingDefs)
1917         KillingBlocks.insert(KD->getParent());
1918       assert(!KillingBlocks.empty() &&
1919              "Expected at least a single killing block");
1920 
1921       // Find the common post-dominator of all killing blocks.
1922       BasicBlock *CommonPred = *KillingBlocks.begin();
1923       for (auto I = std::next(KillingBlocks.begin()), E = KillingBlocks.end();
1924            I != E; I++) {
1925         if (!CommonPred)
1926           break;
1927         CommonPred = PDT.findNearestCommonDominator(CommonPred, *I);
1928       }
1929 
1930       // If CommonPred is in the set of killing blocks, just check if it
1931       // post-dominates DomAccess.
1932       if (KillingBlocks.count(CommonPred)) {
1933         if (PDT.dominates(CommonPred, DomAccess->getBlock()))
1934           return {DomAccess};
1935         return None;
1936       }
1937 
1938       // If the common post-dominator does not post-dominate DomAccess, there
1939       // is a path from DomAccess to an exit not going through a killing block.
1940       if (PDT.dominates(CommonPred, DomAccess->getBlock())) {
1941         SetVector<BasicBlock *> WorkList;
1942 
1943         // DomAccess's post-order number provides an upper bound of the blocks
1944         // on a path starting at DomAccess.
1945         unsigned UpperBound =
1946             PostOrderNumbers.find(DomAccess->getBlock())->second;
1947 
1948         // If CommonPred is null, there are multiple exits from the function.
1949         // They all have to be added to the worklist.
1950         if (CommonPred)
1951           WorkList.insert(CommonPred);
1952         else
1953           for (BasicBlock *R : PDT.roots())
1954             WorkList.insert(R);
1955 
1956         NumCFGTries++;
1957         // Check if all paths starting from an exit node go through one of the
1958         // killing blocks before reaching DomAccess.
1959         for (unsigned I = 0; I < WorkList.size(); I++) {
1960           NumCFGChecks++;
1961           BasicBlock *Current = WorkList[I];
1962           if (KillingBlocks.count(Current))
1963             continue;
1964           if (Current == DomAccess->getBlock())
1965             return None;
1966 
1967           // DomAccess is reachable from the entry, so we don't have to explore
1968           // unreachable blocks further.
1969           if (!DT.isReachableFromEntry(Current))
1970             continue;
1971 
1972           unsigned CPO = PostOrderNumbers.find(Current)->second;
1973           // Current block is not on a path starting at DomAccess.
1974           if (CPO > UpperBound)
1975             continue;
1976           for (BasicBlock *Pred : predecessors(Current))
1977             WorkList.insert(Pred);
1978 
1979           if (WorkList.size() >= MemorySSAPathCheckLimit)
1980             return None;
1981         }
1982         NumCFGSuccess++;
1983         return {DomAccess};
1984       }
1985       return None;
1986     }
1987 
1988     // No aliasing MemoryUses of DomAccess found, DomAccess is potentially dead.
1989     return {DomAccess};
1990   }
1991 
1992   // Delete dead memory defs
1993   void deleteDeadInstruction(Instruction *SI) {
1994     MemorySSAUpdater Updater(&MSSA);
1995     SmallVector<Instruction *, 32> NowDeadInsts;
1996     NowDeadInsts.push_back(SI);
1997     --NumFastOther;
1998 
1999     while (!NowDeadInsts.empty()) {
2000       Instruction *DeadInst = NowDeadInsts.pop_back_val();
2001       ++NumFastOther;
2002 
2003       // Try to preserve debug information attached to the dead instruction.
2004       salvageDebugInfo(*DeadInst);
2005       salvageKnowledge(DeadInst);
2006 
2007       // Remove the Instruction from MSSA.
2008       if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) {
2009         if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) {
2010           SkipStores.insert(MD);
2011         }
2012         Updater.removeMemoryAccess(MA);
2013       }
2014 
2015       auto I = IOLs.find(DeadInst->getParent());
2016       if (I != IOLs.end())
2017         I->second.erase(DeadInst);
2018       // Remove its operands
2019       for (Use &O : DeadInst->operands())
2020         if (Instruction *OpI = dyn_cast<Instruction>(O)) {
2021           O = nullptr;
2022           if (isInstructionTriviallyDead(OpI, &TLI))
2023             NowDeadInsts.push_back(OpI);
2024         }
2025 
2026       DeadInst->eraseFromParent();
2027     }
2028   }
2029 
2030   // Check for any extra throws between SI and NI that block DSE.  This only
2031   // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may
2032   // throw are handled during the walk from one def to the next.
2033   bool mayThrowBetween(Instruction *SI, Instruction *NI,
2034                        const Value *SILocUnd) const {
2035     // First see if we can ignore it by using the fact that SI is an
2036     // alloca/alloca like object that is not visible to the caller during
2037     // execution of the function.
2038     if (SILocUnd && InvisibleToCallerBeforeRet.count(SILocUnd))
2039       return false;
2040 
2041     if (SI->getParent() == NI->getParent())
2042       return ThrowingBlocks.count(SI->getParent());
2043     return !ThrowingBlocks.empty();
2044   }
2045 
2046   // Check if \p NI acts as a DSE barrier for \p SI. The following instructions
2047   // act as barriers:
2048   //  * A memory instruction that may throw and \p SI accesses a non-stack
2049   //  object.
2050   //  * Atomic stores stronger that monotonic.
2051   bool isDSEBarrier(const Value *SILocUnd, Instruction *NI) const {
2052     // If NI may throw it acts as a barrier, unless we are to an alloca/alloca
2053     // like object that does not escape.
2054     if (NI->mayThrow() && !InvisibleToCallerBeforeRet.count(SILocUnd))
2055       return true;
2056 
2057     // If NI is an atomic load/store stronger than monotonic, do not try to
2058     // eliminate/reorder it.
2059     if (NI->isAtomic()) {
2060       if (auto *LI = dyn_cast<LoadInst>(NI))
2061         return isStrongerThanMonotonic(LI->getOrdering());
2062       if (auto *SI = dyn_cast<StoreInst>(NI))
2063         return isStrongerThanMonotonic(SI->getOrdering());
2064       if (auto *ARMW = dyn_cast<AtomicRMWInst>(NI))
2065         return isStrongerThanMonotonic(ARMW->getOrdering());
2066       if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(NI))
2067         return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) ||
2068                isStrongerThanMonotonic(CmpXchg->getFailureOrdering());
2069       llvm_unreachable("other instructions should be skipped in MemorySSA");
2070     }
2071     return false;
2072   }
2073 
2074   /// Eliminate writes to objects that are not visible in the caller and are not
2075   /// accessed before returning from the function.
2076   bool eliminateDeadWritesAtEndOfFunction() {
2077     bool MadeChange = false;
2078     LLVM_DEBUG(
2079         dbgs()
2080         << "Trying to eliminate MemoryDefs at the end of the function\n");
2081     for (int I = MemDefs.size() - 1; I >= 0; I--) {
2082       MemoryDef *Def = MemDefs[I];
2083       if (SkipStores.find(Def) != SkipStores.end() ||
2084           !isRemovable(Def->getMemoryInst()))
2085         continue;
2086 
2087       Instruction *DefI = Def->getMemoryInst();
2088       SmallVector<const Value *, 4> Pointers;
2089       auto DefLoc = getLocForWriteEx(DefI);
2090       if (!DefLoc)
2091         continue;
2092       getUnderlyingObjects(DefLoc->Ptr, Pointers);
2093 
2094       bool CanKill = true;
2095       for (const Value *Pointer : Pointers) {
2096         if (!InvisibleToCallerAfterRet.count(Pointer)) {
2097           CanKill = false;
2098           break;
2099         }
2100       }
2101 
2102       if (CanKill && isWriteAtEndOfFunction(Def)) {
2103         // See through pointer-to-pointer bitcasts
2104         LLVM_DEBUG(dbgs() << "   ... MemoryDef is not accessed until the end "
2105                              "of the function\n");
2106         deleteDeadInstruction(DefI);
2107         ++NumFastStores;
2108         MadeChange = true;
2109       }
2110     }
2111     return MadeChange;
2112   }
2113 
2114   /// \returns true if \p Def is a no-op store, either because it
2115   /// directly stores back a loaded value or stores zero to a calloced object.
2116   bool storeIsNoop(MemoryDef *Def, MemoryLocation DefLoc, const Value *DefUO) {
2117     StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst());
2118     if (!Store)
2119       return false;
2120 
2121     if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) {
2122       if (LoadI->getPointerOperand() == Store->getOperand(1)) {
2123         auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess();
2124         // If both accesses share the same defining access, no instructions
2125         // between them can modify the memory location.
2126         return LoadAccess == Def->getDefiningAccess();
2127       }
2128     }
2129 
2130     Constant *StoredConstant = dyn_cast<Constant>(Store->getOperand(0));
2131     if (StoredConstant && StoredConstant->isNullValue()) {
2132       auto *DefUOInst = dyn_cast<Instruction>(DefUO);
2133       if (DefUOInst && isCallocLikeFn(DefUOInst, &TLI)) {
2134         auto *UnderlyingDef = cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst));
2135         // If UnderlyingDef is the clobbering access of Def, no instructions
2136         // between them can modify the memory location.
2137         auto *ClobberDef =
2138             MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def);
2139         return UnderlyingDef == ClobberDef;
2140       }
2141     }
2142     return false;
2143   }
2144 };
2145 
2146 bool eliminateDeadStoresMemorySSA(Function &F, AliasAnalysis &AA,
2147                                   MemorySSA &MSSA, DominatorTree &DT,
2148                                   PostDominatorTree &PDT,
2149                                   const TargetLibraryInfo &TLI) {
2150   const DataLayout &DL = F.getParent()->getDataLayout();
2151   bool MadeChange = false;
2152 
2153   DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI);
2154   // For each store:
2155   for (unsigned I = 0; I < State.MemDefs.size(); I++) {
2156     MemoryDef *KillingDef = State.MemDefs[I];
2157     if (State.SkipStores.count(KillingDef))
2158       continue;
2159     Instruction *SI = KillingDef->getMemoryInst();
2160 
2161     auto MaybeSILoc = State.getLocForWriteEx(SI);
2162     if (State.isMemTerminatorInst(SI))
2163       MaybeSILoc = State.getLocForTerminator(SI).map(
2164           [](const std::pair<MemoryLocation, bool> &P) { return P.first; });
2165     else
2166       MaybeSILoc = State.getLocForWriteEx(SI);
2167 
2168     if (!MaybeSILoc) {
2169       LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for "
2170                         << *SI << "\n");
2171       continue;
2172     }
2173     MemoryLocation SILoc = *MaybeSILoc;
2174     assert(SILoc.Ptr && "SILoc should not be null");
2175     const Value *SILocUnd = getUnderlyingObject(SILoc.Ptr);
2176 
2177     // Check if the store is a no-op.
2178     if (isRemovable(SI) && State.storeIsNoop(KillingDef, SILoc, SILocUnd)) {
2179       LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n  DEAD: " << *SI << '\n');
2180       State.deleteDeadInstruction(SI);
2181       NumRedundantStores++;
2182       MadeChange = true;
2183       continue;
2184     }
2185 
2186     Instruction *DefObj =
2187         const_cast<Instruction *>(dyn_cast<Instruction>(SILocUnd));
2188     bool DefVisibleToCallerBeforeRet =
2189         !State.InvisibleToCallerBeforeRet.count(SILocUnd);
2190     bool DefVisibleToCallerAfterRet =
2191         !State.InvisibleToCallerAfterRet.count(SILocUnd);
2192     if (DefObj && isAllocLikeFn(DefObj, &TLI)) {
2193       if (DefVisibleToCallerBeforeRet)
2194         DefVisibleToCallerBeforeRet =
2195             PointerMayBeCapturedBefore(DefObj, false, true, SI, &DT);
2196     }
2197 
2198     MemoryAccess *Current = KillingDef;
2199     LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by "
2200                       << *KillingDef << " (" << *SI << ")\n");
2201 
2202     unsigned ScanLimit = MemorySSAScanLimit;
2203     // Worklist of MemoryAccesses that may be killed by KillingDef.
2204     SetVector<MemoryAccess *> ToCheck;
2205     ToCheck.insert(KillingDef->getDefiningAccess());
2206 
2207     // Check if MemoryAccesses in the worklist are killed by KillingDef.
2208     for (unsigned I = 0; I < ToCheck.size(); I++) {
2209       Current = ToCheck[I];
2210       if (State.SkipStores.count(Current))
2211         continue;
2212 
2213       Optional<MemoryAccess *> Next = State.getDomMemoryDef(
2214           KillingDef, Current, SILoc, DefVisibleToCallerBeforeRet,
2215           DefVisibleToCallerAfterRet, ScanLimit);
2216 
2217       if (!Next) {
2218         LLVM_DEBUG(dbgs() << "  finished walk\n");
2219         continue;
2220       }
2221 
2222       MemoryAccess *DomAccess = *Next;
2223       LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DomAccess);
2224       if (isa<MemoryPhi>(DomAccess)) {
2225         LLVM_DEBUG(dbgs() << "\n  ... adding incoming values to worklist\n");
2226         for (Value *V : cast<MemoryPhi>(DomAccess)->incoming_values()) {
2227           MemoryAccess *IncomingAccess = cast<MemoryAccess>(V);
2228           BasicBlock *IncomingBlock = IncomingAccess->getBlock();
2229           BasicBlock *PhiBlock = DomAccess->getBlock();
2230 
2231           // We only consider incoming MemoryAccesses that come before the
2232           // MemoryPhi. Otherwise we could discover candidates that do not
2233           // strictly dominate our starting def.
2234           if (State.PostOrderNumbers[IncomingBlock] >
2235               State.PostOrderNumbers[PhiBlock])
2236             ToCheck.insert(IncomingAccess);
2237         }
2238         continue;
2239       }
2240       MemoryDef *NextDef = dyn_cast<MemoryDef>(DomAccess);
2241       Instruction *NI = NextDef->getMemoryInst();
2242       LLVM_DEBUG(dbgs() << " (" << *NI << ")\n");
2243 
2244       // Before we try to remove anything, check for any extra throwing
2245       // instructions that block us from DSEing
2246       if (State.mayThrowBetween(SI, NI, SILocUnd)) {
2247         LLVM_DEBUG(dbgs() << "  ... skip, may throw!\n");
2248         break;
2249       }
2250 
2251       // Check for anything that looks like it will be a barrier to further
2252       // removal
2253       if (State.isDSEBarrier(SILocUnd, NI)) {
2254         LLVM_DEBUG(dbgs() << "  ... skip, barrier\n");
2255         continue;
2256       }
2257 
2258       ToCheck.insert(NextDef->getDefiningAccess());
2259 
2260       if (!hasAnalyzableMemoryWrite(NI, TLI)) {
2261         LLVM_DEBUG(dbgs() << "  ... skip, cannot analyze def\n");
2262         continue;
2263       }
2264 
2265       if (!isRemovable(NI)) {
2266         LLVM_DEBUG(dbgs() << "  ... skip, cannot remove def\n");
2267         continue;
2268       }
2269 
2270       if (!DebugCounter::shouldExecute(MemorySSACounter))
2271         continue;
2272 
2273       MemoryLocation NILoc = *State.getLocForWriteEx(NI);
2274 
2275       if (State.isMemTerminatorInst(SI)) {
2276         const Value *NIUnd = getUnderlyingObject(NILoc.Ptr);
2277         if (!SILocUnd || SILocUnd != NIUnd)
2278           continue;
2279         LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *NI
2280                           << "\n  KILLER: " << *SI << '\n');
2281         State.deleteDeadInstruction(NI);
2282         ++NumFastStores;
2283         MadeChange = true;
2284       } else {
2285         // Check if NI overwrites SI.
2286         int64_t InstWriteOffset, DepWriteOffset;
2287         OverwriteResult OR = isOverwrite(SILoc, NILoc, DL, TLI, DepWriteOffset,
2288                                          InstWriteOffset, State.AA, &F);
2289         if (OR == OW_MaybePartial) {
2290           auto Iter = State.IOLs.insert(
2291               std::make_pair<BasicBlock *, InstOverlapIntervalsTy>(
2292                   NI->getParent(), InstOverlapIntervalsTy()));
2293           auto &IOL = Iter.first->second;
2294           OR = isPartialOverwrite(SILoc, NILoc, DepWriteOffset, InstWriteOffset,
2295                                   NI, IOL);
2296         }
2297 
2298         if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) {
2299           auto *Earlier = dyn_cast<StoreInst>(NI);
2300           auto *Later = dyn_cast<StoreInst>(SI);
2301           // We are re-using tryToMergePartialOverlappingStores, which requires
2302           // Earlier to domiante Later.
2303           // TODO: implement tryToMergeParialOverlappingStores using MemorySSA.
2304           if (Earlier && Later && DT.dominates(Earlier, Later)) {
2305             if (Constant *Merged = tryToMergePartialOverlappingStores(
2306                     Earlier, Later, InstWriteOffset, DepWriteOffset, DL, &AA,
2307                     &DT)) {
2308 
2309               // Update stored value of earlier store to merged constant.
2310               Earlier->setOperand(0, Merged);
2311               ++NumModifiedStores;
2312               MadeChange = true;
2313 
2314               // Remove later store and remove any outstanding overlap intervals
2315               // for the updated store.
2316               State.deleteDeadInstruction(Later);
2317               auto I = State.IOLs.find(Earlier->getParent());
2318               if (I != State.IOLs.end())
2319                 I->second.erase(Earlier);
2320               break;
2321             }
2322           }
2323         }
2324 
2325         if (OR == OW_Complete) {
2326           LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *NI
2327                             << "\n  KILLER: " << *SI << '\n');
2328           State.deleteDeadInstruction(NI);
2329           ++NumFastStores;
2330           MadeChange = true;
2331         }
2332       }
2333     }
2334   }
2335 
2336   if (EnablePartialOverwriteTracking)
2337     for (auto &KV : State.IOLs)
2338       MadeChange |= removePartiallyOverlappedStores(DL, KV.second);
2339 
2340   MadeChange |= State.eliminateDeadWritesAtEndOfFunction();
2341   return MadeChange;
2342 }
2343 } // end anonymous namespace
2344 
2345 //===----------------------------------------------------------------------===//
2346 // DSE Pass
2347 //===----------------------------------------------------------------------===//
2348 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
2349   AliasAnalysis &AA = AM.getResult<AAManager>(F);
2350   const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2351   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
2352 
2353   bool Changed = false;
2354   if (EnableMemorySSA) {
2355     MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2356     PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
2357 
2358     Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI);
2359   } else {
2360     MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
2361 
2362     Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI);
2363   }
2364 
2365 #ifdef LLVM_ENABLE_STATS
2366   if (AreStatisticsEnabled())
2367     for (auto &I : instructions(F))
2368       NumRemainingStores += isa<StoreInst>(&I);
2369 #endif
2370 
2371   if (!Changed)
2372     return PreservedAnalyses::all();
2373 
2374   PreservedAnalyses PA;
2375   PA.preserveSet<CFGAnalyses>();
2376   PA.preserve<GlobalsAA>();
2377   if (EnableMemorySSA)
2378     PA.preserve<MemorySSAAnalysis>();
2379   else
2380     PA.preserve<MemoryDependenceAnalysis>();
2381   return PA;
2382 }
2383 
2384 namespace {
2385 
2386 /// A legacy pass for the legacy pass manager that wraps \c DSEPass.
2387 class DSELegacyPass : public FunctionPass {
2388 public:
2389   static char ID; // Pass identification, replacement for typeid
2390 
2391   DSELegacyPass() : FunctionPass(ID) {
2392     initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
2393   }
2394 
2395   bool runOnFunction(Function &F) override {
2396     if (skipFunction(F))
2397       return false;
2398 
2399     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2400     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2401     const TargetLibraryInfo &TLI =
2402         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2403 
2404     bool Changed = false;
2405     if (EnableMemorySSA) {
2406       MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2407       PostDominatorTree &PDT =
2408           getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
2409 
2410       Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI);
2411     } else {
2412       MemoryDependenceResults &MD =
2413           getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
2414 
2415       Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI);
2416     }
2417 
2418 #ifdef LLVM_ENABLE_STATS
2419     if (AreStatisticsEnabled())
2420       for (auto &I : instructions(F))
2421         NumRemainingStores += isa<StoreInst>(&I);
2422 #endif
2423 
2424     return Changed;
2425   }
2426 
2427   void getAnalysisUsage(AnalysisUsage &AU) const override {
2428     AU.setPreservesCFG();
2429     AU.addRequired<AAResultsWrapperPass>();
2430     AU.addRequired<TargetLibraryInfoWrapperPass>();
2431     AU.addPreserved<GlobalsAAWrapperPass>();
2432     AU.addRequired<DominatorTreeWrapperPass>();
2433     AU.addPreserved<DominatorTreeWrapperPass>();
2434 
2435     if (EnableMemorySSA) {
2436       AU.addRequired<PostDominatorTreeWrapperPass>();
2437       AU.addRequired<MemorySSAWrapperPass>();
2438       AU.addPreserved<PostDominatorTreeWrapperPass>();
2439       AU.addPreserved<MemorySSAWrapperPass>();
2440     } else {
2441       AU.addRequired<MemoryDependenceWrapperPass>();
2442       AU.addPreserved<MemoryDependenceWrapperPass>();
2443     }
2444   }
2445 };
2446 
2447 } // end anonymous namespace
2448 
2449 char DSELegacyPass::ID = 0;
2450 
2451 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
2452                       false)
2453 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2454 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
2455 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2456 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2457 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2458 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2459 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2460 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
2461                     false)
2462 
2463 FunctionPass *llvm::createDeadStoreEliminationPass() {
2464   return new DSELegacyPass();
2465 }
2466