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