1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs various transformations related to eliminating memcpy
10 // calls, or transforming sets of stores into memset's.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/GlobalsModRef.h"
25 #include "llvm/Analysis/Loads.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/Analysis/MemorySSA.h"
28 #include "llvm/Analysis/MemorySSAUpdater.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GetElementPtrTypeIterator.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/Scalar.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstdint>
64 #include <utility>
65 
66 using namespace llvm;
67 
68 #define DEBUG_TYPE "memcpyopt"
69 
70 static cl::opt<bool> EnableMemCpyOptWithoutLibcalls(
71     "enable-memcpyopt-without-libcalls", cl::init(false), cl::Hidden,
72     cl::ZeroOrMore,
73     cl::desc("Enable memcpyopt even when libcalls are disabled"));
74 
75 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
76 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
77 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
78 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
79 STATISTIC(NumCallSlot,    "Number of call slot optimizations performed");
80 
81 namespace {
82 
83 /// Represents a range of memset'd bytes with the ByteVal value.
84 /// This allows us to analyze stores like:
85 ///   store 0 -> P+1
86 ///   store 0 -> P+0
87 ///   store 0 -> P+3
88 ///   store 0 -> P+2
89 /// which sometimes happens with stores to arrays of structs etc.  When we see
90 /// the first store, we make a range [1, 2).  The second store extends the range
91 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
92 /// two ranges into [0, 3) which is memset'able.
93 struct MemsetRange {
94   // Start/End - A semi range that describes the span that this range covers.
95   // The range is closed at the start and open at the end: [Start, End).
96   int64_t Start, End;
97 
98   /// StartPtr - The getelementptr instruction that points to the start of the
99   /// range.
100   Value *StartPtr;
101 
102   /// Alignment - The known alignment of the first store.
103   unsigned Alignment;
104 
105   /// TheStores - The actual stores that make up this range.
106   SmallVector<Instruction*, 16> TheStores;
107 
108   bool isProfitableToUseMemset(const DataLayout &DL) const;
109 };
110 
111 } // end anonymous namespace
112 
113 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
114   // If we found more than 4 stores to merge or 16 bytes, use memset.
115   if (TheStores.size() >= 4 || End-Start >= 16) return true;
116 
117   // If there is nothing to merge, don't do anything.
118   if (TheStores.size() < 2) return false;
119 
120   // If any of the stores are a memset, then it is always good to extend the
121   // memset.
122   for (Instruction *SI : TheStores)
123     if (!isa<StoreInst>(SI))
124       return true;
125 
126   // Assume that the code generator is capable of merging pairs of stores
127   // together if it wants to.
128   if (TheStores.size() == 2) return false;
129 
130   // If we have fewer than 8 stores, it can still be worthwhile to do this.
131   // For example, merging 4 i8 stores into an i32 store is useful almost always.
132   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
133   // memset will be split into 2 32-bit stores anyway) and doing so can
134   // pessimize the llvm optimizer.
135   //
136   // Since we don't have perfect knowledge here, make some assumptions: assume
137   // the maximum GPR width is the same size as the largest legal integer
138   // size. If so, check to see whether we will end up actually reducing the
139   // number of stores used.
140   unsigned Bytes = unsigned(End-Start);
141   unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
142   if (MaxIntSize == 0)
143     MaxIntSize = 1;
144   unsigned NumPointerStores = Bytes / MaxIntSize;
145 
146   // Assume the remaining bytes if any are done a byte at a time.
147   unsigned NumByteStores = Bytes % MaxIntSize;
148 
149   // If we will reduce the # stores (according to this heuristic), do the
150   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
151   // etc.
152   return TheStores.size() > NumPointerStores+NumByteStores;
153 }
154 
155 namespace {
156 
157 class MemsetRanges {
158   using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
159 
160   /// A sorted list of the memset ranges.
161   SmallVector<MemsetRange, 8> Ranges;
162 
163   const DataLayout &DL;
164 
165 public:
166   MemsetRanges(const DataLayout &DL) : DL(DL) {}
167 
168   using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
169 
170   const_iterator begin() const { return Ranges.begin(); }
171   const_iterator end() const { return Ranges.end(); }
172   bool empty() const { return Ranges.empty(); }
173 
174   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
175     if (auto *SI = dyn_cast<StoreInst>(Inst))
176       addStore(OffsetFromFirst, SI);
177     else
178       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
179   }
180 
181   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
182     TypeSize StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
183     assert(!StoreSize.isScalable() && "Can't track scalable-typed stores");
184     addRange(OffsetFromFirst, StoreSize.getFixedSize(), SI->getPointerOperand(),
185              SI->getAlign().value(), SI);
186   }
187 
188   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
189     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
190     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
191   }
192 
193   void addRange(int64_t Start, int64_t Size, Value *Ptr,
194                 unsigned Alignment, Instruction *Inst);
195 };
196 
197 } // end anonymous namespace
198 
199 /// Add a new store to the MemsetRanges data structure.  This adds a
200 /// new range for the specified store at the specified offset, merging into
201 /// existing ranges as appropriate.
202 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
203                             unsigned Alignment, Instruction *Inst) {
204   int64_t End = Start+Size;
205 
206   range_iterator I = partition_point(
207       Ranges, [=](const MemsetRange &O) { return O.End < Start; });
208 
209   // We now know that I == E, in which case we didn't find anything to merge
210   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
211   // to insert a new range.  Handle this now.
212   if (I == Ranges.end() || End < I->Start) {
213     MemsetRange &R = *Ranges.insert(I, MemsetRange());
214     R.Start        = Start;
215     R.End          = End;
216     R.StartPtr     = Ptr;
217     R.Alignment    = Alignment;
218     R.TheStores.push_back(Inst);
219     return;
220   }
221 
222   // This store overlaps with I, add it.
223   I->TheStores.push_back(Inst);
224 
225   // At this point, we may have an interval that completely contains our store.
226   // If so, just add it to the interval and return.
227   if (I->Start <= Start && I->End >= End)
228     return;
229 
230   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
231   // but is not entirely contained within the range.
232 
233   // See if the range extends the start of the range.  In this case, it couldn't
234   // possibly cause it to join the prior range, because otherwise we would have
235   // stopped on *it*.
236   if (Start < I->Start) {
237     I->Start = Start;
238     I->StartPtr = Ptr;
239     I->Alignment = Alignment;
240   }
241 
242   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
243   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
244   // End.
245   if (End > I->End) {
246     I->End = End;
247     range_iterator NextI = I;
248     while (++NextI != Ranges.end() && End >= NextI->Start) {
249       // Merge the range in.
250       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
251       if (NextI->End > I->End)
252         I->End = NextI->End;
253       Ranges.erase(NextI);
254       NextI = I;
255     }
256   }
257 }
258 
259 //===----------------------------------------------------------------------===//
260 //                         MemCpyOptLegacyPass Pass
261 //===----------------------------------------------------------------------===//
262 
263 namespace {
264 
265 class MemCpyOptLegacyPass : public FunctionPass {
266   MemCpyOptPass Impl;
267 
268 public:
269   static char ID; // Pass identification, replacement for typeid
270 
271   MemCpyOptLegacyPass() : FunctionPass(ID) {
272     initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
273   }
274 
275   bool runOnFunction(Function &F) override;
276 
277 private:
278   // This transformation requires dominator postdominator info
279   void getAnalysisUsage(AnalysisUsage &AU) const override {
280     AU.setPreservesCFG();
281     AU.addRequired<AssumptionCacheTracker>();
282     AU.addRequired<DominatorTreeWrapperPass>();
283     AU.addPreserved<DominatorTreeWrapperPass>();
284     AU.addPreserved<GlobalsAAWrapperPass>();
285     AU.addRequired<TargetLibraryInfoWrapperPass>();
286     AU.addRequired<AAResultsWrapperPass>();
287     AU.addPreserved<AAResultsWrapperPass>();
288     AU.addRequired<MemorySSAWrapperPass>();
289     AU.addPreserved<MemorySSAWrapperPass>();
290   }
291 };
292 
293 } // end anonymous namespace
294 
295 char MemCpyOptLegacyPass::ID = 0;
296 
297 /// The public interface to this file...
298 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
299 
300 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
301                       false, false)
302 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
303 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
304 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
305 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
306 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
307 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
308 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
309                     false, false)
310 
311 // Check that V is either not accessible by the caller, or unwinding cannot
312 // occur between Start and End.
313 static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
314                                          Instruction *End) {
315   assert(Start->getParent() == End->getParent() && "Must be in same block");
316   if (!Start->getFunction()->doesNotThrow() &&
317       !isa<AllocaInst>(getUnderlyingObject(V))) {
318     for (const Instruction &I :
319          make_range(Start->getIterator(), End->getIterator())) {
320       if (I.mayThrow())
321         return true;
322     }
323   }
324   return false;
325 }
326 
327 void MemCpyOptPass::eraseInstruction(Instruction *I) {
328   MSSAU->removeMemoryAccess(I);
329   I->eraseFromParent();
330 }
331 
332 // Check for mod or ref of Loc between Start and End, excluding both boundaries.
333 // Start and End must be in the same block
334 static bool accessedBetween(AliasAnalysis &AA, MemoryLocation Loc,
335                             const MemoryUseOrDef *Start,
336                             const MemoryUseOrDef *End) {
337   assert(Start->getBlock() == End->getBlock() && "Only local supported");
338   for (const MemoryAccess &MA :
339        make_range(++Start->getIterator(), End->getIterator())) {
340     if (isModOrRefSet(AA.getModRefInfo(cast<MemoryUseOrDef>(MA).getMemoryInst(),
341                                        Loc)))
342       return true;
343   }
344   return false;
345 }
346 
347 // Check for mod of Loc between Start and End, excluding both boundaries.
348 // Start and End can be in different blocks.
349 static bool writtenBetween(MemorySSA *MSSA, MemoryLocation Loc,
350                            const MemoryUseOrDef *Start,
351                            const MemoryUseOrDef *End) {
352   // TODO: Only walk until we hit Start.
353   MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
354       End->getDefiningAccess(), Loc);
355   return !MSSA->dominates(Clobber, Start);
356 }
357 
358 /// When scanning forward over instructions, we look for some other patterns to
359 /// fold away. In particular, this looks for stores to neighboring locations of
360 /// memory. If it sees enough consecutive ones, it attempts to merge them
361 /// together into a memcpy/memset.
362 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
363                                                  Value *StartPtr,
364                                                  Value *ByteVal) {
365   const DataLayout &DL = StartInst->getModule()->getDataLayout();
366 
367   // We can't track scalable types
368   if (auto *SI = dyn_cast<StoreInst>(StartInst))
369     if (DL.getTypeStoreSize(SI->getOperand(0)->getType()).isScalable())
370       return nullptr;
371 
372   // Okay, so we now have a single store that can be splatable.  Scan to find
373   // all subsequent stores of the same value to offset from the same pointer.
374   // Join these together into ranges, so we can decide whether contiguous blocks
375   // are stored.
376   MemsetRanges Ranges(DL);
377 
378   BasicBlock::iterator BI(StartInst);
379 
380   // Keeps track of the last memory use or def before the insertion point for
381   // the new memset. The new MemoryDef for the inserted memsets will be inserted
382   // after MemInsertPoint. It points to either LastMemDef or to the last user
383   // before the insertion point of the memset, if there are any such users.
384   MemoryUseOrDef *MemInsertPoint = nullptr;
385   // Keeps track of the last MemoryDef between StartInst and the insertion point
386   // for the new memset. This will become the defining access of the inserted
387   // memsets.
388   MemoryDef *LastMemDef = nullptr;
389   for (++BI; !BI->isTerminator(); ++BI) {
390     auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
391         MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
392     if (CurrentAcc) {
393       MemInsertPoint = CurrentAcc;
394       if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
395         LastMemDef = CurrentDef;
396     }
397 
398     // Calls that only access inaccessible memory do not block merging
399     // accessible stores.
400     if (auto *CB = dyn_cast<CallBase>(BI)) {
401       if (CB->onlyAccessesInaccessibleMemory())
402         continue;
403     }
404 
405     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
406       // If the instruction is readnone, ignore it, otherwise bail out.  We
407       // don't even allow readonly here because we don't want something like:
408       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
409       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
410         break;
411       continue;
412     }
413 
414     if (auto *NextStore = dyn_cast<StoreInst>(BI)) {
415       // If this is a store, see if we can merge it in.
416       if (!NextStore->isSimple()) break;
417 
418       Value *StoredVal = NextStore->getValueOperand();
419 
420       // Don't convert stores of non-integral pointer types to memsets (which
421       // stores integers).
422       if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
423         break;
424 
425       // We can't track ranges involving scalable types.
426       if (DL.getTypeStoreSize(StoredVal->getType()).isScalable())
427         break;
428 
429       // Check to see if this stored value is of the same byte-splattable value.
430       Value *StoredByte = isBytewiseValue(StoredVal, DL);
431       if (isa<UndefValue>(ByteVal) && StoredByte)
432         ByteVal = StoredByte;
433       if (ByteVal != StoredByte)
434         break;
435 
436       // Check to see if this store is to a constant offset from the start ptr.
437       Optional<int64_t> Offset =
438           isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
439       if (!Offset)
440         break;
441 
442       Ranges.addStore(*Offset, NextStore);
443     } else {
444       auto *MSI = cast<MemSetInst>(BI);
445 
446       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
447           !isa<ConstantInt>(MSI->getLength()))
448         break;
449 
450       // Check to see if this store is to a constant offset from the start ptr.
451       Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
452       if (!Offset)
453         break;
454 
455       Ranges.addMemSet(*Offset, MSI);
456     }
457   }
458 
459   // If we have no ranges, then we just had a single store with nothing that
460   // could be merged in.  This is a very common case of course.
461   if (Ranges.empty())
462     return nullptr;
463 
464   // If we had at least one store that could be merged in, add the starting
465   // store as well.  We try to avoid this unless there is at least something
466   // interesting as a small compile-time optimization.
467   Ranges.addInst(0, StartInst);
468 
469   // If we create any memsets, we put it right before the first instruction that
470   // isn't part of the memset block.  This ensure that the memset is dominated
471   // by any addressing instruction needed by the start of the block.
472   IRBuilder<> Builder(&*BI);
473 
474   // Now that we have full information about ranges, loop over the ranges and
475   // emit memset's for anything big enough to be worthwhile.
476   Instruction *AMemSet = nullptr;
477   for (const MemsetRange &Range : Ranges) {
478     if (Range.TheStores.size() == 1) continue;
479 
480     // If it is profitable to lower this range to memset, do so now.
481     if (!Range.isProfitableToUseMemset(DL))
482       continue;
483 
484     // Otherwise, we do want to transform this!  Create a new memset.
485     // Get the starting pointer of the block.
486     StartPtr = Range.StartPtr;
487 
488     AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
489                                    MaybeAlign(Range.Alignment));
490     LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
491                                                    : Range.TheStores) dbgs()
492                                               << *SI << '\n';
493                dbgs() << "With: " << *AMemSet << '\n');
494     if (!Range.TheStores.empty())
495       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
496 
497     assert(LastMemDef && MemInsertPoint &&
498            "Both LastMemDef and MemInsertPoint need to be set");
499     auto *NewDef =
500         cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
501                             ? MSSAU->createMemoryAccessBefore(
502                                   AMemSet, LastMemDef, MemInsertPoint)
503                             : MSSAU->createMemoryAccessAfter(
504                                   AMemSet, LastMemDef, MemInsertPoint));
505     MSSAU->insertDef(NewDef, /*RenameUses=*/true);
506     LastMemDef = NewDef;
507     MemInsertPoint = NewDef;
508 
509     // Zap all the stores.
510     for (Instruction *SI : Range.TheStores)
511       eraseInstruction(SI);
512 
513     ++NumMemSetInfer;
514   }
515 
516   return AMemSet;
517 }
518 
519 // This method try to lift a store instruction before position P.
520 // It will lift the store and its argument + that anything that
521 // may alias with these.
522 // The method returns true if it was successful.
523 bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
524   // If the store alias this position, early bail out.
525   MemoryLocation StoreLoc = MemoryLocation::get(SI);
526   if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
527     return false;
528 
529   // Keep track of the arguments of all instruction we plan to lift
530   // so we can make sure to lift them as well if appropriate.
531   DenseSet<Instruction*> Args;
532   if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
533     if (Ptr->getParent() == SI->getParent())
534       Args.insert(Ptr);
535 
536   // Instruction to lift before P.
537   SmallVector<Instruction *, 8> ToLift{SI};
538 
539   // Memory locations of lifted instructions.
540   SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
541 
542   // Lifted calls.
543   SmallVector<const CallBase *, 8> Calls;
544 
545   const MemoryLocation LoadLoc = MemoryLocation::get(LI);
546 
547   for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
548     auto *C = &*I;
549 
550     // Make sure hoisting does not perform a store that was not guaranteed to
551     // happen.
552     if (!isGuaranteedToTransferExecutionToSuccessor(C))
553       return false;
554 
555     bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None));
556 
557     bool NeedLift = false;
558     if (Args.erase(C))
559       NeedLift = true;
560     else if (MayAlias) {
561       NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
562         return isModOrRefSet(AA->getModRefInfo(C, ML));
563       });
564 
565       if (!NeedLift)
566         NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
567           return isModOrRefSet(AA->getModRefInfo(C, Call));
568         });
569     }
570 
571     if (!NeedLift)
572       continue;
573 
574     if (MayAlias) {
575       // Since LI is implicitly moved downwards past the lifted instructions,
576       // none of them may modify its source.
577       if (isModSet(AA->getModRefInfo(C, LoadLoc)))
578         return false;
579       else if (const auto *Call = dyn_cast<CallBase>(C)) {
580         // If we can't lift this before P, it's game over.
581         if (isModOrRefSet(AA->getModRefInfo(P, Call)))
582           return false;
583 
584         Calls.push_back(Call);
585       } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
586         // If we can't lift this before P, it's game over.
587         auto ML = MemoryLocation::get(C);
588         if (isModOrRefSet(AA->getModRefInfo(P, ML)))
589           return false;
590 
591         MemLocs.push_back(ML);
592       } else
593         // We don't know how to lift this instruction.
594         return false;
595     }
596 
597     ToLift.push_back(C);
598     for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
599       if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
600         if (A->getParent() == SI->getParent()) {
601           // Cannot hoist user of P above P
602           if(A == P) return false;
603           Args.insert(A);
604         }
605       }
606   }
607 
608   // Find MSSA insertion point. Normally P will always have a corresponding
609   // memory access before which we can insert. However, with non-standard AA
610   // pipelines, there may be a mismatch between AA and MSSA, in which case we
611   // will scan for a memory access before P. In either case, we know for sure
612   // that at least the load will have a memory access.
613   // TODO: Simplify this once P will be determined by MSSA, in which case the
614   // discrepancy can no longer occur.
615   MemoryUseOrDef *MemInsertPoint = nullptr;
616   if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
617     MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
618   } else {
619     const Instruction *ConstP = P;
620     for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
621                                            ++LI->getReverseIterator())) {
622       if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
623         MemInsertPoint = MA;
624         break;
625       }
626     }
627   }
628 
629   // We made it, we need to lift.
630   for (auto *I : llvm::reverse(ToLift)) {
631     LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
632     I->moveBefore(P);
633     assert(MemInsertPoint && "Must have found insert point");
634     if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
635       MSSAU->moveAfter(MA, MemInsertPoint);
636       MemInsertPoint = MA;
637     }
638   }
639 
640   return true;
641 }
642 
643 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
644   if (!SI->isSimple()) return false;
645 
646   // Avoid merging nontemporal stores since the resulting
647   // memcpy/memset would not be able to preserve the nontemporal hint.
648   // In theory we could teach how to propagate the !nontemporal metadata to
649   // memset calls. However, that change would force the backend to
650   // conservatively expand !nontemporal memset calls back to sequences of
651   // store instructions (effectively undoing the merging).
652   if (SI->getMetadata(LLVMContext::MD_nontemporal))
653     return false;
654 
655   const DataLayout &DL = SI->getModule()->getDataLayout();
656 
657   Value *StoredVal = SI->getValueOperand();
658 
659   // Not all the transforms below are correct for non-integral pointers, bail
660   // until we've audited the individual pieces.
661   if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
662     return false;
663 
664   // Load to store forwarding can be interpreted as memcpy.
665   if (auto *LI = dyn_cast<LoadInst>(StoredVal)) {
666     if (LI->isSimple() && LI->hasOneUse() &&
667         LI->getParent() == SI->getParent()) {
668 
669       auto *T = LI->getType();
670       // Don't introduce calls to memcpy/memmove intrinsics out of thin air if
671       // the corresponding libcalls are not available.
672       // TODO: We should really distinguish between libcall availability and
673       // our ability to introduce intrinsics.
674       if (T->isAggregateType() &&
675           (EnableMemCpyOptWithoutLibcalls ||
676            (TLI->has(LibFunc_memcpy) && TLI->has(LibFunc_memmove)))) {
677         MemoryLocation LoadLoc = MemoryLocation::get(LI);
678 
679         // We use alias analysis to check if an instruction may store to
680         // the memory we load from in between the load and the store. If
681         // such an instruction is found, we try to promote there instead
682         // of at the store position.
683         // TODO: Can use MSSA for this.
684         Instruction *P = SI;
685         for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
686           if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
687             P = &I;
688             break;
689           }
690         }
691 
692         // We found an instruction that may write to the loaded memory.
693         // We can try to promote at this position instead of the store
694         // position if nothing aliases the store memory after this and the store
695         // destination is not in the range.
696         if (P && P != SI) {
697           if (!moveUp(SI, P, LI))
698             P = nullptr;
699         }
700 
701         // If a valid insertion position is found, then we can promote
702         // the load/store pair to a memcpy.
703         if (P) {
704           // If we load from memory that may alias the memory we store to,
705           // memmove must be used to preserve semantic. If not, memcpy can
706           // be used. Also, if we load from constant memory, memcpy can be used
707           // as the constant memory won't be modified.
708           bool UseMemMove = false;
709           if (isModSet(AA->getModRefInfo(SI, LoadLoc)))
710             UseMemMove = true;
711 
712           uint64_t Size = DL.getTypeStoreSize(T);
713 
714           IRBuilder<> Builder(P);
715           Instruction *M;
716           if (UseMemMove)
717             M = Builder.CreateMemMove(
718                 SI->getPointerOperand(), SI->getAlign(),
719                 LI->getPointerOperand(), LI->getAlign(), Size);
720           else
721             M = Builder.CreateMemCpy(
722                 SI->getPointerOperand(), SI->getAlign(),
723                 LI->getPointerOperand(), LI->getAlign(), Size);
724 
725           LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
726                             << *M << "\n");
727 
728           auto *LastDef =
729               cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
730           auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
731           MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
732 
733           eraseInstruction(SI);
734           eraseInstruction(LI);
735           ++NumMemCpyInstr;
736 
737           // Make sure we do not invalidate the iterator.
738           BBI = M->getIterator();
739           return true;
740         }
741       }
742 
743       // Detect cases where we're performing call slot forwarding, but
744       // happen to be using a load-store pair to implement it, rather than
745       // a memcpy.
746       CallInst *C = nullptr;
747       if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
748               MSSA->getWalker()->getClobberingMemoryAccess(LI))) {
749         // The load most post-dom the call. Limit to the same block for now.
750         // TODO: Support non-local call-slot optimization?
751         if (LoadClobber->getBlock() == SI->getParent())
752           C = dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
753       }
754 
755       if (C) {
756         // Check that nothing touches the dest of the "copy" between
757         // the call and the store.
758         MemoryLocation StoreLoc = MemoryLocation::get(SI);
759         if (accessedBetween(*AA, StoreLoc, MSSA->getMemoryAccess(C),
760                             MSSA->getMemoryAccess(SI)))
761           C = nullptr;
762       }
763 
764       if (C) {
765         bool changed = performCallSlotOptzn(
766             LI, SI, SI->getPointerOperand()->stripPointerCasts(),
767             LI->getPointerOperand()->stripPointerCasts(),
768             DL.getTypeStoreSize(SI->getOperand(0)->getType()),
769             commonAlignment(SI->getAlign(), LI->getAlign()), C);
770         if (changed) {
771           eraseInstruction(SI);
772           eraseInstruction(LI);
773           ++NumMemCpyInstr;
774           return true;
775         }
776       }
777     }
778   }
779 
780   // The following code creates memset intrinsics out of thin air. Don't do
781   // this if the corresponding libfunc is not available.
782   // TODO: We should really distinguish between libcall availability and
783   // our ability to introduce intrinsics.
784   if (!(TLI->has(LibFunc_memset) || EnableMemCpyOptWithoutLibcalls))
785     return false;
786 
787   // There are two cases that are interesting for this code to handle: memcpy
788   // and memset.  Right now we only handle memset.
789 
790   // Ensure that the value being stored is something that can be memset'able a
791   // byte at a time like "0" or "-1" or any width, as well as things like
792   // 0xA0A0A0A0 and 0.0.
793   auto *V = SI->getOperand(0);
794   if (Value *ByteVal = isBytewiseValue(V, DL)) {
795     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
796                                               ByteVal)) {
797       BBI = I->getIterator(); // Don't invalidate iterator.
798       return true;
799     }
800 
801     // If we have an aggregate, we try to promote it to memset regardless
802     // of opportunity for merging as it can expose optimization opportunities
803     // in subsequent passes.
804     auto *T = V->getType();
805     if (T->isAggregateType()) {
806       uint64_t Size = DL.getTypeStoreSize(T);
807       IRBuilder<> Builder(SI);
808       auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
809                                      SI->getAlign());
810 
811       LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
812 
813       // The newly inserted memset is immediately overwritten by the original
814       // store, so we do not need to rename uses.
815       auto *StoreDef = cast<MemoryDef>(MSSA->getMemoryAccess(SI));
816       auto *NewAccess = MSSAU->createMemoryAccessBefore(
817           M, StoreDef->getDefiningAccess(), StoreDef);
818       MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/false);
819 
820       eraseInstruction(SI);
821       NumMemSetInfer++;
822 
823       // Make sure we do not invalidate the iterator.
824       BBI = M->getIterator();
825       return true;
826     }
827   }
828 
829   return false;
830 }
831 
832 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
833   // See if there is another memset or store neighboring this memset which
834   // allows us to widen out the memset to do a single larger store.
835   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
836     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
837                                               MSI->getValue())) {
838       BBI = I->getIterator(); // Don't invalidate iterator.
839       return true;
840     }
841   return false;
842 }
843 
844 /// Takes a memcpy and a call that it depends on,
845 /// and checks for the possibility of a call slot optimization by having
846 /// the call write its result directly into the destination of the memcpy.
847 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
848                                          Instruction *cpyStore, Value *cpyDest,
849                                          Value *cpySrc, TypeSize cpySize,
850                                          Align cpyAlign, CallInst *C) {
851   // The general transformation to keep in mind is
852   //
853   //   call @func(..., src, ...)
854   //   memcpy(dest, src, ...)
855   //
856   // ->
857   //
858   //   memcpy(dest, src, ...)
859   //   call @func(..., dest, ...)
860   //
861   // Since moving the memcpy is technically awkward, we additionally check that
862   // src only holds uninitialized values at the moment of the call, meaning that
863   // the memcpy can be discarded rather than moved.
864 
865   // We can't optimize scalable types.
866   if (cpySize.isScalable())
867     return false;
868 
869   // Lifetime marks shouldn't be operated on.
870   if (Function *F = C->getCalledFunction())
871     if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
872       return false;
873 
874   // Require that src be an alloca.  This simplifies the reasoning considerably.
875   auto *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
876   if (!srcAlloca)
877     return false;
878 
879   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
880   if (!srcArraySize)
881     return false;
882 
883   const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
884   uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
885                      srcArraySize->getZExtValue();
886 
887   if (cpySize < srcSize)
888     return false;
889 
890   // Check that accessing the first srcSize bytes of dest will not cause a
891   // trap.  Otherwise the transform is invalid since it might cause a trap
892   // to occur earlier than it otherwise would.
893   if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpySize),
894                                           DL, C, DT)) {
895     LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer not dereferenceable\n");
896     return false;
897   }
898 
899   // Make sure that nothing can observe cpyDest being written early. There are
900   // a number of cases to consider:
901   //  1. cpyDest cannot be accessed between C and cpyStore as a precondition of
902   //     the transform.
903   //  2. C itself may not access cpyDest (prior to the transform). This is
904   //     checked further below.
905   //  3. If cpyDest is accessible to the caller of this function (potentially
906   //     captured and not based on an alloca), we need to ensure that we cannot
907   //     unwind between C and cpyStore. This is checked here.
908   //  4. If cpyDest is potentially captured, there may be accesses to it from
909   //     another thread. In this case, we need to check that cpyStore is
910   //     guaranteed to be executed if C is. As it is a non-atomic access, it
911   //     renders accesses from other threads undefined.
912   //     TODO: This is currently not checked.
913   if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore)) {
914     LLVM_DEBUG(dbgs() << "Call Slot: Dest may be visible through unwinding");
915     return false;
916   }
917 
918   // Check that dest points to memory that is at least as aligned as src.
919   Align srcAlign = srcAlloca->getAlign();
920   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
921   // If dest is not aligned enough and we can't increase its alignment then
922   // bail out.
923   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
924     return false;
925 
926   // Check that src is not accessed except via the call and the memcpy.  This
927   // guarantees that it holds only undefined values when passed in (so the final
928   // memcpy can be dropped), that it is not read or written between the call and
929   // the memcpy, and that writing beyond the end of it is undefined.
930   SmallVector<User *, 8> srcUseList(srcAlloca->users());
931   while (!srcUseList.empty()) {
932     User *U = srcUseList.pop_back_val();
933 
934     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
935       append_range(srcUseList, U->users());
936       continue;
937     }
938     if (const auto *G = dyn_cast<GetElementPtrInst>(U)) {
939       if (!G->hasAllZeroIndices())
940         return false;
941 
942       append_range(srcUseList, U->users());
943       continue;
944     }
945     if (const auto *IT = dyn_cast<IntrinsicInst>(U))
946       if (IT->isLifetimeStartOrEnd())
947         continue;
948 
949     if (U != C && U != cpyLoad)
950       return false;
951   }
952 
953   // Check whether src is captured by the called function, in which case there
954   // may be further indirect uses of src.
955   bool SrcIsCaptured = any_of(C->args(), [&](Use &U) {
956     return U->stripPointerCasts() == cpySrc &&
957            !C->doesNotCapture(C->getArgOperandNo(&U));
958   });
959 
960   // If src is captured, then check whether there are any potential uses of
961   // src through the captured pointer before the lifetime of src ends, either
962   // due to a lifetime.end or a return from the function.
963   if (SrcIsCaptured) {
964     // Check that dest is not captured before/at the call. We have already
965     // checked that src is not captured before it. If either had been captured,
966     // then the call might be comparing the argument against the captured dest
967     // or src pointer.
968     Value *DestObj = getUnderlyingObject(cpyDest);
969     if (!isIdentifiedFunctionLocal(DestObj) ||
970         PointerMayBeCapturedBefore(DestObj, /* ReturnCaptures */ true,
971                                    /* StoreCaptures */ true, C, DT,
972                                    /* IncludeI */ true))
973       return false;
974 
975     MemoryLocation SrcLoc =
976         MemoryLocation(srcAlloca, LocationSize::precise(srcSize));
977     for (Instruction &I :
978          make_range(++C->getIterator(), C->getParent()->end())) {
979       // Lifetime of srcAlloca ends at lifetime.end.
980       if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
981         if (II->getIntrinsicID() == Intrinsic::lifetime_end &&
982             II->getArgOperand(1)->stripPointerCasts() == srcAlloca &&
983             cast<ConstantInt>(II->getArgOperand(0))->uge(srcSize))
984           break;
985       }
986 
987       // Lifetime of srcAlloca ends at return.
988       if (isa<ReturnInst>(&I))
989         break;
990 
991       // Ignore the direct read of src in the load.
992       if (&I == cpyLoad)
993         continue;
994 
995       // Check whether this instruction may mod/ref src through the captured
996       // pointer (we have already any direct mod/refs in the loop above).
997       // Also bail if we hit a terminator, as we don't want to scan into other
998       // blocks.
999       if (isModOrRefSet(AA->getModRefInfo(&I, SrcLoc)) || I.isTerminator())
1000         return false;
1001     }
1002   }
1003 
1004   // Since we're changing the parameter to the callsite, we need to make sure
1005   // that what would be the new parameter dominates the callsite.
1006   if (!DT->dominates(cpyDest, C)) {
1007     // Support moving a constant index GEP before the call.
1008     auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest);
1009     if (GEP && GEP->hasAllConstantIndices() &&
1010         DT->dominates(GEP->getPointerOperand(), C))
1011       GEP->moveBefore(C);
1012     else
1013       return false;
1014   }
1015 
1016   // In addition to knowing that the call does not access src in some
1017   // unexpected manner, for example via a global, which we deduce from
1018   // the use analysis, we also need to know that it does not sneakily
1019   // access dest.  We rely on AA to figure this out for us.
1020   ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
1021   // If necessary, perform additional analysis.
1022   if (isModOrRefSet(MR))
1023     MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT);
1024   if (isModOrRefSet(MR))
1025     return false;
1026 
1027   // We can't create address space casts here because we don't know if they're
1028   // safe for the target.
1029   if (cpySrc->getType()->getPointerAddressSpace() !=
1030       cpyDest->getType()->getPointerAddressSpace())
1031     return false;
1032   for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1033     if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
1034         cpySrc->getType()->getPointerAddressSpace() !=
1035             C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
1036       return false;
1037 
1038   // All the checks have passed, so do the transformation.
1039   bool changedArgument = false;
1040   for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1041     if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
1042       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
1043         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
1044                                       cpyDest->getName(), C);
1045       changedArgument = true;
1046       if (C->getArgOperand(ArgI)->getType() == Dest->getType())
1047         C->setArgOperand(ArgI, Dest);
1048       else
1049         C->setArgOperand(ArgI, CastInst::CreatePointerCast(
1050                                    Dest, C->getArgOperand(ArgI)->getType(),
1051                                    Dest->getName(), C));
1052     }
1053 
1054   if (!changedArgument)
1055     return false;
1056 
1057   // If the destination wasn't sufficiently aligned then increase its alignment.
1058   if (!isDestSufficientlyAligned) {
1059     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
1060     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
1061   }
1062 
1063   // Update AA metadata
1064   // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
1065   // handled here, but combineMetadata doesn't support them yet
1066   unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1067                          LLVMContext::MD_noalias,
1068                          LLVMContext::MD_invariant_group,
1069                          LLVMContext::MD_access_group};
1070   combineMetadata(C, cpyLoad, KnownIDs, true);
1071   if (cpyLoad != cpyStore)
1072     combineMetadata(C, cpyStore, KnownIDs, true);
1073 
1074   ++NumCallSlot;
1075   return true;
1076 }
1077 
1078 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
1079 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
1080 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1081                                                   MemCpyInst *MDep) {
1082   // We can only transforms memcpy's where the dest of one is the source of the
1083   // other.
1084   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
1085     return false;
1086 
1087   // If dep instruction is reading from our current input, then it is a noop
1088   // transfer and substituting the input won't change this instruction.  Just
1089   // ignore the input and let someone else zap MDep.  This handles cases like:
1090   //    memcpy(a <- a)
1091   //    memcpy(b <- a)
1092   if (M->getSource() == MDep->getSource())
1093     return false;
1094 
1095   // Second, the length of the memcpy's must be the same, or the preceding one
1096   // must be larger than the following one.
1097   if (MDep->getLength() != M->getLength()) {
1098     auto *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1099     auto *MLen = dyn_cast<ConstantInt>(M->getLength());
1100     if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1101       return false;
1102   }
1103 
1104   // Verify that the copied-from memory doesn't change in between the two
1105   // transfers.  For example, in:
1106   //    memcpy(a <- b)
1107   //    *b = 42;
1108   //    memcpy(c <- a)
1109   // It would be invalid to transform the second memcpy into memcpy(c <- b).
1110   //
1111   // TODO: If the code between M and MDep is transparent to the destination "c",
1112   // then we could still perform the xform by moving M up to the first memcpy.
1113   // TODO: It would be sufficient to check the MDep source up to the memcpy
1114   // size of M, rather than MDep.
1115   if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1116                      MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M)))
1117     return false;
1118 
1119   // If the dest of the second might alias the source of the first, then the
1120   // source and dest might overlap. In addition, if the source of the first
1121   // points to constant memory, they won't overlap by definition. Otherwise, we
1122   // still want to eliminate the intermediate value, but we have to generate a
1123   // memmove instead of memcpy.
1124   bool UseMemMove = false;
1125   if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(MDep))))
1126     UseMemMove = true;
1127 
1128   // If all checks passed, then we can transform M.
1129   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
1130                     << *MDep << '\n' << *M << '\n');
1131 
1132   // TODO: Is this worth it if we're creating a less aligned memcpy? For
1133   // example we could be moving from movaps -> movq on x86.
1134   IRBuilder<> Builder(M);
1135   Instruction *NewM;
1136   if (UseMemMove)
1137     NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
1138                                  MDep->getRawSource(), MDep->getSourceAlign(),
1139                                  M->getLength(), M->isVolatile());
1140   else if (isa<MemCpyInlineInst>(M)) {
1141     // llvm.memcpy may be promoted to llvm.memcpy.inline, but the converse is
1142     // never allowed since that would allow the latter to be lowered as a call
1143     // to an external function.
1144     NewM = Builder.CreateMemCpyInline(
1145         M->getRawDest(), M->getDestAlign(), MDep->getRawSource(),
1146         MDep->getSourceAlign(), M->getLength(), M->isVolatile());
1147   } else
1148     NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
1149                                 MDep->getRawSource(), MDep->getSourceAlign(),
1150                                 M->getLength(), M->isVolatile());
1151 
1152   assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)));
1153   auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1154   auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1155   MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1156 
1157   // Remove the instruction we're replacing.
1158   eraseInstruction(M);
1159   ++NumMemCpyInstr;
1160   return true;
1161 }
1162 
1163 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
1164 /// \p MemSet.  Try to simplify \p MemSet to only set the trailing bytes that
1165 /// weren't copied over by \p MemCpy.
1166 ///
1167 /// In other words, transform:
1168 /// \code
1169 ///   memset(dst, c, dst_size);
1170 ///   memcpy(dst, src, src_size);
1171 /// \endcode
1172 /// into:
1173 /// \code
1174 ///   memcpy(dst, src, src_size);
1175 ///   memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1176 /// \endcode
1177 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1178                                                   MemSetInst *MemSet) {
1179   // We can only transform memset/memcpy with the same destination.
1180   if (!AA->isMustAlias(MemSet->getDest(), MemCpy->getDest()))
1181     return false;
1182 
1183   // Check that src and dst of the memcpy aren't the same. While memcpy
1184   // operands cannot partially overlap, exact equality is allowed.
1185   if (isModSet(AA->getModRefInfo(MemCpy, MemoryLocation::getForSource(MemCpy))))
1186     return false;
1187 
1188   // We know that dst up to src_size is not written. We now need to make sure
1189   // that dst up to dst_size is not accessed. (If we did not move the memset,
1190   // checking for reads would be sufficient.)
1191   if (accessedBetween(*AA, MemoryLocation::getForDest(MemSet),
1192                       MSSA->getMemoryAccess(MemSet),
1193                       MSSA->getMemoryAccess(MemCpy)))
1194     return false;
1195 
1196   // Use the same i8* dest as the memcpy, killing the memset dest if different.
1197   Value *Dest = MemCpy->getRawDest();
1198   Value *DestSize = MemSet->getLength();
1199   Value *SrcSize = MemCpy->getLength();
1200 
1201   if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
1202     return false;
1203 
1204   // If the sizes are the same, simply drop the memset instead of generating
1205   // a replacement with zero size.
1206   if (DestSize == SrcSize) {
1207     eraseInstruction(MemSet);
1208     return true;
1209   }
1210 
1211   // By default, create an unaligned memset.
1212   unsigned Align = 1;
1213   // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1214   // of the sum.
1215   const unsigned DestAlign =
1216       std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1217   if (DestAlign > 1)
1218     if (auto *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1219       Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1220 
1221   IRBuilder<> Builder(MemCpy);
1222 
1223   // If the sizes have different types, zext the smaller one.
1224   if (DestSize->getType() != SrcSize->getType()) {
1225     if (DestSize->getType()->getIntegerBitWidth() >
1226         SrcSize->getType()->getIntegerBitWidth())
1227       SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1228     else
1229       DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1230   }
1231 
1232   Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1233   Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1234   Value *MemsetLen = Builder.CreateSelect(
1235       Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1236   unsigned DestAS = Dest->getType()->getPointerAddressSpace();
1237   Instruction *NewMemSet = Builder.CreateMemSet(
1238       Builder.CreateGEP(Builder.getInt8Ty(),
1239                         Builder.CreatePointerCast(Dest,
1240                                                   Builder.getInt8PtrTy(DestAS)),
1241                         SrcSize),
1242       MemSet->getOperand(1), MemsetLen, MaybeAlign(Align));
1243 
1244   assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&
1245          "MemCpy must be a MemoryDef");
1246   // The new memset is inserted after the memcpy, but it is known that its
1247   // defining access is the memset about to be removed which immediately
1248   // precedes the memcpy.
1249   auto *LastDef =
1250       cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1251   auto *NewAccess = MSSAU->createMemoryAccessBefore(
1252       NewMemSet, LastDef->getDefiningAccess(), LastDef);
1253   MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1254 
1255   eraseInstruction(MemSet);
1256   return true;
1257 }
1258 
1259 /// Determine whether the instruction has undefined content for the given Size,
1260 /// either because it was freshly alloca'd or started its lifetime.
1261 static bool hasUndefContents(MemorySSA *MSSA, AliasAnalysis *AA, Value *V,
1262                              MemoryDef *Def, Value *Size) {
1263   if (MSSA->isLiveOnEntryDef(Def))
1264     return isa<AllocaInst>(getUnderlyingObject(V));
1265 
1266   if (auto *II = dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
1267     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1268       auto *LTSize = cast<ConstantInt>(II->getArgOperand(0));
1269 
1270       if (auto *CSize = dyn_cast<ConstantInt>(Size)) {
1271         if (AA->isMustAlias(V, II->getArgOperand(1)) &&
1272             LTSize->getZExtValue() >= CSize->getZExtValue())
1273           return true;
1274       }
1275 
1276       // If the lifetime.start covers a whole alloca (as it almost always
1277       // does) and we're querying a pointer based on that alloca, then we know
1278       // the memory is definitely undef, regardless of how exactly we alias.
1279       // The size also doesn't matter, as an out-of-bounds access would be UB.
1280       if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(V))) {
1281         if (getUnderlyingObject(II->getArgOperand(1)) == Alloca) {
1282           const DataLayout &DL = Alloca->getModule()->getDataLayout();
1283           if (Optional<TypeSize> AllocaSize =
1284                   Alloca->getAllocationSizeInBits(DL))
1285             if (*AllocaSize == LTSize->getValue() * 8)
1286               return true;
1287         }
1288       }
1289     }
1290   }
1291 
1292   return false;
1293 }
1294 
1295 /// Transform memcpy to memset when its source was just memset.
1296 /// In other words, turn:
1297 /// \code
1298 ///   memset(dst1, c, dst1_size);
1299 ///   memcpy(dst2, dst1, dst2_size);
1300 /// \endcode
1301 /// into:
1302 /// \code
1303 ///   memset(dst1, c, dst1_size);
1304 ///   memset(dst2, c, dst2_size);
1305 /// \endcode
1306 /// When dst2_size <= dst1_size.
1307 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1308                                                MemSetInst *MemSet) {
1309   // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1310   // memcpying from the same address. Otherwise it is hard to reason about.
1311   if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1312     return false;
1313 
1314   Value *MemSetSize = MemSet->getLength();
1315   Value *CopySize = MemCpy->getLength();
1316 
1317   if (MemSetSize != CopySize) {
1318     // Make sure the memcpy doesn't read any more than what the memset wrote.
1319     // Don't worry about sizes larger than i64.
1320 
1321     // A known memset size is required.
1322     auto *CMemSetSize = dyn_cast<ConstantInt>(MemSetSize);
1323     if (!CMemSetSize)
1324       return false;
1325 
1326     // A known memcpy size is also required.
1327     auto  *CCopySize = dyn_cast<ConstantInt>(CopySize);
1328     if (!CCopySize)
1329       return false;
1330     if (CCopySize->getZExtValue() > CMemSetSize->getZExtValue()) {
1331       // If the memcpy is larger than the memset, but the memory was undef prior
1332       // to the memset, we can just ignore the tail. Technically we're only
1333       // interested in the bytes from MemSetSize..CopySize here, but as we can't
1334       // easily represent this location, we use the full 0..CopySize range.
1335       MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1336       bool CanReduceSize = false;
1337       MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet);
1338       MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1339           MemSetAccess->getDefiningAccess(), MemCpyLoc);
1340       if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1341         if (hasUndefContents(MSSA, AA, MemCpy->getSource(), MD, CopySize))
1342           CanReduceSize = true;
1343 
1344       if (!CanReduceSize)
1345         return false;
1346       CopySize = MemSetSize;
1347     }
1348   }
1349 
1350   IRBuilder<> Builder(MemCpy);
1351   Instruction *NewM =
1352       Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1353                            CopySize, MaybeAlign(MemCpy->getDestAlignment()));
1354   auto *LastDef =
1355       cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1356   auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1357   MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1358 
1359   return true;
1360 }
1361 
1362 /// Perform simplification of memcpy's.  If we have memcpy A
1363 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1364 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1365 /// circumstances). This allows later passes to remove the first memcpy
1366 /// altogether.
1367 bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1368   // We can only optimize non-volatile memcpy's.
1369   if (M->isVolatile()) return false;
1370 
1371   // If the source and destination of the memcpy are the same, then zap it.
1372   if (M->getSource() == M->getDest()) {
1373     ++BBI;
1374     eraseInstruction(M);
1375     return true;
1376   }
1377 
1378   // If copying from a constant, try to turn the memcpy into a memset.
1379   if (auto *GV = dyn_cast<GlobalVariable>(M->getSource()))
1380     if (GV->isConstant() && GV->hasDefinitiveInitializer())
1381       if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1382                                            M->getModule()->getDataLayout())) {
1383         IRBuilder<> Builder(M);
1384         Instruction *NewM =
1385             Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1386                                  MaybeAlign(M->getDestAlignment()), false);
1387         auto *LastDef =
1388             cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1389         auto *NewAccess =
1390             MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1391         MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1392 
1393         eraseInstruction(M);
1394         ++NumCpyToSet;
1395         return true;
1396       }
1397 
1398   MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
1399   MemoryAccess *AnyClobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1400   MemoryLocation DestLoc = MemoryLocation::getForDest(M);
1401   const MemoryAccess *DestClobber =
1402       MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc);
1403 
1404   // Try to turn a partially redundant memset + memcpy into
1405   // memcpy + smaller memset.  We don't need the memcpy size for this.
1406   // The memcpy most post-dom the memset, so limit this to the same basic
1407   // block. A non-local generalization is likely not worthwhile.
1408   if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
1409     if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
1410       if (DestClobber->getBlock() == M->getParent())
1411         if (processMemSetMemCpyDependence(M, MDep))
1412           return true;
1413 
1414   MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
1415       AnyClobber, MemoryLocation::getForSource(M));
1416 
1417   // There are four possible optimizations we can do for memcpy:
1418   //   a) memcpy-memcpy xform which exposes redundance for DSE.
1419   //   b) call-memcpy xform for return slot optimization.
1420   //   c) memcpy from freshly alloca'd space or space that has just started
1421   //      its lifetime copies undefined data, and we can therefore eliminate
1422   //      the memcpy in favor of the data that was already at the destination.
1423   //   d) memcpy from a just-memset'd source can be turned into memset.
1424   if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) {
1425     if (Instruction *MI = MD->getMemoryInst()) {
1426       if (auto *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
1427         if (auto *C = dyn_cast<CallInst>(MI)) {
1428           // The memcpy must post-dom the call. Limit to the same block for
1429           // now. Additionally, we need to ensure that there are no accesses
1430           // to dest between the call and the memcpy. Accesses to src will be
1431           // checked by performCallSlotOptzn().
1432           // TODO: Support non-local call-slot optimization?
1433           if (C->getParent() == M->getParent() &&
1434               !accessedBetween(*AA, DestLoc, MD, MA)) {
1435             // FIXME: Can we pass in either of dest/src alignment here instead
1436             // of conservatively taking the minimum?
1437             Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1438                                        M->getSourceAlign().valueOrOne());
1439             if (performCallSlotOptzn(
1440                     M, M, M->getDest(), M->getSource(),
1441                     TypeSize::getFixed(CopySize->getZExtValue()), Alignment,
1442                     C)) {
1443               LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"
1444                                 << "    call: " << *C << "\n"
1445                                 << "    memcpy: " << *M << "\n");
1446               eraseInstruction(M);
1447               ++NumMemCpyInstr;
1448               return true;
1449             }
1450           }
1451         }
1452       }
1453       if (auto *MDep = dyn_cast<MemCpyInst>(MI))
1454         return processMemCpyMemCpyDependence(M, MDep);
1455       if (auto *MDep = dyn_cast<MemSetInst>(MI)) {
1456         if (performMemCpyToMemSetOptzn(M, MDep)) {
1457           LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n");
1458           eraseInstruction(M);
1459           ++NumCpyToSet;
1460           return true;
1461         }
1462       }
1463     }
1464 
1465     if (hasUndefContents(MSSA, AA, M->getSource(), MD, M->getLength())) {
1466       LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n");
1467       eraseInstruction(M);
1468       ++NumMemCpyInstr;
1469       return true;
1470     }
1471   }
1472 
1473   return false;
1474 }
1475 
1476 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1477 /// not to alias.
1478 bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1479   // See if the source could be modified by this memmove potentially.
1480   if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(M))))
1481     return false;
1482 
1483   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1484                     << "\n");
1485 
1486   // If not, then we know we can transform this.
1487   Type *ArgTys[3] = { M->getRawDest()->getType(),
1488                       M->getRawSource()->getType(),
1489                       M->getLength()->getType() };
1490   M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1491                                                  Intrinsic::memcpy, ArgTys));
1492 
1493   // For MemorySSA nothing really changes (except that memcpy may imply stricter
1494   // aliasing guarantees).
1495 
1496   ++NumMoveToCpy;
1497   return true;
1498 }
1499 
1500 /// This is called on every byval argument in call sites.
1501 bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1502   const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
1503   // Find out what feeds this byval argument.
1504   Value *ByValArg = CB.getArgOperand(ArgNo);
1505   Type *ByValTy = CB.getParamByValType(ArgNo);
1506   TypeSize ByValSize = DL.getTypeAllocSize(ByValTy);
1507   MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize));
1508   MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
1509   if (!CallAccess)
1510     return false;
1511   MemCpyInst *MDep = nullptr;
1512   MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1513       CallAccess->getDefiningAccess(), Loc);
1514   if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1515     MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
1516 
1517   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
1518   // a memcpy, see if we can byval from the source of the memcpy instead of the
1519   // result.
1520   if (!MDep || MDep->isVolatile() ||
1521       ByValArg->stripPointerCasts() != MDep->getDest())
1522     return false;
1523 
1524   // The length of the memcpy must be larger or equal to the size of the byval.
1525   auto *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1526   if (!C1 || !TypeSize::isKnownGE(
1527                  TypeSize::getFixed(C1->getValue().getZExtValue()), ByValSize))
1528     return false;
1529 
1530   // Get the alignment of the byval.  If the call doesn't specify the alignment,
1531   // then it is some target specific value that we can't know.
1532   MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
1533   if (!ByValAlign) return false;
1534 
1535   // If it is greater than the memcpy, then we check to see if we can force the
1536   // source of the memcpy to the alignment we need.  If we fail, we bail out.
1537   MaybeAlign MemDepAlign = MDep->getSourceAlign();
1538   if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
1539       getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
1540                                  DT) < *ByValAlign)
1541     return false;
1542 
1543   // The address space of the memcpy source must match the byval argument
1544   if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1545       ByValArg->getType()->getPointerAddressSpace())
1546     return false;
1547 
1548   // Verify that the copied-from memory doesn't change in between the memcpy and
1549   // the byval call.
1550   //    memcpy(a <- b)
1551   //    *b = 42;
1552   //    foo(*a)
1553   // It would be invalid to transform the second memcpy into foo(*b).
1554   if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1555                      MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB)))
1556     return false;
1557 
1558   Value *TmpCast = MDep->getSource();
1559   if (MDep->getSource()->getType() != ByValArg->getType()) {
1560     BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1561                                               "tmpcast", &CB);
1562     // Set the tmpcast's DebugLoc to MDep's
1563     TmpBitCast->setDebugLoc(MDep->getDebugLoc());
1564     TmpCast = TmpBitCast;
1565   }
1566 
1567   LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1568                     << "  " << *MDep << "\n"
1569                     << "  " << CB << "\n");
1570 
1571   // Otherwise we're good!  Update the byval argument.
1572   CB.setArgOperand(ArgNo, TmpCast);
1573   ++NumMemCpyInstr;
1574   return true;
1575 }
1576 
1577 /// Executes one iteration of MemCpyOptPass.
1578 bool MemCpyOptPass::iterateOnFunction(Function &F) {
1579   bool MadeChange = false;
1580 
1581   // Walk all instruction in the function.
1582   for (BasicBlock &BB : F) {
1583     // Skip unreachable blocks. For example processStore assumes that an
1584     // instruction in a BB can't be dominated by a later instruction in the
1585     // same BB (which is a scenario that can happen for an unreachable BB that
1586     // has itself as a predecessor).
1587     if (!DT->isReachableFromEntry(&BB))
1588       continue;
1589 
1590     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
1591         // Avoid invalidating the iterator.
1592       Instruction *I = &*BI++;
1593 
1594       bool RepeatInstruction = false;
1595 
1596       if (auto *SI = dyn_cast<StoreInst>(I))
1597         MadeChange |= processStore(SI, BI);
1598       else if (auto *M = dyn_cast<MemSetInst>(I))
1599         RepeatInstruction = processMemSet(M, BI);
1600       else if (auto *M = dyn_cast<MemCpyInst>(I))
1601         RepeatInstruction = processMemCpy(M, BI);
1602       else if (auto *M = dyn_cast<MemMoveInst>(I))
1603         RepeatInstruction = processMemMove(M);
1604       else if (auto *CB = dyn_cast<CallBase>(I)) {
1605         for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
1606           if (CB->isByValArgument(i))
1607             MadeChange |= processByValArgument(*CB, i);
1608       }
1609 
1610       // Reprocess the instruction if desired.
1611       if (RepeatInstruction) {
1612         if (BI != BB.begin())
1613           --BI;
1614         MadeChange = true;
1615       }
1616     }
1617   }
1618 
1619   return MadeChange;
1620 }
1621 
1622 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1623   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1624   auto *AA = &AM.getResult<AAManager>(F);
1625   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
1626   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1627   auto *MSSA = &AM.getResult<MemorySSAAnalysis>(F);
1628 
1629   bool MadeChange = runImpl(F, &TLI, AA, AC, DT, &MSSA->getMSSA());
1630   if (!MadeChange)
1631     return PreservedAnalyses::all();
1632 
1633   PreservedAnalyses PA;
1634   PA.preserveSet<CFGAnalyses>();
1635   PA.preserve<MemorySSAAnalysis>();
1636   return PA;
1637 }
1638 
1639 bool MemCpyOptPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
1640                             AliasAnalysis *AA_, AssumptionCache *AC_,
1641                             DominatorTree *DT_, MemorySSA *MSSA_) {
1642   bool MadeChange = false;
1643   TLI = TLI_;
1644   AA = AA_;
1645   AC = AC_;
1646   DT = DT_;
1647   MSSA = MSSA_;
1648   MemorySSAUpdater MSSAU_(MSSA_);
1649   MSSAU = &MSSAU_;
1650 
1651   while (true) {
1652     if (!iterateOnFunction(F))
1653       break;
1654     MadeChange = true;
1655   }
1656 
1657   if (VerifyMemorySSA)
1658     MSSA_->verifyMemorySSA();
1659 
1660   return MadeChange;
1661 }
1662 
1663 /// This is the main transformation entry point for a function.
1664 bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1665   if (skipFunction(F))
1666     return false;
1667 
1668   auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1669   auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1670   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1671   auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1672   auto *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
1673 
1674   return Impl.runImpl(F, TLI, AA, AC, DT, MSSA);
1675 }
1676