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