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