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