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