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