1 //===- DeadStoreElimination.cpp - MemorySSA Backed 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 // The code below implements dead store elimination using MemorySSA. It uses
10 // the following general approach: given a MemoryDef, walk upwards to find
11 // clobbering MemoryDefs that may be killed by the starting def. Then check
12 // that there are no uses that may read the location of the original MemoryDef
13 // in between both MemoryDefs. A bit more concretely:
14 //
15 // For all MemoryDefs StartDef:
16 // 1. Get the next dominating clobbering MemoryDef (MaybeDeadAccess) by walking
17 //    upwards.
18 // 2. Check that there are no reads between MaybeDeadAccess and the StartDef by
19 //    checking all uses starting at MaybeDeadAccess and walking until we see
20 //    StartDef.
21 // 3. For each found CurrentDef, check that:
22 //   1. There are no barrier instructions between CurrentDef and StartDef (like
23 //       throws or stores with ordering constraints).
24 //   2. StartDef is executed whenever CurrentDef is executed.
25 //   3. StartDef completely overwrites CurrentDef.
26 // 4. Erase CurrentDef from the function and MemorySSA.
27 //
28 //===----------------------------------------------------------------------===//
29 
30 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/MapVector.h"
34 #include "llvm/ADT/PostOrderIterator.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Analysis/AliasAnalysis.h"
41 #include "llvm/Analysis/CaptureTracking.h"
42 #include "llvm/Analysis/GlobalsModRef.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Analysis/MemoryBuiltins.h"
45 #include "llvm/Analysis/MemoryLocation.h"
46 #include "llvm/Analysis/MemorySSA.h"
47 #include "llvm/Analysis/MemorySSAUpdater.h"
48 #include "llvm/Analysis/MustExecute.h"
49 #include "llvm/Analysis/PostDominators.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/Argument.h"
53 #include "llvm/IR/BasicBlock.h"
54 #include "llvm/IR/Constant.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstIterator.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/PassManager.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/InitializePasses.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/DebugCounter.h"
77 #include "llvm/Support/ErrorHandling.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Transforms/Scalar.h"
81 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
82 #include "llvm/Transforms/Utils/BuildLibCalls.h"
83 #include "llvm/Transforms/Utils/Local.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cstddef>
87 #include <cstdint>
88 #include <iterator>
89 #include <map>
90 #include <utility>
91 
92 using namespace llvm;
93 using namespace PatternMatch;
94 
95 #define DEBUG_TYPE "dse"
96 
97 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE");
98 STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
99 STATISTIC(NumFastStores, "Number of stores deleted");
100 STATISTIC(NumFastOther, "Number of other instrs removed");
101 STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
102 STATISTIC(NumModifiedStores, "Number of stores modified");
103 STATISTIC(NumCFGChecks, "Number of stores modified");
104 STATISTIC(NumCFGTries, "Number of stores modified");
105 STATISTIC(NumCFGSuccess, "Number of stores modified");
106 STATISTIC(NumGetDomMemoryDefPassed,
107           "Number of times a valid candidate is returned from getDomMemoryDef");
108 STATISTIC(NumDomMemDefChecks,
109           "Number iterations check for reads in getDomMemoryDef");
110 
111 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa",
112               "Controls which MemoryDefs are eliminated.");
113 
114 static cl::opt<bool>
115 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking",
116   cl::init(true), cl::Hidden,
117   cl::desc("Enable partial-overwrite tracking in DSE"));
118 
119 static cl::opt<bool>
120 EnablePartialStoreMerging("enable-dse-partial-store-merging",
121   cl::init(true), cl::Hidden,
122   cl::desc("Enable partial store merging in DSE"));
123 
124 static cl::opt<unsigned>
125     MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden,
126                        cl::desc("The number of memory instructions to scan for "
127                                 "dead store elimination (default = 150)"));
128 static cl::opt<unsigned> MemorySSAUpwardsStepLimit(
129     "dse-memoryssa-walklimit", cl::init(90), cl::Hidden,
130     cl::desc("The maximum number of steps while walking upwards to find "
131              "MemoryDefs that may be killed (default = 90)"));
132 
133 static cl::opt<unsigned> MemorySSAPartialStoreLimit(
134     "dse-memoryssa-partial-store-limit", cl::init(5), cl::Hidden,
135     cl::desc("The maximum number candidates that only partially overwrite the "
136              "killing MemoryDef to consider"
137              " (default = 5)"));
138 
139 static cl::opt<unsigned> MemorySSADefsPerBlockLimit(
140     "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden,
141     cl::desc("The number of MemoryDefs we consider as candidates to eliminated "
142              "other stores per basic block (default = 5000)"));
143 
144 static cl::opt<unsigned> MemorySSASameBBStepCost(
145     "dse-memoryssa-samebb-cost", cl::init(1), cl::Hidden,
146     cl::desc(
147         "The cost of a step in the same basic block as the killing MemoryDef"
148         "(default = 1)"));
149 
150 static cl::opt<unsigned>
151     MemorySSAOtherBBStepCost("dse-memoryssa-otherbb-cost", cl::init(5),
152                              cl::Hidden,
153                              cl::desc("The cost of a step in a different basic "
154                                       "block than the killing MemoryDef"
155                                       "(default = 5)"));
156 
157 static cl::opt<unsigned> MemorySSAPathCheckLimit(
158     "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden,
159     cl::desc("The maximum number of blocks to check when trying to prove that "
160              "all paths to an exit go through a killing block (default = 50)"));
161 
162 //===----------------------------------------------------------------------===//
163 // Helper functions
164 //===----------------------------------------------------------------------===//
165 using OverlapIntervalsTy = std::map<int64_t, int64_t>;
166 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>;
167 
168 /// Does this instruction write some memory?  This only returns true for things
169 /// that we can analyze with other helpers below.
170 static bool hasAnalyzableMemoryWrite(Instruction *I,
171                                      const TargetLibraryInfo &TLI) {
172   if (isa<StoreInst>(I))
173     return true;
174   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
175     switch (II->getIntrinsicID()) {
176     default:
177       return false;
178     case Intrinsic::memset:
179     case Intrinsic::memmove:
180     case Intrinsic::memcpy:
181     case Intrinsic::memcpy_inline:
182     case Intrinsic::memcpy_element_unordered_atomic:
183     case Intrinsic::memmove_element_unordered_atomic:
184     case Intrinsic::memset_element_unordered_atomic:
185     case Intrinsic::init_trampoline:
186     case Intrinsic::lifetime_end:
187     case Intrinsic::masked_store:
188       return true;
189     }
190   }
191   if (auto *CB = dyn_cast<CallBase>(I)) {
192     LibFunc LF;
193     if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) {
194       switch (LF) {
195       case LibFunc_strcpy:
196       case LibFunc_strncpy:
197       case LibFunc_strcat:
198       case LibFunc_strncat:
199         return true;
200       default:
201         return false;
202       }
203     }
204   }
205   return false;
206 }
207 
208 /// If the value of this instruction and the memory it writes to is unused, may
209 /// we delete this instruction?
210 static bool isRemovable(Instruction *I) {
211   // Don't remove volatile/atomic stores.
212   if (StoreInst *SI = dyn_cast<StoreInst>(I))
213     return SI->isUnordered();
214 
215   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
216     switch (II->getIntrinsicID()) {
217     default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate");
218     case Intrinsic::lifetime_end:
219       // Never remove dead lifetime_end's, e.g. because it is followed by a
220       // free.
221       return false;
222     case Intrinsic::init_trampoline:
223       // Always safe to remove init_trampoline.
224       return true;
225     case Intrinsic::memset:
226     case Intrinsic::memmove:
227     case Intrinsic::memcpy:
228     case Intrinsic::memcpy_inline:
229       // Don't remove volatile memory intrinsics.
230       return !cast<MemIntrinsic>(II)->isVolatile();
231     case Intrinsic::memcpy_element_unordered_atomic:
232     case Intrinsic::memmove_element_unordered_atomic:
233     case Intrinsic::memset_element_unordered_atomic:
234     case Intrinsic::masked_store:
235       return true;
236     }
237   }
238 
239   // note: only get here for calls with analyzable writes - i.e. libcalls
240   if (auto *CB = dyn_cast<CallBase>(I))
241     return CB->use_empty();
242 
243   return false;
244 }
245 
246 /// Returns true if the end of this instruction can be safely shortened in
247 /// length.
248 static bool isShortenableAtTheEnd(Instruction *I) {
249   // Don't shorten stores for now
250   if (isa<StoreInst>(I))
251     return false;
252 
253   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
254     switch (II->getIntrinsicID()) {
255       default: return false;
256       case Intrinsic::memset:
257       case Intrinsic::memcpy:
258       case Intrinsic::memcpy_element_unordered_atomic:
259       case Intrinsic::memset_element_unordered_atomic:
260         // Do shorten memory intrinsics.
261         // FIXME: Add memmove if it's also safe to transform.
262         return true;
263     }
264   }
265 
266   // Don't shorten libcalls calls for now.
267 
268   return false;
269 }
270 
271 /// Returns true if the beginning of this instruction can be safely shortened
272 /// in length.
273 static bool isShortenableAtTheBeginning(Instruction *I) {
274   // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
275   // easily done by offsetting the source address.
276   return isa<AnyMemSetInst>(I);
277 }
278 
279 static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
280                                const TargetLibraryInfo &TLI,
281                                const Function *F) {
282   uint64_t Size;
283   ObjectSizeOpts Opts;
284   Opts.NullIsUnknownSize = NullPointerIsDefined(F);
285 
286   if (getObjectSize(V, Size, DL, &TLI, Opts))
287     return Size;
288   return MemoryLocation::UnknownSize;
289 }
290 
291 namespace {
292 
293 enum OverwriteResult {
294   OW_Begin,
295   OW_Complete,
296   OW_End,
297   OW_PartialEarlierWithFullLater,
298   OW_MaybePartial,
299   OW_Unknown
300 };
301 
302 } // end anonymous namespace
303 
304 /// Check if two instruction are masked stores that completely
305 /// overwrite one another. More specifically, \p KillingI has to
306 /// overwrite \p DeadI.
307 static OverwriteResult isMaskedStoreOverwrite(const Instruction *KillingI,
308                                               const Instruction *DeadI,
309                                               BatchAAResults &AA) {
310   const auto *KillingII = dyn_cast<IntrinsicInst>(KillingI);
311   const auto *DeadII = dyn_cast<IntrinsicInst>(DeadI);
312   if (KillingII == nullptr || DeadII == nullptr)
313     return OW_Unknown;
314   if (KillingII->getIntrinsicID() != Intrinsic::masked_store ||
315       DeadII->getIntrinsicID() != Intrinsic::masked_store)
316     return OW_Unknown;
317   // Pointers.
318   Value *KillingPtr = KillingII->getArgOperand(1)->stripPointerCasts();
319   Value *DeadPtr = DeadII->getArgOperand(1)->stripPointerCasts();
320   if (KillingPtr != DeadPtr && !AA.isMustAlias(KillingPtr, DeadPtr))
321     return OW_Unknown;
322   // Masks.
323   // TODO: check that KillingII's mask is a superset of the DeadII's mask.
324   if (KillingII->getArgOperand(3) != DeadII->getArgOperand(3))
325     return OW_Unknown;
326   return OW_Complete;
327 }
328 
329 /// Return 'OW_Complete' if a store to the 'KillingLoc' location completely
330 /// overwrites a store to the 'DeadLoc' location, 'OW_End' if the end of the
331 /// 'DeadLoc' location is completely overwritten by 'KillingLoc', 'OW_Begin'
332 /// if the beginning of the 'DeadLoc' location is overwritten by 'KillingLoc'.
333 /// 'OW_PartialEarlierWithFullLater' means that a dead (big) store was
334 /// overwritten by a killing (smaller) store which doesn't write outside the big
335 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
336 /// NOTE: This function must only be called if both \p KillingLoc and \p
337 /// DeadLoc belong to the same underlying object with valid \p KillingOff and
338 /// \p DeadOff.
339 static OverwriteResult isPartialOverwrite(const MemoryLocation &KillingLoc,
340                                           const MemoryLocation &DeadLoc,
341                                           int64_t KillingOff, int64_t DeadOff,
342                                           Instruction *DeadI,
343                                           InstOverlapIntervalsTy &IOL) {
344   const uint64_t KillingSize = KillingLoc.Size.getValue();
345   const uint64_t DeadSize = DeadLoc.Size.getValue();
346   // We may now overlap, although the overlap is not complete. There might also
347   // be other incomplete overlaps, and together, they might cover the complete
348   // dead store.
349   // Note: The correctness of this logic depends on the fact that this function
350   // is not even called providing DepWrite when there are any intervening reads.
351   if (EnablePartialOverwriteTracking &&
352       KillingOff < int64_t(DeadOff + DeadSize) &&
353       int64_t(KillingOff + KillingSize) >= DeadOff) {
354 
355     // Insert our part of the overlap into the map.
356     auto &IM = IOL[DeadI];
357     LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: DeadLoc [" << DeadOff << ", "
358                       << int64_t(DeadOff + DeadSize) << ") KillingLoc ["
359                       << KillingOff << ", " << int64_t(KillingOff + KillingSize)
360                       << ")\n");
361 
362     // Make sure that we only insert non-overlapping intervals and combine
363     // adjacent intervals. The intervals are stored in the map with the ending
364     // offset as the key (in the half-open sense) and the starting offset as
365     // the value.
366     int64_t KillingIntStart = KillingOff;
367     int64_t KillingIntEnd = KillingOff + KillingSize;
368 
369     // Find any intervals ending at, or after, KillingIntStart which start
370     // before KillingIntEnd.
371     auto ILI = IM.lower_bound(KillingIntStart);
372     if (ILI != IM.end() && ILI->second <= KillingIntEnd) {
373       // This existing interval is overlapped with the current store somewhere
374       // in [KillingIntStart, KillingIntEnd]. Merge them by erasing the existing
375       // intervals and adjusting our start and end.
376       KillingIntStart = std::min(KillingIntStart, ILI->second);
377       KillingIntEnd = std::max(KillingIntEnd, ILI->first);
378       ILI = IM.erase(ILI);
379 
380       // Continue erasing and adjusting our end in case other previous
381       // intervals are also overlapped with the current store.
382       //
383       // |--- dead 1 ---|  |--- dead 2 ---|
384       //     |------- killing---------|
385       //
386       while (ILI != IM.end() && ILI->second <= KillingIntEnd) {
387         assert(ILI->second > KillingIntStart && "Unexpected interval");
388         KillingIntEnd = std::max(KillingIntEnd, ILI->first);
389         ILI = IM.erase(ILI);
390       }
391     }
392 
393     IM[KillingIntEnd] = KillingIntStart;
394 
395     ILI = IM.begin();
396     if (ILI->second <= DeadOff && ILI->first >= int64_t(DeadOff + DeadSize)) {
397       LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: DeadLoc ["
398                         << DeadOff << ", " << int64_t(DeadOff + DeadSize)
399                         << ") Composite KillingLoc [" << ILI->second << ", "
400                         << ILI->first << ")\n");
401       ++NumCompletePartials;
402       return OW_Complete;
403     }
404   }
405 
406   // Check for a dead store which writes to all the memory locations that
407   // the killing store writes to.
408   if (EnablePartialStoreMerging && KillingOff >= DeadOff &&
409       int64_t(DeadOff + DeadSize) > KillingOff &&
410       uint64_t(KillingOff - DeadOff) + KillingSize <= DeadSize) {
411     LLVM_DEBUG(dbgs() << "DSE: Partial overwrite a dead load [" << DeadOff
412                       << ", " << int64_t(DeadOff + DeadSize)
413                       << ") by a killing store [" << KillingOff << ", "
414                       << int64_t(KillingOff + KillingSize) << ")\n");
415     // TODO: Maybe come up with a better name?
416     return OW_PartialEarlierWithFullLater;
417   }
418 
419   // Another interesting case is if the killing store overwrites the end of the
420   // dead store.
421   //
422   //      |--dead--|
423   //                |--   killing   --|
424   //
425   // In this case we may want to trim the size of dead store to avoid
426   // generating stores to addresses which will definitely be overwritten killing
427   // store.
428   if (!EnablePartialOverwriteTracking &&
429       (KillingOff > DeadOff && KillingOff < int64_t(DeadOff + DeadSize) &&
430        int64_t(KillingOff + KillingSize) >= int64_t(DeadOff + DeadSize)))
431     return OW_End;
432 
433   // Finally, we also need to check if the killing store overwrites the
434   // beginning of the dead store.
435   //
436   //                |--dead--|
437   //      |--  killing  --|
438   //
439   // In this case we may want to move the destination address and trim the size
440   // of dead store to avoid generating stores to addresses which will definitely
441   // be overwritten killing store.
442   if (!EnablePartialOverwriteTracking &&
443       (KillingOff <= DeadOff && int64_t(KillingOff + KillingSize) > DeadOff)) {
444     assert(int64_t(KillingOff + KillingSize) < int64_t(DeadOff + DeadSize) &&
445            "Expect to be handled as OW_Complete");
446     return OW_Begin;
447   }
448   // Otherwise, they don't completely overlap.
449   return OW_Unknown;
450 }
451 
452 /// Returns true if the memory which is accessed by the second instruction is not
453 /// modified between the first and the second instruction.
454 /// Precondition: Second instruction must be dominated by the first
455 /// instruction.
456 static bool
457 memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI,
458                            BatchAAResults &AA, const DataLayout &DL,
459                            DominatorTree *DT) {
460   // Do a backwards scan through the CFG from SecondI to FirstI. Look for
461   // instructions which can modify the memory location accessed by SecondI.
462   //
463   // While doing the walk keep track of the address to check. It might be
464   // different in different basic blocks due to PHI translation.
465   using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>;
466   SmallVector<BlockAddressPair, 16> WorkList;
467   // Keep track of the address we visited each block with. Bail out if we
468   // visit a block with different addresses.
469   DenseMap<BasicBlock *, Value *> Visited;
470 
471   BasicBlock::iterator FirstBBI(FirstI);
472   ++FirstBBI;
473   BasicBlock::iterator SecondBBI(SecondI);
474   BasicBlock *FirstBB = FirstI->getParent();
475   BasicBlock *SecondBB = SecondI->getParent();
476   MemoryLocation MemLoc;
477   if (auto *MemSet = dyn_cast<MemSetInst>(SecondI))
478     MemLoc = MemoryLocation::getForDest(MemSet);
479   else
480     MemLoc = MemoryLocation::get(SecondI);
481 
482   auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr);
483 
484   // Start checking the SecondBB.
485   WorkList.push_back(
486       std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr)));
487   bool isFirstBlock = true;
488 
489   // Check all blocks going backward until we reach the FirstBB.
490   while (!WorkList.empty()) {
491     BlockAddressPair Current = WorkList.pop_back_val();
492     BasicBlock *B = Current.first;
493     PHITransAddr &Addr = Current.second;
494     Value *Ptr = Addr.getAddr();
495 
496     // Ignore instructions before FirstI if this is the FirstBB.
497     BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
498 
499     BasicBlock::iterator EI;
500     if (isFirstBlock) {
501       // Ignore instructions after SecondI if this is the first visit of SecondBB.
502       assert(B == SecondBB && "first block is not the store block");
503       EI = SecondBBI;
504       isFirstBlock = false;
505     } else {
506       // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
507       // In this case we also have to look at instructions after SecondI.
508       EI = B->end();
509     }
510     for (; BI != EI; ++BI) {
511       Instruction *I = &*BI;
512       if (I->mayWriteToMemory() && I != SecondI)
513         if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr))))
514           return false;
515     }
516     if (B != FirstBB) {
517       assert(B != &FirstBB->getParent()->getEntryBlock() &&
518           "Should not hit the entry block because SI must be dominated by LI");
519       for (BasicBlock *Pred : predecessors(B)) {
520         PHITransAddr PredAddr = Addr;
521         if (PredAddr.NeedsPHITranslationFromBlock(B)) {
522           if (!PredAddr.IsPotentiallyPHITranslatable())
523             return false;
524           if (PredAddr.PHITranslateValue(B, Pred, DT, false))
525             return false;
526         }
527         Value *TranslatedPtr = PredAddr.getAddr();
528         auto Inserted = Visited.insert(std::make_pair(Pred, TranslatedPtr));
529         if (!Inserted.second) {
530           // We already visited this block before. If it was with a different
531           // address - bail out!
532           if (TranslatedPtr != Inserted.first->second)
533             return false;
534           // ... otherwise just skip it.
535           continue;
536         }
537         WorkList.push_back(std::make_pair(Pred, PredAddr));
538       }
539     }
540   }
541   return true;
542 }
543 
544 static bool tryToShorten(Instruction *DeadI, int64_t &DeadStart,
545                          uint64_t &DeadSize, int64_t KillingStart,
546                          uint64_t KillingSize, bool IsOverwriteEnd) {
547   auto *DeadIntrinsic = cast<AnyMemIntrinsic>(DeadI);
548   Align PrefAlign = DeadIntrinsic->getDestAlign().valueOrOne();
549 
550   // We assume that memet/memcpy operates in chunks of the "largest" native
551   // type size and aligned on the same value. That means optimal start and size
552   // of memset/memcpy should be modulo of preferred alignment of that type. That
553   // is it there is no any sense in trying to reduce store size any further
554   // since any "extra" stores comes for free anyway.
555   // On the other hand, maximum alignment we can achieve is limited by alignment
556   // of initial store.
557 
558   // TODO: Limit maximum alignment by preferred (or abi?) alignment of the
559   // "largest" native type.
560   // Note: What is the proper way to get that value?
561   // Should TargetTransformInfo::getRegisterBitWidth be used or anything else?
562   // PrefAlign = std::min(DL.getPrefTypeAlign(LargestType), PrefAlign);
563 
564   int64_t ToRemoveStart = 0;
565   uint64_t ToRemoveSize = 0;
566   // Compute start and size of the region to remove. Make sure 'PrefAlign' is
567   // maintained on the remaining store.
568   if (IsOverwriteEnd) {
569     // Calculate required adjustment for 'KillingStart' in order to keep
570     // remaining store size aligned on 'PerfAlign'.
571     uint64_t Off =
572         offsetToAlignment(uint64_t(KillingStart - DeadStart), PrefAlign);
573     ToRemoveStart = KillingStart + Off;
574     if (DeadSize <= uint64_t(ToRemoveStart - DeadStart))
575       return false;
576     ToRemoveSize = DeadSize - uint64_t(ToRemoveStart - DeadStart);
577   } else {
578     ToRemoveStart = DeadStart;
579     assert(KillingSize >= uint64_t(DeadStart - KillingStart) &&
580            "Not overlapping accesses?");
581     ToRemoveSize = KillingSize - uint64_t(DeadStart - KillingStart);
582     // Calculate required adjustment for 'ToRemoveSize'in order to keep
583     // start of the remaining store aligned on 'PerfAlign'.
584     uint64_t Off = offsetToAlignment(ToRemoveSize, PrefAlign);
585     if (Off != 0) {
586       if (ToRemoveSize <= (PrefAlign.value() - Off))
587         return false;
588       ToRemoveSize -= PrefAlign.value() - Off;
589     }
590     assert(isAligned(PrefAlign, ToRemoveSize) &&
591            "Should preserve selected alignment");
592   }
593 
594   assert(ToRemoveSize > 0 && "Shouldn't reach here if nothing to remove");
595   assert(DeadSize > ToRemoveSize && "Can't remove more than original size");
596 
597   uint64_t NewSize = DeadSize - ToRemoveSize;
598   if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(DeadI)) {
599     // When shortening an atomic memory intrinsic, the newly shortened
600     // length must remain an integer multiple of the element size.
601     const uint32_t ElementSize = AMI->getElementSizeInBytes();
602     if (0 != NewSize % ElementSize)
603       return false;
604   }
605 
606   LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW "
607                     << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *DeadI
608                     << "\n  KILLER [" << ToRemoveStart << ", "
609                     << int64_t(ToRemoveStart + ToRemoveSize) << ")\n");
610 
611   Value *DeadWriteLength = DeadIntrinsic->getLength();
612   Value *TrimmedLength = ConstantInt::get(DeadWriteLength->getType(), NewSize);
613   DeadIntrinsic->setLength(TrimmedLength);
614   DeadIntrinsic->setDestAlignment(PrefAlign);
615 
616   if (!IsOverwriteEnd) {
617     Value *OrigDest = DeadIntrinsic->getRawDest();
618     Type *Int8PtrTy =
619         Type::getInt8PtrTy(DeadIntrinsic->getContext(),
620                            OrigDest->getType()->getPointerAddressSpace());
621     Value *Dest = OrigDest;
622     if (OrigDest->getType() != Int8PtrTy)
623       Dest = CastInst::CreatePointerCast(OrigDest, Int8PtrTy, "", DeadI);
624     Value *Indices[1] = {
625         ConstantInt::get(DeadWriteLength->getType(), ToRemoveSize)};
626     Instruction *NewDestGEP = GetElementPtrInst::CreateInBounds(
627         Type::getInt8Ty(DeadIntrinsic->getContext()), Dest, Indices, "", DeadI);
628     NewDestGEP->setDebugLoc(DeadIntrinsic->getDebugLoc());
629     if (NewDestGEP->getType() != OrigDest->getType())
630       NewDestGEP = CastInst::CreatePointerCast(NewDestGEP, OrigDest->getType(),
631                                                "", DeadI);
632     DeadIntrinsic->setDest(NewDestGEP);
633   }
634 
635   // Finally update start and size of dead access.
636   if (!IsOverwriteEnd)
637     DeadStart += ToRemoveSize;
638   DeadSize = NewSize;
639 
640   return true;
641 }
642 
643 static bool tryToShortenEnd(Instruction *DeadI, OverlapIntervalsTy &IntervalMap,
644                             int64_t &DeadStart, uint64_t &DeadSize) {
645   if (IntervalMap.empty() || !isShortenableAtTheEnd(DeadI))
646     return false;
647 
648   OverlapIntervalsTy::iterator OII = --IntervalMap.end();
649   int64_t KillingStart = OII->second;
650   uint64_t KillingSize = OII->first - KillingStart;
651 
652   assert(OII->first - KillingStart >= 0 && "Size expected to be positive");
653 
654   if (KillingStart > DeadStart &&
655       // Note: "KillingStart - KillingStart" is known to be positive due to
656       // preceding check.
657       (uint64_t)(KillingStart - DeadStart) < DeadSize &&
658       // Note: "DeadSize - (uint64_t)(KillingStart - DeadStart)" is known to
659       // be non negative due to preceding checks.
660       KillingSize >= DeadSize - (uint64_t)(KillingStart - DeadStart)) {
661     if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize,
662                      true)) {
663       IntervalMap.erase(OII);
664       return true;
665     }
666   }
667   return false;
668 }
669 
670 static bool tryToShortenBegin(Instruction *DeadI,
671                               OverlapIntervalsTy &IntervalMap,
672                               int64_t &DeadStart, uint64_t &DeadSize) {
673   if (IntervalMap.empty() || !isShortenableAtTheBeginning(DeadI))
674     return false;
675 
676   OverlapIntervalsTy::iterator OII = IntervalMap.begin();
677   int64_t KillingStart = OII->second;
678   uint64_t KillingSize = OII->first - KillingStart;
679 
680   assert(OII->first - KillingStart >= 0 && "Size expected to be positive");
681 
682   if (KillingStart <= DeadStart &&
683       // Note: "DeadStart - KillingStart" is known to be non negative due to
684       // preceding check.
685       KillingSize > (uint64_t)(DeadStart - KillingStart)) {
686     // Note: "KillingSize - (uint64_t)(DeadStart - DeadStart)" is known to
687     // be positive due to preceding checks.
688     assert(KillingSize - (uint64_t)(DeadStart - KillingStart) < DeadSize &&
689            "Should have been handled as OW_Complete");
690     if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize,
691                      false)) {
692       IntervalMap.erase(OII);
693       return true;
694     }
695   }
696   return false;
697 }
698 
699 static Constant *
700 tryToMergePartialOverlappingStores(StoreInst *KillingI, StoreInst *DeadI,
701                                    int64_t KillingOffset, int64_t DeadOffset,
702                                    const DataLayout &DL, BatchAAResults &AA,
703                                    DominatorTree *DT) {
704 
705   if (DeadI && isa<ConstantInt>(DeadI->getValueOperand()) &&
706       DL.typeSizeEqualsStoreSize(DeadI->getValueOperand()->getType()) &&
707       KillingI && isa<ConstantInt>(KillingI->getValueOperand()) &&
708       DL.typeSizeEqualsStoreSize(KillingI->getValueOperand()->getType()) &&
709       memoryIsNotModifiedBetween(DeadI, KillingI, AA, DL, DT)) {
710     // If the store we find is:
711     //   a) partially overwritten by the store to 'Loc'
712     //   b) the killing store is fully contained in the dead one and
713     //   c) they both have a constant value
714     //   d) none of the two stores need padding
715     // Merge the two stores, replacing the dead store's value with a
716     // merge of both values.
717     // TODO: Deal with other constant types (vectors, etc), and probably
718     // some mem intrinsics (if needed)
719 
720     APInt DeadValue = cast<ConstantInt>(DeadI->getValueOperand())->getValue();
721     APInt KillingValue =
722         cast<ConstantInt>(KillingI->getValueOperand())->getValue();
723     unsigned KillingBits = KillingValue.getBitWidth();
724     assert(DeadValue.getBitWidth() > KillingValue.getBitWidth());
725     KillingValue = KillingValue.zext(DeadValue.getBitWidth());
726 
727     // Offset of the smaller store inside the larger store
728     unsigned BitOffsetDiff = (KillingOffset - DeadOffset) * 8;
729     unsigned LShiftAmount =
730         DL.isBigEndian() ? DeadValue.getBitWidth() - BitOffsetDiff - KillingBits
731                          : BitOffsetDiff;
732     APInt Mask = APInt::getBitsSet(DeadValue.getBitWidth(), LShiftAmount,
733                                    LShiftAmount + KillingBits);
734     // Clear the bits we'll be replacing, then OR with the smaller
735     // store, shifted appropriately.
736     APInt Merged = (DeadValue & ~Mask) | (KillingValue << LShiftAmount);
737     LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n  Dead: " << *DeadI
738                       << "\n  Killing: " << *KillingI
739                       << "\n  Merged Value: " << Merged << '\n');
740     return ConstantInt::get(DeadI->getValueOperand()->getType(), Merged);
741   }
742   return nullptr;
743 }
744 
745 namespace {
746 // Returns true if \p I is an intrisnic that does not read or write memory.
747 bool isNoopIntrinsic(Instruction *I) {
748   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
749     switch (II->getIntrinsicID()) {
750     case Intrinsic::lifetime_start:
751     case Intrinsic::lifetime_end:
752     case Intrinsic::invariant_end:
753     case Intrinsic::launder_invariant_group:
754     case Intrinsic::assume:
755       return true;
756     case Intrinsic::dbg_addr:
757     case Intrinsic::dbg_declare:
758     case Intrinsic::dbg_label:
759     case Intrinsic::dbg_value:
760       llvm_unreachable("Intrinsic should not be modeled in MemorySSA");
761     default:
762       return false;
763     }
764   }
765   return false;
766 }
767 
768 // Check if we can ignore \p D for DSE.
769 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller,
770                 const TargetLibraryInfo &TLI) {
771   Instruction *DI = D->getMemoryInst();
772   // Calls that only access inaccessible memory cannot read or write any memory
773   // locations we consider for elimination.
774   if (auto *CB = dyn_cast<CallBase>(DI))
775     if (CB->onlyAccessesInaccessibleMemory()) {
776       if (isAllocLikeFn(DI, &TLI))
777         return false;
778       return true;
779     }
780   // We can eliminate stores to locations not visible to the caller across
781   // throwing instructions.
782   if (DI->mayThrow() && !DefVisibleToCaller)
783     return true;
784 
785   // We can remove the dead stores, irrespective of the fence and its ordering
786   // (release/acquire/seq_cst). Fences only constraints the ordering of
787   // already visible stores, it does not make a store visible to other
788   // threads. So, skipping over a fence does not change a store from being
789   // dead.
790   if (isa<FenceInst>(DI))
791     return true;
792 
793   // Skip intrinsics that do not really read or modify memory.
794   if (isNoopIntrinsic(DI))
795     return true;
796 
797   return false;
798 }
799 
800 struct DSEState {
801   Function &F;
802   AliasAnalysis &AA;
803   EarliestEscapeInfo EI;
804 
805   /// The single BatchAA instance that is used to cache AA queries. It will
806   /// not be invalidated over the whole run. This is safe, because:
807   /// 1. Only memory writes are removed, so the alias cache for memory
808   ///    locations remains valid.
809   /// 2. No new instructions are added (only instructions removed), so cached
810   ///    information for a deleted value cannot be accessed by a re-used new
811   ///    value pointer.
812   BatchAAResults BatchAA;
813 
814   MemorySSA &MSSA;
815   DominatorTree &DT;
816   PostDominatorTree &PDT;
817   const TargetLibraryInfo &TLI;
818   const DataLayout &DL;
819   const LoopInfo &LI;
820 
821   // Whether the function contains any irreducible control flow, useful for
822   // being accurately able to detect loops.
823   bool ContainsIrreducibleLoops;
824 
825   // All MemoryDefs that potentially could kill other MemDefs.
826   SmallVector<MemoryDef *, 64> MemDefs;
827   // Any that should be skipped as they are already deleted
828   SmallPtrSet<MemoryAccess *, 4> SkipStores;
829   // Keep track of all of the objects that are invisible to the caller before
830   // the function returns.
831   // SmallPtrSet<const Value *, 16> InvisibleToCallerBeforeRet;
832   DenseMap<const Value *, bool> InvisibleToCallerBeforeRet;
833   // Keep track of all of the objects that are invisible to the caller after
834   // the function returns.
835   DenseMap<const Value *, bool> InvisibleToCallerAfterRet;
836   // Keep track of blocks with throwing instructions not modeled in MemorySSA.
837   SmallPtrSet<BasicBlock *, 16> ThrowingBlocks;
838   // Post-order numbers for each basic block. Used to figure out if memory
839   // accesses are executed before another access.
840   DenseMap<BasicBlock *, unsigned> PostOrderNumbers;
841 
842   /// Keep track of instructions (partly) overlapping with killing MemoryDefs per
843   /// basic block.
844   DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs;
845 
846   // Class contains self-reference, make sure it's not copied/moved.
847   DSEState(const DSEState &) = delete;
848   DSEState &operator=(const DSEState &) = delete;
849 
850   DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT,
851            PostDominatorTree &PDT, const TargetLibraryInfo &TLI,
852            const LoopInfo &LI)
853       : F(F), AA(AA), EI(DT, LI), BatchAA(AA, &EI), MSSA(MSSA), DT(DT),
854         PDT(PDT), TLI(TLI), DL(F.getParent()->getDataLayout()), LI(LI) {
855     // Collect blocks with throwing instructions not modeled in MemorySSA and
856     // alloc-like objects.
857     unsigned PO = 0;
858     for (BasicBlock *BB : post_order(&F)) {
859       PostOrderNumbers[BB] = PO++;
860       for (Instruction &I : *BB) {
861         MemoryAccess *MA = MSSA.getMemoryAccess(&I);
862         if (I.mayThrow() && !MA)
863           ThrowingBlocks.insert(I.getParent());
864 
865         auto *MD = dyn_cast_or_null<MemoryDef>(MA);
866         if (MD && MemDefs.size() < MemorySSADefsPerBlockLimit &&
867             (getLocForWriteEx(&I) || isMemTerminatorInst(&I)))
868           MemDefs.push_back(MD);
869       }
870     }
871 
872     // Treat byval or inalloca arguments the same as Allocas, stores to them are
873     // dead at the end of the function.
874     for (Argument &AI : F.args())
875       if (AI.hasPassPointeeByValueCopyAttr()) {
876         // For byval, the caller doesn't know the address of the allocation.
877         if (AI.hasByValAttr())
878           InvisibleToCallerBeforeRet.insert({&AI, true});
879         InvisibleToCallerAfterRet.insert({&AI, true});
880       }
881 
882     // Collect whether there is any irreducible control flow in the function.
883     ContainsIrreducibleLoops = mayContainIrreducibleControl(F, &LI);
884   }
885 
886   /// Return 'OW_Complete' if a store to the 'KillingLoc' location (by \p
887   /// KillingI instruction) completely overwrites a store to the 'DeadLoc'
888   /// location (by \p DeadI instruction).
889   /// Return OW_MaybePartial if \p KillingI does not completely overwrite
890   /// \p DeadI, but they both write to the same underlying object. In that
891   /// case, use isPartialOverwrite to check if \p KillingI partially overwrites
892   /// \p DeadI. Returns 'OW_Unknown' if nothing can be determined.
893   OverwriteResult isOverwrite(const Instruction *KillingI,
894                               const Instruction *DeadI,
895                               const MemoryLocation &KillingLoc,
896                               const MemoryLocation &DeadLoc,
897                               int64_t &KillingOff, int64_t &DeadOff) {
898     // AliasAnalysis does not always account for loops. Limit overwrite checks
899     // to dependencies for which we can guarantee they are independent of any
900     // loops they are in.
901     if (!isGuaranteedLoopIndependent(DeadI, KillingI, DeadLoc))
902       return OW_Unknown;
903 
904     // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll
905     // get imprecise values here, though (except for unknown sizes).
906     if (!KillingLoc.Size.isPrecise() || !DeadLoc.Size.isPrecise()) {
907       // In case no constant size is known, try to an IR values for the number
908       // of bytes written and check if they match.
909       const auto *KillingMemI = dyn_cast<MemIntrinsic>(KillingI);
910       const auto *DeadMemI = dyn_cast<MemIntrinsic>(DeadI);
911       if (KillingMemI && DeadMemI) {
912         const Value *KillingV = KillingMemI->getLength();
913         const Value *DeadV = DeadMemI->getLength();
914         if (KillingV == DeadV && BatchAA.isMustAlias(DeadLoc, KillingLoc))
915           return OW_Complete;
916       }
917 
918       // Masked stores have imprecise locations, but we can reason about them
919       // to some extent.
920       return isMaskedStoreOverwrite(KillingI, DeadI, BatchAA);
921     }
922 
923     const uint64_t KillingSize = KillingLoc.Size.getValue();
924     const uint64_t DeadSize = DeadLoc.Size.getValue();
925 
926     // Query the alias information
927     AliasResult AAR = BatchAA.alias(KillingLoc, DeadLoc);
928 
929     // If the start pointers are the same, we just have to compare sizes to see if
930     // the killing store was larger than the dead store.
931     if (AAR == AliasResult::MustAlias) {
932       // Make sure that the KillingSize size is >= the DeadSize size.
933       if (KillingSize >= DeadSize)
934         return OW_Complete;
935     }
936 
937     // If we hit a partial alias we may have a full overwrite
938     if (AAR == AliasResult::PartialAlias && AAR.hasOffset()) {
939       int32_t Off = AAR.getOffset();
940       if (Off >= 0 && (uint64_t)Off + DeadSize <= KillingSize)
941         return OW_Complete;
942     }
943 
944     // Check to see if the killing store is to the entire object (either a
945     // global, an alloca, or a byval/inalloca argument).  If so, then it clearly
946     // overwrites any other store to the same object.
947     const Value *DeadPtr = DeadLoc.Ptr->stripPointerCasts();
948     const Value *KillingPtr = KillingLoc.Ptr->stripPointerCasts();
949     const Value *DeadUndObj = getUnderlyingObject(DeadPtr);
950     const Value *KillingUndObj = getUnderlyingObject(KillingPtr);
951 
952     // If we can't resolve the same pointers to the same object, then we can't
953     // analyze them at all.
954     if (DeadUndObj != KillingUndObj)
955       return OW_Unknown;
956 
957     // If the KillingI store is to a recognizable object, get its size.
958     uint64_t KillingUndObjSize = getPointerSize(KillingUndObj, DL, TLI, &F);
959     if (KillingUndObjSize != MemoryLocation::UnknownSize)
960       if (KillingUndObjSize == KillingSize && KillingUndObjSize >= DeadSize)
961         return OW_Complete;
962 
963     // Okay, we have stores to two completely different pointers.  Try to
964     // decompose the pointer into a "base + constant_offset" form.  If the base
965     // pointers are equal, then we can reason about the two stores.
966     DeadOff = 0;
967     KillingOff = 0;
968     const Value *DeadBasePtr =
969         GetPointerBaseWithConstantOffset(DeadPtr, DeadOff, DL);
970     const Value *KillingBasePtr =
971         GetPointerBaseWithConstantOffset(KillingPtr, KillingOff, DL);
972 
973     // If the base pointers still differ, we have two completely different
974     // stores.
975     if (DeadBasePtr != KillingBasePtr)
976       return OW_Unknown;
977 
978     // The killing access completely overlaps the dead store if and only if
979     // both start and end of the dead one is "inside" the killing one:
980     //    |<->|--dead--|<->|
981     //    |-----killing------|
982     // Accesses may overlap if and only if start of one of them is "inside"
983     // another one:
984     //    |<->|--dead--|<-------->|
985     //    |-------killing--------|
986     //           OR
987     //    |-------dead-------|
988     //    |<->|---killing---|<----->|
989     //
990     // We have to be careful here as *Off is signed while *.Size is unsigned.
991 
992     // Check if the dead access starts "not before" the killing one.
993     if (DeadOff >= KillingOff) {
994       // If the dead access ends "not after" the killing access then the
995       // dead one is completely overwritten by the killing one.
996       if (uint64_t(DeadOff - KillingOff) + DeadSize <= KillingSize)
997         return OW_Complete;
998       // If start of the dead access is "before" end of the killing access
999       // then accesses overlap.
1000       else if ((uint64_t)(DeadOff - KillingOff) < KillingSize)
1001         return OW_MaybePartial;
1002     }
1003     // If start of the killing access is "before" end of the dead access then
1004     // accesses overlap.
1005     else if ((uint64_t)(KillingOff - DeadOff) < DeadSize) {
1006       return OW_MaybePartial;
1007     }
1008 
1009     // Can reach here only if accesses are known not to overlap. There is no
1010     // dedicated code to indicate no overlap so signal "unknown".
1011     return OW_Unknown;
1012   }
1013 
1014   bool isInvisibleToCallerAfterRet(const Value *V) {
1015     if (isa<AllocaInst>(V))
1016       return true;
1017     auto I = InvisibleToCallerAfterRet.insert({V, false});
1018     if (I.second) {
1019       if (!isInvisibleToCallerBeforeRet(V)) {
1020         I.first->second = false;
1021       } else {
1022         auto *Inst = dyn_cast<Instruction>(V);
1023         if (Inst && isAllocLikeFn(Inst, &TLI))
1024           I.first->second = !PointerMayBeCaptured(V, true, false);
1025       }
1026     }
1027     return I.first->second;
1028   }
1029 
1030   bool isInvisibleToCallerBeforeRet(const Value *V) {
1031     if (isa<AllocaInst>(V))
1032       return true;
1033     auto I = InvisibleToCallerBeforeRet.insert({V, false});
1034     if (I.second) {
1035       auto *Inst = dyn_cast<Instruction>(V);
1036       if (Inst && isAllocLikeFn(Inst, &TLI))
1037         // NOTE: This could be made more precise by PointerMayBeCapturedBefore
1038         // with the killing MemoryDef. But we refrain from doing so for now to
1039         // limit compile-time and this does not cause any changes to the number
1040         // of stores removed on a large test set in practice.
1041         I.first->second = !PointerMayBeCaptured(V, false, true);
1042     }
1043     return I.first->second;
1044   }
1045 
1046   Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const {
1047     if (!I->mayWriteToMemory())
1048       return None;
1049 
1050     if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I))
1051       return {MemoryLocation::getForDest(MTI)};
1052 
1053     if (auto *CB = dyn_cast<CallBase>(I)) {
1054       // If the functions may write to memory we do not know about, bail out.
1055       if (!CB->onlyAccessesArgMemory() &&
1056           !CB->onlyAccessesInaccessibleMemOrArgMem())
1057         return None;
1058 
1059       LibFunc LF;
1060       if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) {
1061         switch (LF) {
1062         case LibFunc_strcpy:
1063         case LibFunc_strncpy:
1064         case LibFunc_strcat:
1065         case LibFunc_strncat:
1066           return {MemoryLocation::getAfter(CB->getArgOperand(0))};
1067         default:
1068           break;
1069         }
1070       }
1071       switch (CB->getIntrinsicID()) {
1072       case Intrinsic::init_trampoline:
1073         return {MemoryLocation::getAfter(CB->getArgOperand(0))};
1074       case Intrinsic::masked_store:
1075         return {MemoryLocation::getForArgument(CB, 1, TLI)};
1076       default:
1077         break;
1078       }
1079       return None;
1080     }
1081 
1082     return MemoryLocation::getOrNone(I);
1083   }
1084 
1085   /// Returns true if \p UseInst completely overwrites \p DefLoc
1086   /// (stored by \p DefInst).
1087   bool isCompleteOverwrite(const MemoryLocation &DefLoc, Instruction *DefInst,
1088                            Instruction *UseInst) {
1089     // UseInst has a MemoryDef associated in MemorySSA. It's possible for a
1090     // MemoryDef to not write to memory, e.g. a volatile load is modeled as a
1091     // MemoryDef.
1092     if (!UseInst->mayWriteToMemory())
1093       return false;
1094 
1095     if (auto *CB = dyn_cast<CallBase>(UseInst))
1096       if (CB->onlyAccessesInaccessibleMemory())
1097         return false;
1098 
1099     int64_t InstWriteOffset, DepWriteOffset;
1100     if (auto CC = getLocForWriteEx(UseInst))
1101       return isOverwrite(UseInst, DefInst, *CC, DefLoc, InstWriteOffset,
1102                          DepWriteOffset) == OW_Complete;
1103     return false;
1104   }
1105 
1106   /// Returns true if \p Def is not read before returning from the function.
1107   bool isWriteAtEndOfFunction(MemoryDef *Def) {
1108     LLVM_DEBUG(dbgs() << "  Check if def " << *Def << " ("
1109                       << *Def->getMemoryInst()
1110                       << ") is at the end the function \n");
1111 
1112     auto MaybeLoc = getLocForWriteEx(Def->getMemoryInst());
1113     if (!MaybeLoc) {
1114       LLVM_DEBUG(dbgs() << "  ... could not get location for write.\n");
1115       return false;
1116     }
1117 
1118     SmallVector<MemoryAccess *, 4> WorkList;
1119     SmallPtrSet<MemoryAccess *, 8> Visited;
1120     auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) {
1121       if (!Visited.insert(Acc).second)
1122         return;
1123       for (Use &U : Acc->uses())
1124         WorkList.push_back(cast<MemoryAccess>(U.getUser()));
1125     };
1126     PushMemUses(Def);
1127     for (unsigned I = 0; I < WorkList.size(); I++) {
1128       if (WorkList.size() >= MemorySSAScanLimit) {
1129         LLVM_DEBUG(dbgs() << "  ... hit exploration limit.\n");
1130         return false;
1131       }
1132 
1133       MemoryAccess *UseAccess = WorkList[I];
1134       // Simply adding the users of MemoryPhi to the worklist is not enough,
1135       // because we might miss read clobbers in different iterations of a loop,
1136       // for example.
1137       // TODO: Add support for phi translation to handle the loop case.
1138       if (isa<MemoryPhi>(UseAccess))
1139         return false;
1140 
1141       // TODO: Checking for aliasing is expensive. Consider reducing the amount
1142       // of times this is called and/or caching it.
1143       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1144       if (isReadClobber(*MaybeLoc, UseInst)) {
1145         LLVM_DEBUG(dbgs() << "  ... hit read clobber " << *UseInst << ".\n");
1146         return false;
1147       }
1148 
1149       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess))
1150         PushMemUses(UseDef);
1151     }
1152     return true;
1153   }
1154 
1155   /// If \p I is a memory  terminator like llvm.lifetime.end or free, return a
1156   /// pair with the MemoryLocation terminated by \p I and a boolean flag
1157   /// indicating whether \p I is a free-like call.
1158   Optional<std::pair<MemoryLocation, bool>>
1159   getLocForTerminator(Instruction *I) const {
1160     uint64_t Len;
1161     Value *Ptr;
1162     if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len),
1163                                                       m_Value(Ptr))))
1164       return {std::make_pair(MemoryLocation(Ptr, Len), false)};
1165 
1166     if (auto *CB = dyn_cast<CallBase>(I)) {
1167       if (isFreeCall(I, &TLI))
1168         return {std::make_pair(MemoryLocation::getAfter(CB->getArgOperand(0)),
1169                                true)};
1170     }
1171 
1172     return None;
1173   }
1174 
1175   /// Returns true if \p I is a memory terminator instruction like
1176   /// llvm.lifetime.end or free.
1177   bool isMemTerminatorInst(Instruction *I) const {
1178     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1179     return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) ||
1180            isFreeCall(I, &TLI);
1181   }
1182 
1183   /// Returns true if \p MaybeTerm is a memory terminator for \p Loc from
1184   /// instruction \p AccessI.
1185   bool isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI,
1186                        Instruction *MaybeTerm) {
1187     Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc =
1188         getLocForTerminator(MaybeTerm);
1189 
1190     if (!MaybeTermLoc)
1191       return false;
1192 
1193     // If the terminator is a free-like call, all accesses to the underlying
1194     // object can be considered terminated.
1195     if (getUnderlyingObject(Loc.Ptr) !=
1196         getUnderlyingObject(MaybeTermLoc->first.Ptr))
1197       return false;
1198 
1199     auto TermLoc = MaybeTermLoc->first;
1200     if (MaybeTermLoc->second) {
1201       const Value *LocUO = getUnderlyingObject(Loc.Ptr);
1202       return BatchAA.isMustAlias(TermLoc.Ptr, LocUO);
1203     }
1204     int64_t InstWriteOffset = 0;
1205     int64_t DepWriteOffset = 0;
1206     return isOverwrite(MaybeTerm, AccessI, TermLoc, Loc, InstWriteOffset,
1207                        DepWriteOffset) == OW_Complete;
1208   }
1209 
1210   // Returns true if \p Use may read from \p DefLoc.
1211   bool isReadClobber(const MemoryLocation &DefLoc, Instruction *UseInst) {
1212     if (isNoopIntrinsic(UseInst))
1213       return false;
1214 
1215     // Monotonic or weaker atomic stores can be re-ordered and do not need to be
1216     // treated as read clobber.
1217     if (auto SI = dyn_cast<StoreInst>(UseInst))
1218       return isStrongerThan(SI->getOrdering(), AtomicOrdering::Monotonic);
1219 
1220     if (!UseInst->mayReadFromMemory())
1221       return false;
1222 
1223     if (auto *CB = dyn_cast<CallBase>(UseInst))
1224       if (CB->onlyAccessesInaccessibleMemory())
1225         return false;
1226 
1227     return isRefSet(BatchAA.getModRefInfo(UseInst, DefLoc));
1228   }
1229 
1230   /// Returns true if a dependency between \p Current and \p KillingDef is
1231   /// guaranteed to be loop invariant for the loops that they are in. Either
1232   /// because they are known to be in the same block, in the same loop level or
1233   /// by guaranteeing that \p CurrentLoc only references a single MemoryLocation
1234   /// during execution of the containing function.
1235   bool isGuaranteedLoopIndependent(const Instruction *Current,
1236                                    const Instruction *KillingDef,
1237                                    const MemoryLocation &CurrentLoc) {
1238     // If the dependency is within the same block or loop level (being careful
1239     // of irreducible loops), we know that AA will return a valid result for the
1240     // memory dependency. (Both at the function level, outside of any loop,
1241     // would also be valid but we currently disable that to limit compile time).
1242     if (Current->getParent() == KillingDef->getParent())
1243       return true;
1244     const Loop *CurrentLI = LI.getLoopFor(Current->getParent());
1245     if (!ContainsIrreducibleLoops && CurrentLI &&
1246         CurrentLI == LI.getLoopFor(KillingDef->getParent()))
1247       return true;
1248     // Otherwise check the memory location is invariant to any loops.
1249     return isGuaranteedLoopInvariant(CurrentLoc.Ptr);
1250   }
1251 
1252   /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1253   /// loop. In particular, this guarantees that it only references a single
1254   /// MemoryLocation during execution of the containing function.
1255   bool isGuaranteedLoopInvariant(const Value *Ptr) {
1256     auto IsGuaranteedLoopInvariantBase = [this](const Value *Ptr) {
1257       Ptr = Ptr->stripPointerCasts();
1258       if (auto *I = dyn_cast<Instruction>(Ptr)) {
1259         if (isa<AllocaInst>(Ptr))
1260           return true;
1261 
1262         if (isAllocLikeFn(I, &TLI))
1263           return true;
1264 
1265         return false;
1266       }
1267       return true;
1268     };
1269 
1270     Ptr = Ptr->stripPointerCasts();
1271     if (auto *I = dyn_cast<Instruction>(Ptr)) {
1272       if (I->getParent()->isEntryBlock())
1273         return true;
1274     }
1275     if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
1276       return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) &&
1277              GEP->hasAllConstantIndices();
1278     }
1279     return IsGuaranteedLoopInvariantBase(Ptr);
1280   }
1281 
1282   // Find a MemoryDef writing to \p KillingLoc and dominating \p StartAccess,
1283   // with no read access between them or on any other path to a function exit
1284   // block if \p KillingLoc is not accessible after the function returns. If
1285   // there is no such MemoryDef, return None. The returned value may not
1286   // (completely) overwrite \p KillingLoc. Currently we bail out when we
1287   // encounter an aliasing MemoryUse (read).
1288   Optional<MemoryAccess *>
1289   getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess,
1290                   const MemoryLocation &KillingLoc, const Value *KillingUndObj,
1291                   unsigned &ScanLimit, unsigned &WalkerStepLimit,
1292                   bool IsMemTerm, unsigned &PartialLimit) {
1293     if (ScanLimit == 0 || WalkerStepLimit == 0) {
1294       LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1295       return None;
1296     }
1297 
1298     MemoryAccess *Current = StartAccess;
1299     Instruction *KillingI = KillingDef->getMemoryInst();
1300     LLVM_DEBUG(dbgs() << "  trying to get dominating access\n");
1301 
1302     // Find the next clobbering Mod access for DefLoc, starting at StartAccess.
1303     Optional<MemoryLocation> CurrentLoc;
1304     for (;; Current = cast<MemoryDef>(Current)->getDefiningAccess()) {
1305       LLVM_DEBUG({
1306         dbgs() << "   visiting " << *Current;
1307         if (!MSSA.isLiveOnEntryDef(Current) && isa<MemoryUseOrDef>(Current))
1308           dbgs() << " (" << *cast<MemoryUseOrDef>(Current)->getMemoryInst()
1309                  << ")";
1310         dbgs() << "\n";
1311       });
1312 
1313       // Reached TOP.
1314       if (MSSA.isLiveOnEntryDef(Current)) {
1315         LLVM_DEBUG(dbgs() << "   ...  found LiveOnEntryDef\n");
1316         return None;
1317       }
1318 
1319       // Cost of a step. Accesses in the same block are more likely to be valid
1320       // candidates for elimination, hence consider them cheaper.
1321       unsigned StepCost = KillingDef->getBlock() == Current->getBlock()
1322                               ? MemorySSASameBBStepCost
1323                               : MemorySSAOtherBBStepCost;
1324       if (WalkerStepLimit <= StepCost) {
1325         LLVM_DEBUG(dbgs() << "   ...  hit walker step limit\n");
1326         return None;
1327       }
1328       WalkerStepLimit -= StepCost;
1329 
1330       // Return for MemoryPhis. They cannot be eliminated directly and the
1331       // caller is responsible for traversing them.
1332       if (isa<MemoryPhi>(Current)) {
1333         LLVM_DEBUG(dbgs() << "   ...  found MemoryPhi\n");
1334         return Current;
1335       }
1336 
1337       // Below, check if CurrentDef is a valid candidate to be eliminated by
1338       // KillingDef. If it is not, check the next candidate.
1339       MemoryDef *CurrentDef = cast<MemoryDef>(Current);
1340       Instruction *CurrentI = CurrentDef->getMemoryInst();
1341 
1342       if (canSkipDef(CurrentDef, !isInvisibleToCallerBeforeRet(KillingUndObj),
1343                      TLI))
1344         continue;
1345 
1346       // Before we try to remove anything, check for any extra throwing
1347       // instructions that block us from DSEing
1348       if (mayThrowBetween(KillingI, CurrentI, KillingUndObj)) {
1349         LLVM_DEBUG(dbgs() << "  ... skip, may throw!\n");
1350         return None;
1351       }
1352 
1353       // Check for anything that looks like it will be a barrier to further
1354       // removal
1355       if (isDSEBarrier(KillingUndObj, CurrentI)) {
1356         LLVM_DEBUG(dbgs() << "  ... skip, barrier\n");
1357         return None;
1358       }
1359 
1360       // If Current is known to be on path that reads DefLoc or is a read
1361       // clobber, bail out, as the path is not profitable. We skip this check
1362       // for intrinsic calls, because the code knows how to handle memcpy
1363       // intrinsics.
1364       if (!isa<IntrinsicInst>(CurrentI) && isReadClobber(KillingLoc, CurrentI))
1365         return None;
1366 
1367       // Quick check if there are direct uses that are read-clobbers.
1368       if (any_of(Current->uses(), [this, &KillingLoc, StartAccess](Use &U) {
1369             if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U.getUser()))
1370               return !MSSA.dominates(StartAccess, UseOrDef) &&
1371                      isReadClobber(KillingLoc, UseOrDef->getMemoryInst());
1372             return false;
1373           })) {
1374         LLVM_DEBUG(dbgs() << "   ...  found a read clobber\n");
1375         return None;
1376       }
1377 
1378       // If Current cannot be analyzed or is not removable, check the next
1379       // candidate.
1380       if (!hasAnalyzableMemoryWrite(CurrentI, TLI) || !isRemovable(CurrentI))
1381         continue;
1382 
1383       // If Current does not have an analyzable write location, skip it
1384       CurrentLoc = getLocForWriteEx(CurrentI);
1385       if (!CurrentLoc)
1386         continue;
1387 
1388       // AliasAnalysis does not account for loops. Limit elimination to
1389       // candidates for which we can guarantee they always store to the same
1390       // memory location and not located in different loops.
1391       if (!isGuaranteedLoopIndependent(CurrentI, KillingI, *CurrentLoc)) {
1392         LLVM_DEBUG(dbgs() << "  ... not guaranteed loop independent\n");
1393         WalkerStepLimit -= 1;
1394         continue;
1395       }
1396 
1397       if (IsMemTerm) {
1398         // If the killing def is a memory terminator (e.g. lifetime.end), check
1399         // the next candidate if the current Current does not write the same
1400         // underlying object as the terminator.
1401         if (!isMemTerminator(*CurrentLoc, CurrentI, KillingI))
1402           continue;
1403       } else {
1404         int64_t KillingOffset = 0;
1405         int64_t DeadOffset = 0;
1406         auto OR = isOverwrite(KillingI, CurrentI, KillingLoc, *CurrentLoc,
1407                               KillingOffset, DeadOffset);
1408         // If Current does not write to the same object as KillingDef, check
1409         // the next candidate.
1410         if (OR == OW_Unknown)
1411           continue;
1412         else if (OR == OW_MaybePartial) {
1413           // If KillingDef only partially overwrites Current, check the next
1414           // candidate if the partial step limit is exceeded. This aggressively
1415           // limits the number of candidates for partial store elimination,
1416           // which are less likely to be removable in the end.
1417           if (PartialLimit <= 1) {
1418             WalkerStepLimit -= 1;
1419             continue;
1420           }
1421           PartialLimit -= 1;
1422         }
1423       }
1424       break;
1425     };
1426 
1427     // Accesses to objects accessible after the function returns can only be
1428     // eliminated if the access is dead along all paths to the exit. Collect
1429     // the blocks with killing (=completely overwriting MemoryDefs) and check if
1430     // they cover all paths from MaybeDeadAccess to any function exit.
1431     SmallPtrSet<Instruction *, 16> KillingDefs;
1432     KillingDefs.insert(KillingDef->getMemoryInst());
1433     MemoryAccess *MaybeDeadAccess = Current;
1434     MemoryLocation MaybeDeadLoc = *CurrentLoc;
1435     Instruction *MaybeDeadI = cast<MemoryDef>(MaybeDeadAccess)->getMemoryInst();
1436     LLVM_DEBUG(dbgs() << "  Checking for reads of " << *MaybeDeadAccess << " ("
1437                       << *MaybeDeadI << ")\n");
1438 
1439     SmallSetVector<MemoryAccess *, 32> WorkList;
1440     auto PushMemUses = [&WorkList](MemoryAccess *Acc) {
1441       for (Use &U : Acc->uses())
1442         WorkList.insert(cast<MemoryAccess>(U.getUser()));
1443     };
1444     PushMemUses(MaybeDeadAccess);
1445 
1446     // Check if DeadDef may be read.
1447     for (unsigned I = 0; I < WorkList.size(); I++) {
1448       MemoryAccess *UseAccess = WorkList[I];
1449 
1450       LLVM_DEBUG(dbgs() << "   " << *UseAccess);
1451       // Bail out if the number of accesses to check exceeds the scan limit.
1452       if (ScanLimit < (WorkList.size() - I)) {
1453         LLVM_DEBUG(dbgs() << "\n    ...  hit scan limit\n");
1454         return None;
1455       }
1456       --ScanLimit;
1457       NumDomMemDefChecks++;
1458 
1459       if (isa<MemoryPhi>(UseAccess)) {
1460         if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) {
1461               return DT.properlyDominates(KI->getParent(),
1462                                           UseAccess->getBlock());
1463             })) {
1464           LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n");
1465           continue;
1466         }
1467         LLVM_DEBUG(dbgs() << "\n    ... adding PHI uses\n");
1468         PushMemUses(UseAccess);
1469         continue;
1470       }
1471 
1472       Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst();
1473       LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n");
1474 
1475       if (any_of(KillingDefs, [this, UseInst](Instruction *KI) {
1476             return DT.dominates(KI, UseInst);
1477           })) {
1478         LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n");
1479         continue;
1480       }
1481 
1482       // A memory terminator kills all preceeding MemoryDefs and all succeeding
1483       // MemoryAccesses. We do not have to check it's users.
1484       if (isMemTerminator(MaybeDeadLoc, MaybeDeadI, UseInst)) {
1485         LLVM_DEBUG(
1486             dbgs()
1487             << " ... skipping, memterminator invalidates following accesses\n");
1488         continue;
1489       }
1490 
1491       if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess)->getMemoryInst())) {
1492         LLVM_DEBUG(dbgs() << "    ... adding uses of intrinsic\n");
1493         PushMemUses(UseAccess);
1494         continue;
1495       }
1496 
1497       if (UseInst->mayThrow() && !isInvisibleToCallerBeforeRet(KillingUndObj)) {
1498         LLVM_DEBUG(dbgs() << "  ... found throwing instruction\n");
1499         return None;
1500       }
1501 
1502       // Uses which may read the original MemoryDef mean we cannot eliminate the
1503       // original MD. Stop walk.
1504       if (isReadClobber(MaybeDeadLoc, UseInst)) {
1505         LLVM_DEBUG(dbgs() << "    ... found read clobber\n");
1506         return None;
1507       }
1508 
1509       // If this worklist walks back to the original memory access (and the
1510       // pointer is not guarenteed loop invariant) then we cannot assume that a
1511       // store kills itself.
1512       if (MaybeDeadAccess == UseAccess &&
1513           !isGuaranteedLoopInvariant(MaybeDeadLoc.Ptr)) {
1514         LLVM_DEBUG(dbgs() << "    ... found not loop invariant self access\n");
1515         return None;
1516       }
1517       // Otherwise, for the KillingDef and MaybeDeadAccess we only have to check
1518       // if it reads the memory location.
1519       // TODO: It would probably be better to check for self-reads before
1520       // calling the function.
1521       if (KillingDef == UseAccess || MaybeDeadAccess == UseAccess) {
1522         LLVM_DEBUG(dbgs() << "    ... skipping killing def/dom access\n");
1523         continue;
1524       }
1525 
1526       // Check all uses for MemoryDefs, except for defs completely overwriting
1527       // the original location. Otherwise we have to check uses of *all*
1528       // MemoryDefs we discover, including non-aliasing ones. Otherwise we might
1529       // miss cases like the following
1530       //   1 = Def(LoE) ; <----- DeadDef stores [0,1]
1531       //   2 = Def(1)   ; (2, 1) = NoAlias,   stores [2,3]
1532       //   Use(2)       ; MayAlias 2 *and* 1, loads [0, 3].
1533       //                  (The Use points to the *first* Def it may alias)
1534       //   3 = Def(1)   ; <---- Current  (3, 2) = NoAlias, (3,1) = MayAlias,
1535       //                  stores [0,1]
1536       if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) {
1537         if (isCompleteOverwrite(MaybeDeadLoc, MaybeDeadI, UseInst)) {
1538           BasicBlock *MaybeKillingBlock = UseInst->getParent();
1539           if (PostOrderNumbers.find(MaybeKillingBlock)->second <
1540               PostOrderNumbers.find(MaybeDeadAccess->getBlock())->second) {
1541             if (!isInvisibleToCallerAfterRet(KillingUndObj)) {
1542               LLVM_DEBUG(dbgs()
1543                          << "    ... found killing def " << *UseInst << "\n");
1544               KillingDefs.insert(UseInst);
1545             }
1546           } else {
1547             LLVM_DEBUG(dbgs()
1548                        << "    ... found preceeding def " << *UseInst << "\n");
1549             return None;
1550           }
1551         } else
1552           PushMemUses(UseDef);
1553       }
1554     }
1555 
1556     // For accesses to locations visible after the function returns, make sure
1557     // that the location is dead (=overwritten) along all paths from
1558     // MaybeDeadAccess to the exit.
1559     if (!isInvisibleToCallerAfterRet(KillingUndObj)) {
1560       SmallPtrSet<BasicBlock *, 16> KillingBlocks;
1561       for (Instruction *KD : KillingDefs)
1562         KillingBlocks.insert(KD->getParent());
1563       assert(!KillingBlocks.empty() &&
1564              "Expected at least a single killing block");
1565 
1566       // Find the common post-dominator of all killing blocks.
1567       BasicBlock *CommonPred = *KillingBlocks.begin();
1568       for (BasicBlock *BB : llvm::drop_begin(KillingBlocks)) {
1569         if (!CommonPred)
1570           break;
1571         CommonPred = PDT.findNearestCommonDominator(CommonPred, BB);
1572       }
1573 
1574       // If CommonPred is in the set of killing blocks, just check if it
1575       // post-dominates MaybeDeadAccess.
1576       if (KillingBlocks.count(CommonPred)) {
1577         if (PDT.dominates(CommonPred, MaybeDeadAccess->getBlock()))
1578           return {MaybeDeadAccess};
1579         return None;
1580       }
1581 
1582       // If the common post-dominator does not post-dominate MaybeDeadAccess,
1583       // there is a path from MaybeDeadAccess to an exit not going through a
1584       // killing block.
1585       if (PDT.dominates(CommonPred, MaybeDeadAccess->getBlock())) {
1586         SetVector<BasicBlock *> WorkList;
1587 
1588         // If CommonPred is null, there are multiple exits from the function.
1589         // They all have to be added to the worklist.
1590         if (CommonPred)
1591           WorkList.insert(CommonPred);
1592         else
1593           for (BasicBlock *R : PDT.roots())
1594             WorkList.insert(R);
1595 
1596         NumCFGTries++;
1597         // Check if all paths starting from an exit node go through one of the
1598         // killing blocks before reaching MaybeDeadAccess.
1599         for (unsigned I = 0; I < WorkList.size(); I++) {
1600           NumCFGChecks++;
1601           BasicBlock *Current = WorkList[I];
1602           if (KillingBlocks.count(Current))
1603             continue;
1604           if (Current == MaybeDeadAccess->getBlock())
1605             return None;
1606 
1607           // MaybeDeadAccess is reachable from the entry, so we don't have to
1608           // explore unreachable blocks further.
1609           if (!DT.isReachableFromEntry(Current))
1610             continue;
1611 
1612           for (BasicBlock *Pred : predecessors(Current))
1613             WorkList.insert(Pred);
1614 
1615           if (WorkList.size() >= MemorySSAPathCheckLimit)
1616             return None;
1617         }
1618         NumCFGSuccess++;
1619         return {MaybeDeadAccess};
1620       }
1621       return None;
1622     }
1623 
1624     // No aliasing MemoryUses of MaybeDeadAccess found, MaybeDeadAccess is
1625     // potentially dead.
1626     return {MaybeDeadAccess};
1627   }
1628 
1629   // Delete dead memory defs
1630   void deleteDeadInstruction(Instruction *SI) {
1631     MemorySSAUpdater Updater(&MSSA);
1632     SmallVector<Instruction *, 32> NowDeadInsts;
1633     NowDeadInsts.push_back(SI);
1634     --NumFastOther;
1635 
1636     while (!NowDeadInsts.empty()) {
1637       Instruction *DeadInst = NowDeadInsts.pop_back_val();
1638       ++NumFastOther;
1639 
1640       // Try to preserve debug information attached to the dead instruction.
1641       salvageDebugInfo(*DeadInst);
1642       salvageKnowledge(DeadInst);
1643 
1644       // Remove the Instruction from MSSA.
1645       if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) {
1646         if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) {
1647           SkipStores.insert(MD);
1648         }
1649 
1650         Updater.removeMemoryAccess(MA);
1651       }
1652 
1653       auto I = IOLs.find(DeadInst->getParent());
1654       if (I != IOLs.end())
1655         I->second.erase(DeadInst);
1656       // Remove its operands
1657       for (Use &O : DeadInst->operands())
1658         if (Instruction *OpI = dyn_cast<Instruction>(O)) {
1659           O = nullptr;
1660           if (isInstructionTriviallyDead(OpI, &TLI))
1661             NowDeadInsts.push_back(OpI);
1662         }
1663 
1664       EI.removeInstruction(DeadInst);
1665       DeadInst->eraseFromParent();
1666     }
1667   }
1668 
1669   // Check for any extra throws between \p KillingI and \p DeadI that block
1670   // DSE.  This only checks extra maythrows (those that aren't MemoryDef's).
1671   // MemoryDef that may throw are handled during the walk from one def to the
1672   // next.
1673   bool mayThrowBetween(Instruction *KillingI, Instruction *DeadI,
1674                        const Value *KillingUndObj) {
1675     // First see if we can ignore it by using the fact that KillingI is an
1676     // alloca/alloca like object that is not visible to the caller during
1677     // execution of the function.
1678     if (KillingUndObj && isInvisibleToCallerBeforeRet(KillingUndObj))
1679       return false;
1680 
1681     if (KillingI->getParent() == DeadI->getParent())
1682       return ThrowingBlocks.count(KillingI->getParent());
1683     return !ThrowingBlocks.empty();
1684   }
1685 
1686   // Check if \p DeadI acts as a DSE barrier for \p KillingI. The following
1687   // instructions act as barriers:
1688   //  * A memory instruction that may throw and \p KillingI accesses a non-stack
1689   //  object.
1690   //  * Atomic stores stronger that monotonic.
1691   bool isDSEBarrier(const Value *KillingUndObj, Instruction *DeadI) {
1692     // If DeadI may throw it acts as a barrier, unless we are to an
1693     // alloca/alloca like object that does not escape.
1694     if (DeadI->mayThrow() && !isInvisibleToCallerBeforeRet(KillingUndObj))
1695       return true;
1696 
1697     // If DeadI is an atomic load/store stronger than monotonic, do not try to
1698     // eliminate/reorder it.
1699     if (DeadI->isAtomic()) {
1700       if (auto *LI = dyn_cast<LoadInst>(DeadI))
1701         return isStrongerThanMonotonic(LI->getOrdering());
1702       if (auto *SI = dyn_cast<StoreInst>(DeadI))
1703         return isStrongerThanMonotonic(SI->getOrdering());
1704       if (auto *ARMW = dyn_cast<AtomicRMWInst>(DeadI))
1705         return isStrongerThanMonotonic(ARMW->getOrdering());
1706       if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(DeadI))
1707         return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) ||
1708                isStrongerThanMonotonic(CmpXchg->getFailureOrdering());
1709       llvm_unreachable("other instructions should be skipped in MemorySSA");
1710     }
1711     return false;
1712   }
1713 
1714   /// Eliminate writes to objects that are not visible in the caller and are not
1715   /// accessed before returning from the function.
1716   bool eliminateDeadWritesAtEndOfFunction() {
1717     bool MadeChange = false;
1718     LLVM_DEBUG(
1719         dbgs()
1720         << "Trying to eliminate MemoryDefs at the end of the function\n");
1721     for (int I = MemDefs.size() - 1; I >= 0; I--) {
1722       MemoryDef *Def = MemDefs[I];
1723       if (SkipStores.contains(Def) || !isRemovable(Def->getMemoryInst()))
1724         continue;
1725 
1726       Instruction *DefI = Def->getMemoryInst();
1727       auto DefLoc = getLocForWriteEx(DefI);
1728       if (!DefLoc)
1729         continue;
1730 
1731       // NOTE: Currently eliminating writes at the end of a function is limited
1732       // to MemoryDefs with a single underlying object, to save compile-time. In
1733       // practice it appears the case with multiple underlying objects is very
1734       // uncommon. If it turns out to be important, we can use
1735       // getUnderlyingObjects here instead.
1736       const Value *UO = getUnderlyingObject(DefLoc->Ptr);
1737       if (!isInvisibleToCallerAfterRet(UO))
1738         continue;
1739 
1740       if (isWriteAtEndOfFunction(Def)) {
1741         // See through pointer-to-pointer bitcasts
1742         LLVM_DEBUG(dbgs() << "   ... MemoryDef is not accessed until the end "
1743                              "of the function\n");
1744         deleteDeadInstruction(DefI);
1745         ++NumFastStores;
1746         MadeChange = true;
1747       }
1748     }
1749     return MadeChange;
1750   }
1751 
1752   /// \returns true if \p Def is a no-op store, either because it
1753   /// directly stores back a loaded value or stores zero to a calloced object.
1754   bool storeIsNoop(MemoryDef *Def, const Value *DefUO) {
1755     StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst());
1756     MemSetInst *MemSet = dyn_cast<MemSetInst>(Def->getMemoryInst());
1757     Constant *StoredConstant = nullptr;
1758     if (Store)
1759       StoredConstant = dyn_cast<Constant>(Store->getOperand(0));
1760     if (MemSet)
1761       StoredConstant = dyn_cast<Constant>(MemSet->getValue());
1762 
1763     if (StoredConstant && StoredConstant->isNullValue()) {
1764       auto *DefUOInst = dyn_cast<Instruction>(DefUO);
1765       if (DefUOInst) {
1766         if (isCallocLikeFn(DefUOInst, &TLI)) {
1767           auto *UnderlyingDef =
1768               cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst));
1769           // If UnderlyingDef is the clobbering access of Def, no instructions
1770           // between them can modify the memory location.
1771           auto *ClobberDef =
1772               MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def);
1773           return UnderlyingDef == ClobberDef;
1774         }
1775 
1776         if (MemSet) {
1777           if (F.hasFnAttribute(Attribute::SanitizeMemory) ||
1778               F.hasFnAttribute(Attribute::SanitizeAddress) ||
1779               F.hasFnAttribute(Attribute::SanitizeHWAddress) ||
1780               F.getName() == "calloc")
1781             return false;
1782           auto *Malloc = const_cast<CallInst *>(dyn_cast<CallInst>(DefUOInst));
1783           if (!Malloc)
1784             return false;
1785           auto *InnerCallee = Malloc->getCalledFunction();
1786           if (!InnerCallee)
1787             return false;
1788           LibFunc Func;
1789           if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
1790               Func != LibFunc_malloc)
1791             return false;
1792 
1793           auto shouldCreateCalloc = [](CallInst *Malloc, CallInst *Memset) {
1794             // Check for br(icmp ptr, null), truebb, falsebb) pattern at the end
1795             // of malloc block
1796             auto *MallocBB = Malloc->getParent(),
1797                  *MemsetBB = Memset->getParent();
1798             if (MallocBB == MemsetBB)
1799               return true;
1800             auto *Ptr = Memset->getArgOperand(0);
1801             auto *TI = MallocBB->getTerminator();
1802             ICmpInst::Predicate Pred;
1803             BasicBlock *TrueBB, *FalseBB;
1804             if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Ptr), m_Zero()), TrueBB,
1805                                 FalseBB)))
1806               return false;
1807             if (Pred != ICmpInst::ICMP_EQ || MemsetBB != FalseBB)
1808               return false;
1809             return true;
1810           };
1811 
1812           if (Malloc->getOperand(0) == MemSet->getLength()) {
1813             if (shouldCreateCalloc(Malloc, MemSet) &&
1814                 DT.dominates(Malloc, MemSet) &&
1815                 memoryIsNotModifiedBetween(Malloc, MemSet, BatchAA, DL, &DT)) {
1816               IRBuilder<> IRB(Malloc);
1817               const auto &DL = Malloc->getModule()->getDataLayout();
1818               if (auto *Calloc =
1819                       emitCalloc(ConstantInt::get(IRB.getIntPtrTy(DL), 1),
1820                                  Malloc->getArgOperand(0), IRB, TLI)) {
1821                 MemorySSAUpdater Updater(&MSSA);
1822                 auto *LastDef = cast<MemoryDef>(
1823                     Updater.getMemorySSA()->getMemoryAccess(Malloc));
1824                 auto *NewAccess = Updater.createMemoryAccessAfter(
1825                     cast<Instruction>(Calloc), LastDef, LastDef);
1826                 auto *NewAccessMD = cast<MemoryDef>(NewAccess);
1827                 Updater.insertDef(NewAccessMD, /*RenameUses=*/true);
1828                 Updater.removeMemoryAccess(Malloc);
1829                 Malloc->replaceAllUsesWith(Calloc);
1830                 Malloc->eraseFromParent();
1831                 return true;
1832               }
1833               return false;
1834             }
1835           }
1836         }
1837       }
1838     }
1839 
1840     if (!Store)
1841       return false;
1842 
1843     if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) {
1844       if (LoadI->getPointerOperand() == Store->getOperand(1)) {
1845         // Get the defining access for the load.
1846         auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess();
1847         // Fast path: the defining accesses are the same.
1848         if (LoadAccess == Def->getDefiningAccess())
1849           return true;
1850 
1851         // Look through phi accesses. Recursively scan all phi accesses by
1852         // adding them to a worklist. Bail when we run into a memory def that
1853         // does not match LoadAccess.
1854         SetVector<MemoryAccess *> ToCheck;
1855         MemoryAccess *Current =
1856             MSSA.getWalker()->getClobberingMemoryAccess(Def);
1857         // We don't want to bail when we run into the store memory def. But,
1858         // the phi access may point to it. So, pretend like we've already
1859         // checked it.
1860         ToCheck.insert(Def);
1861         ToCheck.insert(Current);
1862         // Start at current (1) to simulate already having checked Def.
1863         for (unsigned I = 1; I < ToCheck.size(); ++I) {
1864           Current = ToCheck[I];
1865           if (auto PhiAccess = dyn_cast<MemoryPhi>(Current)) {
1866             // Check all the operands.
1867             for (auto &Use : PhiAccess->incoming_values())
1868               ToCheck.insert(cast<MemoryAccess>(&Use));
1869             continue;
1870           }
1871 
1872           // If we found a memory def, bail. This happens when we have an
1873           // unrelated write in between an otherwise noop store.
1874           assert(isa<MemoryDef>(Current) &&
1875                  "Only MemoryDefs should reach here.");
1876           // TODO: Skip no alias MemoryDefs that have no aliasing reads.
1877           // We are searching for the definition of the store's destination.
1878           // So, if that is the same definition as the load, then this is a
1879           // noop. Otherwise, fail.
1880           if (LoadAccess != Current)
1881             return false;
1882         }
1883         return true;
1884       }
1885     }
1886 
1887     return false;
1888   }
1889 
1890   bool removePartiallyOverlappedStores(InstOverlapIntervalsTy &IOL) {
1891     bool Changed = false;
1892     for (auto OI : IOL) {
1893       Instruction *DeadI = OI.first;
1894       MemoryLocation Loc = *getLocForWriteEx(DeadI);
1895       assert(isRemovable(DeadI) && "Expect only removable instruction");
1896 
1897       const Value *Ptr = Loc.Ptr->stripPointerCasts();
1898       int64_t DeadStart = 0;
1899       uint64_t DeadSize = Loc.Size.getValue();
1900       GetPointerBaseWithConstantOffset(Ptr, DeadStart, DL);
1901       OverlapIntervalsTy &IntervalMap = OI.second;
1902       Changed |= tryToShortenEnd(DeadI, IntervalMap, DeadStart, DeadSize);
1903       if (IntervalMap.empty())
1904         continue;
1905       Changed |= tryToShortenBegin(DeadI, IntervalMap, DeadStart, DeadSize);
1906     }
1907     return Changed;
1908   }
1909 
1910   /// Eliminates writes to locations where the value that is being written
1911   /// is already stored at the same location.
1912   bool eliminateRedundantStoresOfExistingValues() {
1913     bool MadeChange = false;
1914     LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs that write the "
1915                          "already existing value\n");
1916     for (auto *Def : MemDefs) {
1917       if (SkipStores.contains(Def) || MSSA.isLiveOnEntryDef(Def) ||
1918           !isRemovable(Def->getMemoryInst()))
1919         continue;
1920       auto *UpperDef = dyn_cast<MemoryDef>(Def->getDefiningAccess());
1921       if (!UpperDef || MSSA.isLiveOnEntryDef(UpperDef))
1922         continue;
1923 
1924       Instruction *DefInst = Def->getMemoryInst();
1925       Instruction *UpperInst = UpperDef->getMemoryInst();
1926       auto IsRedundantStore = [this, DefInst,
1927                                UpperInst](MemoryLocation UpperLoc) {
1928         if (DefInst->isIdenticalTo(UpperInst))
1929           return true;
1930         if (auto *MemSetI = dyn_cast<MemSetInst>(UpperInst)) {
1931           if (auto *SI = dyn_cast<StoreInst>(DefInst)) {
1932             auto MaybeDefLoc = getLocForWriteEx(DefInst);
1933             if (!MaybeDefLoc)
1934               return false;
1935             int64_t InstWriteOffset = 0;
1936             int64_t DepWriteOffset = 0;
1937             auto OR = isOverwrite(UpperInst, DefInst, UpperLoc, *MaybeDefLoc,
1938                                   InstWriteOffset, DepWriteOffset);
1939             Value *StoredByte = isBytewiseValue(SI->getValueOperand(), DL);
1940             return StoredByte && StoredByte == MemSetI->getOperand(1) &&
1941                    OR == OW_Complete;
1942           }
1943         }
1944         return false;
1945       };
1946 
1947       auto MaybeUpperLoc = getLocForWriteEx(UpperInst);
1948       if (!MaybeUpperLoc || !IsRedundantStore(*MaybeUpperLoc) ||
1949           isReadClobber(*MaybeUpperLoc, DefInst))
1950         continue;
1951       LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n  DEAD: " << *DefInst
1952                         << '\n');
1953       deleteDeadInstruction(DefInst);
1954       NumRedundantStores++;
1955       MadeChange = true;
1956     }
1957     return MadeChange;
1958   }
1959 };
1960 
1961 static bool eliminateDeadStores(Function &F, AliasAnalysis &AA, MemorySSA &MSSA,
1962                                 DominatorTree &DT, PostDominatorTree &PDT,
1963                                 const TargetLibraryInfo &TLI,
1964                                 const LoopInfo &LI) {
1965   bool MadeChange = false;
1966 
1967   DSEState State(F, AA, MSSA, DT, PDT, TLI, LI);
1968   // For each store:
1969   for (unsigned I = 0; I < State.MemDefs.size(); I++) {
1970     MemoryDef *KillingDef = State.MemDefs[I];
1971     if (State.SkipStores.count(KillingDef))
1972       continue;
1973     Instruction *KillingI = KillingDef->getMemoryInst();
1974 
1975     Optional<MemoryLocation> MaybeKillingLoc;
1976     if (State.isMemTerminatorInst(KillingI))
1977       MaybeKillingLoc = State.getLocForTerminator(KillingI).map(
1978           [](const std::pair<MemoryLocation, bool> &P) { return P.first; });
1979     else
1980       MaybeKillingLoc = State.getLocForWriteEx(KillingI);
1981 
1982     if (!MaybeKillingLoc) {
1983       LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for "
1984                         << *KillingI << "\n");
1985       continue;
1986     }
1987     MemoryLocation KillingLoc = *MaybeKillingLoc;
1988     assert(KillingLoc.Ptr && "KillingLoc should not be null");
1989     const Value *KillingUndObj = getUnderlyingObject(KillingLoc.Ptr);
1990     LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by "
1991                       << *KillingDef << " (" << *KillingI << ")\n");
1992 
1993     unsigned ScanLimit = MemorySSAScanLimit;
1994     unsigned WalkerStepLimit = MemorySSAUpwardsStepLimit;
1995     unsigned PartialLimit = MemorySSAPartialStoreLimit;
1996     // Worklist of MemoryAccesses that may be killed by KillingDef.
1997     SetVector<MemoryAccess *> ToCheck;
1998     ToCheck.insert(KillingDef->getDefiningAccess());
1999 
2000     bool Shortend = false;
2001     bool IsMemTerm = State.isMemTerminatorInst(KillingI);
2002     // Check if MemoryAccesses in the worklist are killed by KillingDef.
2003     for (unsigned I = 0; I < ToCheck.size(); I++) {
2004       MemoryAccess *Current = ToCheck[I];
2005       if (State.SkipStores.count(Current))
2006         continue;
2007 
2008       Optional<MemoryAccess *> MaybeDeadAccess = State.getDomMemoryDef(
2009           KillingDef, Current, KillingLoc, KillingUndObj, ScanLimit,
2010           WalkerStepLimit, IsMemTerm, PartialLimit);
2011 
2012       if (!MaybeDeadAccess) {
2013         LLVM_DEBUG(dbgs() << "  finished walk\n");
2014         continue;
2015       }
2016 
2017       MemoryAccess *DeadAccess = *MaybeDeadAccess;
2018       LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DeadAccess);
2019       if (isa<MemoryPhi>(DeadAccess)) {
2020         LLVM_DEBUG(dbgs() << "\n  ... adding incoming values to worklist\n");
2021         for (Value *V : cast<MemoryPhi>(DeadAccess)->incoming_values()) {
2022           MemoryAccess *IncomingAccess = cast<MemoryAccess>(V);
2023           BasicBlock *IncomingBlock = IncomingAccess->getBlock();
2024           BasicBlock *PhiBlock = DeadAccess->getBlock();
2025 
2026           // We only consider incoming MemoryAccesses that come before the
2027           // MemoryPhi. Otherwise we could discover candidates that do not
2028           // strictly dominate our starting def.
2029           if (State.PostOrderNumbers[IncomingBlock] >
2030               State.PostOrderNumbers[PhiBlock])
2031             ToCheck.insert(IncomingAccess);
2032         }
2033         continue;
2034       }
2035       auto *DeadDefAccess = cast<MemoryDef>(DeadAccess);
2036       Instruction *DeadI = DeadDefAccess->getMemoryInst();
2037       LLVM_DEBUG(dbgs() << " (" << *DeadI << ")\n");
2038       ToCheck.insert(DeadDefAccess->getDefiningAccess());
2039       NumGetDomMemoryDefPassed++;
2040 
2041       if (!DebugCounter::shouldExecute(MemorySSACounter))
2042         continue;
2043 
2044       MemoryLocation DeadLoc = *State.getLocForWriteEx(DeadI);
2045 
2046       if (IsMemTerm) {
2047         const Value *DeadUndObj = getUnderlyingObject(DeadLoc.Ptr);
2048         if (KillingUndObj != DeadUndObj)
2049           continue;
2050         LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *DeadI
2051                           << "\n  KILLER: " << *KillingI << '\n');
2052         State.deleteDeadInstruction(DeadI);
2053         ++NumFastStores;
2054         MadeChange = true;
2055       } else {
2056         // Check if DeadI overwrites KillingI.
2057         int64_t KillingOffset = 0;
2058         int64_t DeadOffset = 0;
2059         OverwriteResult OR = State.isOverwrite(
2060             KillingI, DeadI, KillingLoc, DeadLoc, KillingOffset, DeadOffset);
2061         if (OR == OW_MaybePartial) {
2062           auto Iter = State.IOLs.insert(
2063               std::make_pair<BasicBlock *, InstOverlapIntervalsTy>(
2064                   DeadI->getParent(), InstOverlapIntervalsTy()));
2065           auto &IOL = Iter.first->second;
2066           OR = isPartialOverwrite(KillingLoc, DeadLoc, KillingOffset,
2067                                   DeadOffset, DeadI, IOL);
2068         }
2069 
2070         if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) {
2071           auto *DeadSI = dyn_cast<StoreInst>(DeadI);
2072           auto *KillingSI = dyn_cast<StoreInst>(KillingI);
2073           // We are re-using tryToMergePartialOverlappingStores, which requires
2074           // DeadSI to dominate DeadSI.
2075           // TODO: implement tryToMergeParialOverlappingStores using MemorySSA.
2076           if (DeadSI && KillingSI && DT.dominates(DeadSI, KillingSI)) {
2077             if (Constant *Merged = tryToMergePartialOverlappingStores(
2078                     KillingSI, DeadSI, KillingOffset, DeadOffset, State.DL,
2079                     State.BatchAA, &DT)) {
2080 
2081               // Update stored value of earlier store to merged constant.
2082               DeadSI->setOperand(0, Merged);
2083               ++NumModifiedStores;
2084               MadeChange = true;
2085 
2086               Shortend = true;
2087               // Remove killing store and remove any outstanding overlap
2088               // intervals for the updated store.
2089               State.deleteDeadInstruction(KillingSI);
2090               auto I = State.IOLs.find(DeadSI->getParent());
2091               if (I != State.IOLs.end())
2092                 I->second.erase(DeadSI);
2093               break;
2094             }
2095           }
2096         }
2097 
2098         if (OR == OW_Complete) {
2099           LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: " << *DeadI
2100                             << "\n  KILLER: " << *KillingI << '\n');
2101           State.deleteDeadInstruction(DeadI);
2102           ++NumFastStores;
2103           MadeChange = true;
2104         }
2105       }
2106     }
2107 
2108     // Check if the store is a no-op.
2109     if (!Shortend && isRemovable(KillingI) &&
2110         State.storeIsNoop(KillingDef, KillingUndObj)) {
2111       LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n  DEAD: " << *KillingI
2112                         << '\n');
2113       State.deleteDeadInstruction(KillingI);
2114       NumRedundantStores++;
2115       MadeChange = true;
2116       continue;
2117     }
2118   }
2119 
2120   if (EnablePartialOverwriteTracking)
2121     for (auto &KV : State.IOLs)
2122       MadeChange |= State.removePartiallyOverlappedStores(KV.second);
2123 
2124   MadeChange |= State.eliminateRedundantStoresOfExistingValues();
2125   MadeChange |= State.eliminateDeadWritesAtEndOfFunction();
2126   return MadeChange;
2127 }
2128 } // end anonymous namespace
2129 
2130 //===----------------------------------------------------------------------===//
2131 // DSE Pass
2132 //===----------------------------------------------------------------------===//
2133 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
2134   AliasAnalysis &AA = AM.getResult<AAManager>(F);
2135   const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2136   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
2137   MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2138   PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
2139   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
2140 
2141   bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI);
2142 
2143 #ifdef LLVM_ENABLE_STATS
2144   if (AreStatisticsEnabled())
2145     for (auto &I : instructions(F))
2146       NumRemainingStores += isa<StoreInst>(&I);
2147 #endif
2148 
2149   if (!Changed)
2150     return PreservedAnalyses::all();
2151 
2152   PreservedAnalyses PA;
2153   PA.preserveSet<CFGAnalyses>();
2154   PA.preserve<MemorySSAAnalysis>();
2155   PA.preserve<LoopAnalysis>();
2156   return PA;
2157 }
2158 
2159 namespace {
2160 
2161 /// A legacy pass for the legacy pass manager that wraps \c DSEPass.
2162 class DSELegacyPass : public FunctionPass {
2163 public:
2164   static char ID; // Pass identification, replacement for typeid
2165 
2166   DSELegacyPass() : FunctionPass(ID) {
2167     initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
2168   }
2169 
2170   bool runOnFunction(Function &F) override {
2171     if (skipFunction(F))
2172       return false;
2173 
2174     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2175     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2176     const TargetLibraryInfo &TLI =
2177         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2178     MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2179     PostDominatorTree &PDT =
2180         getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
2181     LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2182 
2183     bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI);
2184 
2185 #ifdef LLVM_ENABLE_STATS
2186     if (AreStatisticsEnabled())
2187       for (auto &I : instructions(F))
2188         NumRemainingStores += isa<StoreInst>(&I);
2189 #endif
2190 
2191     return Changed;
2192   }
2193 
2194   void getAnalysisUsage(AnalysisUsage &AU) const override {
2195     AU.setPreservesCFG();
2196     AU.addRequired<AAResultsWrapperPass>();
2197     AU.addRequired<TargetLibraryInfoWrapperPass>();
2198     AU.addPreserved<GlobalsAAWrapperPass>();
2199     AU.addRequired<DominatorTreeWrapperPass>();
2200     AU.addPreserved<DominatorTreeWrapperPass>();
2201     AU.addRequired<PostDominatorTreeWrapperPass>();
2202     AU.addRequired<MemorySSAWrapperPass>();
2203     AU.addPreserved<PostDominatorTreeWrapperPass>();
2204     AU.addPreserved<MemorySSAWrapperPass>();
2205     AU.addRequired<LoopInfoWrapperPass>();
2206     AU.addPreserved<LoopInfoWrapperPass>();
2207   }
2208 };
2209 
2210 } // end anonymous namespace
2211 
2212 char DSELegacyPass::ID = 0;
2213 
2214 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
2215                       false)
2216 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2217 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
2218 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2219 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2220 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2221 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2222 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2223 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2224 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
2225                     false)
2226 
2227 FunctionPass *llvm::createDeadStoreEliminationPass() {
2228   return new DSELegacyPass();
2229 }
2230