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