MemCpyOpt: When merging memsets also merge the trivial case of two memsets with the...
[oota-llvm.git] / lib / Transforms / Scalar / MemCpyOptimizer.cpp
1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs various transformations related to eliminating memcpy
11 // calls, or transforming sets of stores into memset's.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "memcpyopt"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include <list>
34 using namespace llvm;
35
36 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
37 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
38 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
39 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
40
41 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
42                                   bool &VariableIdxFound, const DataLayout &TD){
43   // Skip over the first indices.
44   gep_type_iterator GTI = gep_type_begin(GEP);
45   for (unsigned i = 1; i != Idx; ++i, ++GTI)
46     /*skip along*/;
47
48   // Compute the offset implied by the rest of the indices.
49   int64_t Offset = 0;
50   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
51     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
52     if (OpC == 0)
53       return VariableIdxFound = true;
54     if (OpC->isZero()) continue;  // No offset.
55
56     // Handle struct indices, which add their field offset to the pointer.
57     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
58       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
59       continue;
60     }
61
62     // Otherwise, we have a sequential type like an array or vector.  Multiply
63     // the index by the ElementSize.
64     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
65     Offset += Size*OpC->getSExtValue();
66   }
67
68   return Offset;
69 }
70
71 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
72 /// constant offset, and return that constant offset.  For example, Ptr1 might
73 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
74 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
75                             const DataLayout &TD) {
76   Ptr1 = Ptr1->stripPointerCasts();
77   Ptr2 = Ptr2->stripPointerCasts();
78
79   // Handle the trivial case first.
80   if (Ptr1 == Ptr2) {
81     Offset = 0;
82     return true;
83   }
84
85   GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
86   GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
87
88   bool VariableIdxFound = false;
89
90   // If one pointer is a GEP and the other isn't, then see if the GEP is a
91   // constant offset from the base, as in "P" and "gep P, 1".
92   if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
93     Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
94     return !VariableIdxFound;
95   }
96
97   if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
98     Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
99     return !VariableIdxFound;
100   }
101
102   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
103   // base.  After that base, they may have some number of common (and
104   // potentially variable) indices.  After that they handle some constant
105   // offset, which determines their offset from each other.  At this point, we
106   // handle no other case.
107   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
108     return false;
109
110   // Skip any common indices and track the GEP types.
111   unsigned Idx = 1;
112   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
113     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
114       break;
115
116   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
117   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
118   if (VariableIdxFound) return false;
119
120   Offset = Offset2-Offset1;
121   return true;
122 }
123
124
125 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
126 /// This allows us to analyze stores like:
127 ///   store 0 -> P+1
128 ///   store 0 -> P+0
129 ///   store 0 -> P+3
130 ///   store 0 -> P+2
131 /// which sometimes happens with stores to arrays of structs etc.  When we see
132 /// the first store, we make a range [1, 2).  The second store extends the range
133 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
134 /// two ranges into [0, 3) which is memset'able.
135 namespace {
136 struct MemsetRange {
137   // Start/End - A semi range that describes the span that this range covers.
138   // The range is closed at the start and open at the end: [Start, End).
139   int64_t Start, End;
140
141   /// StartPtr - The getelementptr instruction that points to the start of the
142   /// range.
143   Value *StartPtr;
144
145   /// Alignment - The known alignment of the first store.
146   unsigned Alignment;
147
148   /// TheStores - The actual stores that make up this range.
149   SmallVector<Instruction*, 16> TheStores;
150
151   bool isProfitableToUseMemset(const DataLayout &TD) const;
152
153 };
154 } // end anon namespace
155
156 bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
157   // If we found more than 4 stores to merge or 16 bytes, use memset.
158   if (TheStores.size() >= 4 || End-Start >= 16) return true;
159
160   // If there is nothing to merge, don't do anything.
161   if (TheStores.size() < 2) return false;
162
163   // If any of the stores are a memset, then it is always good to extend the
164   // memset.
165   for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
166     if (!isa<StoreInst>(TheStores[i]))
167       return true;
168
169   // Assume that the code generator is capable of merging pairs of stores
170   // together if it wants to.
171   if (TheStores.size() == 2) return false;
172
173   // If we have fewer than 8 stores, it can still be worthwhile to do this.
174   // For example, merging 4 i8 stores into an i32 store is useful almost always.
175   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
176   // memset will be split into 2 32-bit stores anyway) and doing so can
177   // pessimize the llvm optimizer.
178   //
179   // Since we don't have perfect knowledge here, make some assumptions: assume
180   // the maximum GPR width is the same size as the largest legal integer
181   // size. If so, check to see whether we will end up actually reducing the
182   // number of stores used.
183   unsigned Bytes = unsigned(End-Start);
184   unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
185   if (MaxIntSize == 0)
186     MaxIntSize = 1;
187   unsigned NumPointerStores = Bytes / MaxIntSize;
188
189   // Assume the remaining bytes if any are done a byte at a time.
190   unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
191
192   // If we will reduce the # stores (according to this heuristic), do the
193   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
194   // etc.
195   return TheStores.size() > NumPointerStores+NumByteStores;
196 }
197
198
199 namespace {
200 class MemsetRanges {
201   /// Ranges - A sorted list of the memset ranges.  We use std::list here
202   /// because each element is relatively large and expensive to copy.
203   std::list<MemsetRange> Ranges;
204   typedef std::list<MemsetRange>::iterator range_iterator;
205   const DataLayout &DL;
206 public:
207   MemsetRanges(const DataLayout &DL) : DL(DL) {}
208
209   typedef std::list<MemsetRange>::const_iterator const_iterator;
210   const_iterator begin() const { return Ranges.begin(); }
211   const_iterator end() const { return Ranges.end(); }
212   bool empty() const { return Ranges.empty(); }
213
214   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
215     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
216       addStore(OffsetFromFirst, SI);
217     else
218       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
219   }
220
221   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
222     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
223
224     addRange(OffsetFromFirst, StoreSize,
225              SI->getPointerOperand(), SI->getAlignment(), SI);
226   }
227
228   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
229     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
230     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
231   }
232
233   void addRange(int64_t Start, int64_t Size, Value *Ptr,
234                 unsigned Alignment, Instruction *Inst);
235
236 };
237
238 } // end anon namespace
239
240
241 /// addRange - Add a new store to the MemsetRanges data structure.  This adds a
242 /// new range for the specified store at the specified offset, merging into
243 /// existing ranges as appropriate.
244 ///
245 /// Do a linear search of the ranges to see if this can be joined and/or to
246 /// find the insertion point in the list.  We keep the ranges sorted for
247 /// simplicity here.  This is a linear search of a linked list, which is ugly,
248 /// however the number of ranges is limited, so this won't get crazy slow.
249 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
250                             unsigned Alignment, Instruction *Inst) {
251   int64_t End = Start+Size;
252   range_iterator I = Ranges.begin(), E = Ranges.end();
253
254   while (I != E && Start > I->End)
255     ++I;
256
257   // We now know that I == E, in which case we didn't find anything to merge
258   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
259   // to insert a new range.  Handle this now.
260   if (I == E || End < I->Start) {
261     MemsetRange &R = *Ranges.insert(I, MemsetRange());
262     R.Start        = Start;
263     R.End          = End;
264     R.StartPtr     = Ptr;
265     R.Alignment    = Alignment;
266     R.TheStores.push_back(Inst);
267     return;
268   }
269
270   // This store overlaps with I, add it.
271   I->TheStores.push_back(Inst);
272
273   // At this point, we may have an interval that completely contains our store.
274   // If so, just add it to the interval and return.
275   if (I->Start <= Start && I->End >= End)
276     return;
277
278   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
279   // but is not entirely contained within the range.
280
281   // See if the range extends the start of the range.  In this case, it couldn't
282   // possibly cause it to join the prior range, because otherwise we would have
283   // stopped on *it*.
284   if (Start < I->Start) {
285     I->Start = Start;
286     I->StartPtr = Ptr;
287     I->Alignment = Alignment;
288   }
289
290   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
291   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
292   // End.
293   if (End > I->End) {
294     I->End = End;
295     range_iterator NextI = I;
296     while (++NextI != E && End >= NextI->Start) {
297       // Merge the range in.
298       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
299       if (NextI->End > I->End)
300         I->End = NextI->End;
301       Ranges.erase(NextI);
302       NextI = I;
303     }
304   }
305 }
306
307 //===----------------------------------------------------------------------===//
308 //                         MemCpyOpt Pass
309 //===----------------------------------------------------------------------===//
310
311 namespace {
312   class MemCpyOpt : public FunctionPass {
313     MemoryDependenceAnalysis *MD;
314     TargetLibraryInfo *TLI;
315     const DataLayout *DL;
316   public:
317     static char ID; // Pass identification, replacement for typeid
318     MemCpyOpt() : FunctionPass(ID) {
319       initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
320       MD = 0;
321       TLI = 0;
322       DL = 0;
323     }
324
325     bool runOnFunction(Function &F) override;
326
327   private:
328     // This transformation requires dominator postdominator info
329     void getAnalysisUsage(AnalysisUsage &AU) const override {
330       AU.setPreservesCFG();
331       AU.addRequired<DominatorTreeWrapperPass>();
332       AU.addRequired<MemoryDependenceAnalysis>();
333       AU.addRequired<AliasAnalysis>();
334       AU.addRequired<TargetLibraryInfo>();
335       AU.addPreserved<AliasAnalysis>();
336       AU.addPreserved<MemoryDependenceAnalysis>();
337     }
338
339     // Helper fuctions
340     bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
341     bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
342     bool processMemCpy(MemCpyInst *M);
343     bool processMemMove(MemMoveInst *M);
344     bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
345                               uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
346     bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
347                                        uint64_t MSize);
348     bool processByValArgument(CallSite CS, unsigned ArgNo);
349     Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
350                                       Value *ByteVal);
351
352     bool iterateOnFunction(Function &F);
353   };
354
355   char MemCpyOpt::ID = 0;
356 }
357
358 // createMemCpyOptPass - The public interface to this file...
359 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
360
361 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
362                       false, false)
363 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
364 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
365 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
366 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
367 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
368                     false, false)
369
370 /// tryMergingIntoMemset - When scanning forward over instructions, we look for
371 /// some other patterns to fold away.  In particular, this looks for stores to
372 /// neighboring locations of memory.  If it sees enough consecutive ones, it
373 /// attempts to merge them together into a memcpy/memset.
374 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
375                                              Value *StartPtr, Value *ByteVal) {
376   if (DL == 0) return 0;
377
378   // Okay, so we now have a single store that can be splatable.  Scan to find
379   // all subsequent stores of the same value to offset from the same pointer.
380   // Join these together into ranges, so we can decide whether contiguous blocks
381   // are stored.
382   MemsetRanges Ranges(*DL);
383
384   BasicBlock::iterator BI = StartInst;
385   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
386     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
387       // If the instruction is readnone, ignore it, otherwise bail out.  We
388       // don't even allow readonly here because we don't want something like:
389       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
390       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
391         break;
392       continue;
393     }
394
395     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
396       // If this is a store, see if we can merge it in.
397       if (!NextStore->isSimple()) break;
398
399       // Check to see if this stored value is of the same byte-splattable value.
400       if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
401         break;
402
403       // Check to see if this store is to a constant offset from the start ptr.
404       int64_t Offset;
405       if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
406                            Offset, *DL))
407         break;
408
409       Ranges.addStore(Offset, NextStore);
410     } else {
411       MemSetInst *MSI = cast<MemSetInst>(BI);
412
413       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
414           !isa<ConstantInt>(MSI->getLength()))
415         break;
416
417       // Check to see if this store is to a constant offset from the start ptr.
418       int64_t Offset;
419       if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
420         break;
421
422       Ranges.addMemSet(Offset, MSI);
423     }
424   }
425
426   // If we have no ranges, then we just had a single store with nothing that
427   // could be merged in.  This is a very common case of course.
428   if (Ranges.empty())
429     return 0;
430
431   // If we had at least one store that could be merged in, add the starting
432   // store as well.  We try to avoid this unless there is at least something
433   // interesting as a small compile-time optimization.
434   Ranges.addInst(0, StartInst);
435
436   // If we create any memsets, we put it right before the first instruction that
437   // isn't part of the memset block.  This ensure that the memset is dominated
438   // by any addressing instruction needed by the start of the block.
439   IRBuilder<> Builder(BI);
440
441   // Now that we have full information about ranges, loop over the ranges and
442   // emit memset's for anything big enough to be worthwhile.
443   Instruction *AMemSet = 0;
444   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
445        I != E; ++I) {
446     const MemsetRange &Range = *I;
447
448     if (Range.TheStores.size() == 1) continue;
449
450     // If it is profitable to lower this range to memset, do so now.
451     if (!Range.isProfitableToUseMemset(*DL))
452       continue;
453
454     // Otherwise, we do want to transform this!  Create a new memset.
455     // Get the starting pointer of the block.
456     StartPtr = Range.StartPtr;
457
458     // Determine alignment
459     unsigned Alignment = Range.Alignment;
460     if (Alignment == 0) {
461       Type *EltType =
462         cast<PointerType>(StartPtr->getType())->getElementType();
463       Alignment = DL->getABITypeAlignment(EltType);
464     }
465
466     AMemSet =
467       Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
468
469     DEBUG(dbgs() << "Replace stores:\n";
470           for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
471             dbgs() << *Range.TheStores[i] << '\n';
472           dbgs() << "With: " << *AMemSet << '\n');
473
474     if (!Range.TheStores.empty())
475       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
476
477     // Zap all the stores.
478     for (SmallVectorImpl<Instruction *>::const_iterator
479          SI = Range.TheStores.begin(),
480          SE = Range.TheStores.end(); SI != SE; ++SI) {
481       MD->removeInstruction(*SI);
482       (*SI)->eraseFromParent();
483     }
484     ++NumMemSetInfer;
485   }
486
487   return AMemSet;
488 }
489
490
491 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
492   if (!SI->isSimple()) return false;
493
494   if (DL == 0) return false;
495
496   // Detect cases where we're performing call slot forwarding, but
497   // happen to be using a load-store pair to implement it, rather than
498   // a memcpy.
499   if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
500     if (LI->isSimple() && LI->hasOneUse() &&
501         LI->getParent() == SI->getParent()) {
502       MemDepResult ldep = MD->getDependency(LI);
503       CallInst *C = 0;
504       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
505         C = dyn_cast<CallInst>(ldep.getInst());
506
507       if (C) {
508         // Check that nothing touches the dest of the "copy" between
509         // the call and the store.
510         AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
511         AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
512         for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
513                                   E = C; I != E; --I) {
514           if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
515             C = 0;
516             break;
517           }
518         }
519       }
520
521       if (C) {
522         unsigned storeAlign = SI->getAlignment();
523         if (!storeAlign)
524           storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
525         unsigned loadAlign = LI->getAlignment();
526         if (!loadAlign)
527           loadAlign = DL->getABITypeAlignment(LI->getType());
528
529         bool changed = performCallSlotOptzn(LI,
530                         SI->getPointerOperand()->stripPointerCasts(),
531                         LI->getPointerOperand()->stripPointerCasts(),
532                         DL->getTypeStoreSize(SI->getOperand(0)->getType()),
533                         std::min(storeAlign, loadAlign), C);
534         if (changed) {
535           MD->removeInstruction(SI);
536           SI->eraseFromParent();
537           MD->removeInstruction(LI);
538           LI->eraseFromParent();
539           ++NumMemCpyInstr;
540           return true;
541         }
542       }
543     }
544   }
545
546   // There are two cases that are interesting for this code to handle: memcpy
547   // and memset.  Right now we only handle memset.
548
549   // Ensure that the value being stored is something that can be memset'able a
550   // byte at a time like "0" or "-1" or any width, as well as things like
551   // 0xA0A0A0A0 and 0.0.
552   if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
553     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
554                                               ByteVal)) {
555       BBI = I;  // Don't invalidate iterator.
556       return true;
557     }
558
559   return false;
560 }
561
562 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
563   // See if there is another memset or store neighboring this memset which
564   // allows us to widen out the memset to do a single larger store.
565   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
566     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
567                                               MSI->getValue())) {
568       BBI = I;  // Don't invalidate iterator.
569       return true;
570     }
571   return false;
572 }
573
574
575 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
576 /// and checks for the possibility of a call slot optimization by having
577 /// the call write its result directly into the destination of the memcpy.
578 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
579                                      Value *cpyDest, Value *cpySrc,
580                                      uint64_t cpyLen, unsigned cpyAlign,
581                                      CallInst *C) {
582   // The general transformation to keep in mind is
583   //
584   //   call @func(..., src, ...)
585   //   memcpy(dest, src, ...)
586   //
587   // ->
588   //
589   //   memcpy(dest, src, ...)
590   //   call @func(..., dest, ...)
591   //
592   // Since moving the memcpy is technically awkward, we additionally check that
593   // src only holds uninitialized values at the moment of the call, meaning that
594   // the memcpy can be discarded rather than moved.
595
596   // Deliberately get the source and destination with bitcasts stripped away,
597   // because we'll need to do type comparisons based on the underlying type.
598   CallSite CS(C);
599
600   // Require that src be an alloca.  This simplifies the reasoning considerably.
601   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
602   if (!srcAlloca)
603     return false;
604
605   // Check that all of src is copied to dest.
606   if (DL == 0) return false;
607
608   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
609   if (!srcArraySize)
610     return false;
611
612   uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
613     srcArraySize->getZExtValue();
614
615   if (cpyLen < srcSize)
616     return false;
617
618   // Check that accessing the first srcSize bytes of dest will not cause a
619   // trap.  Otherwise the transform is invalid since it might cause a trap
620   // to occur earlier than it otherwise would.
621   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
622     // The destination is an alloca.  Check it is larger than srcSize.
623     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
624     if (!destArraySize)
625       return false;
626
627     uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
628       destArraySize->getZExtValue();
629
630     if (destSize < srcSize)
631       return false;
632   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
633     // If the destination is an sret parameter then only accesses that are
634     // outside of the returned struct type can trap.
635     if (!A->hasStructRetAttr())
636       return false;
637
638     Type *StructTy = cast<PointerType>(A->getType())->getElementType();
639     if (!StructTy->isSized()) {
640       // The call may never return and hence the copy-instruction may never
641       // be executed, and therefore it's not safe to say "the destination
642       // has at least <cpyLen> bytes, as implied by the copy-instruction",
643       return false;
644     }
645
646     uint64_t destSize = DL->getTypeAllocSize(StructTy);
647     if (destSize < srcSize)
648       return false;
649   } else {
650     return false;
651   }
652
653   // Check that dest points to memory that is at least as aligned as src.
654   unsigned srcAlign = srcAlloca->getAlignment();
655   if (!srcAlign)
656     srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
657   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
658   // If dest is not aligned enough and we can't increase its alignment then
659   // bail out.
660   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
661     return false;
662
663   // Check that src is not accessed except via the call and the memcpy.  This
664   // guarantees that it holds only undefined values when passed in (so the final
665   // memcpy can be dropped), that it is not read or written between the call and
666   // the memcpy, and that writing beyond the end of it is undefined.
667   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
668                                    srcAlloca->user_end());
669   while (!srcUseList.empty()) {
670     User *U = srcUseList.pop_back_val();
671
672     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
673       for (User *UU : U->users())
674         srcUseList.push_back(UU);
675     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
676       if (G->hasAllZeroIndices())
677         for (User *UU : U->users())
678           srcUseList.push_back(UU);
679       else
680         return false;
681     } else if (U != C && U != cpy) {
682       return false;
683     }
684   }
685
686   // Since we're changing the parameter to the callsite, we need to make sure
687   // that what would be the new parameter dominates the callsite.
688   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
689   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
690     if (!DT.dominates(cpyDestInst, C))
691       return false;
692
693   // In addition to knowing that the call does not access src in some
694   // unexpected manner, for example via a global, which we deduce from
695   // the use analysis, we also need to know that it does not sneakily
696   // access dest.  We rely on AA to figure this out for us.
697   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
698   AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
699   // If necessary, perform additional analysis.
700   if (MR != AliasAnalysis::NoModRef)
701     MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
702   if (MR != AliasAnalysis::NoModRef)
703     return false;
704
705   // All the checks have passed, so do the transformation.
706   bool changedArgument = false;
707   for (unsigned i = 0; i < CS.arg_size(); ++i)
708     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
709       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
710         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
711                                       cpyDest->getName(), C);
712       changedArgument = true;
713       if (CS.getArgument(i)->getType() == Dest->getType())
714         CS.setArgument(i, Dest);
715       else
716         CS.setArgument(i, CastInst::CreatePointerCast(Dest,
717                           CS.getArgument(i)->getType(), Dest->getName(), C));
718     }
719
720   if (!changedArgument)
721     return false;
722
723   // If the destination wasn't sufficiently aligned then increase its alignment.
724   if (!isDestSufficientlyAligned) {
725     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
726     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
727   }
728
729   // Drop any cached information about the call, because we may have changed
730   // its dependence information by changing its parameter.
731   MD->removeInstruction(C);
732
733   // Remove the memcpy.
734   MD->removeInstruction(cpy);
735   ++NumMemCpyInstr;
736
737   return true;
738 }
739
740 /// processMemCpyMemCpyDependence - We've found that the (upward scanning)
741 /// memory dependence of memcpy 'M' is the memcpy 'MDep'.  Try to simplify M to
742 /// copy from MDep's input if we can.  MSize is the size of M's copy.
743 ///
744 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
745                                               uint64_t MSize) {
746   // We can only transforms memcpy's where the dest of one is the source of the
747   // other.
748   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
749     return false;
750
751   // If dep instruction is reading from our current input, then it is a noop
752   // transfer and substituting the input won't change this instruction.  Just
753   // ignore the input and let someone else zap MDep.  This handles cases like:
754   //    memcpy(a <- a)
755   //    memcpy(b <- a)
756   if (M->getSource() == MDep->getSource())
757     return false;
758
759   // Second, the length of the memcpy's must be the same, or the preceding one
760   // must be larger than the following one.
761   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
762   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
763   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
764     return false;
765
766   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
767
768   // Verify that the copied-from memory doesn't change in between the two
769   // transfers.  For example, in:
770   //    memcpy(a <- b)
771   //    *b = 42;
772   //    memcpy(c <- a)
773   // It would be invalid to transform the second memcpy into memcpy(c <- b).
774   //
775   // TODO: If the code between M and MDep is transparent to the destination "c",
776   // then we could still perform the xform by moving M up to the first memcpy.
777   //
778   // NOTE: This is conservative, it will stop on any read from the source loc,
779   // not just the defining memcpy.
780   MemDepResult SourceDep =
781     MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
782                                  false, M, M->getParent());
783   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
784     return false;
785
786   // If the dest of the second might alias the source of the first, then the
787   // source and dest might overlap.  We still want to eliminate the intermediate
788   // value, but we have to generate a memmove instead of memcpy.
789   bool UseMemMove = false;
790   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
791     UseMemMove = true;
792
793   // If all checks passed, then we can transform M.
794
795   // Make sure to use the lesser of the alignment of the source and the dest
796   // since we're changing where we're reading from, but don't want to increase
797   // the alignment past what can be read from or written to.
798   // TODO: Is this worth it if we're creating a less aligned memcpy? For
799   // example we could be moving from movaps -> movq on x86.
800   unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
801
802   IRBuilder<> Builder(M);
803   if (UseMemMove)
804     Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
805                           Align, M->isVolatile());
806   else
807     Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
808                          Align, M->isVolatile());
809
810   // Remove the instruction we're replacing.
811   MD->removeInstruction(M);
812   M->eraseFromParent();
813   ++NumMemCpyInstr;
814   return true;
815 }
816
817
818 /// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
819 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
820 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
821 /// circumstances). This allows later passes to remove the first memcpy
822 /// altogether.
823 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
824   // We can only optimize non-volatile memcpy's.
825   if (M->isVolatile()) return false;
826
827   // If the source and destination of the memcpy are the same, then zap it.
828   if (M->getSource() == M->getDest()) {
829     MD->removeInstruction(M);
830     M->eraseFromParent();
831     return false;
832   }
833
834   // If copying from a constant, try to turn the memcpy into a memset.
835   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
836     if (GV->isConstant() && GV->hasDefinitiveInitializer())
837       if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
838         IRBuilder<> Builder(M);
839         Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
840                              M->getAlignment(), false);
841         MD->removeInstruction(M);
842         M->eraseFromParent();
843         ++NumCpyToSet;
844         return true;
845       }
846
847   // The optimizations after this point require the memcpy size.
848   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
849   if (CopySize == 0) return false;
850
851   // The are three possible optimizations we can do for memcpy:
852   //   a) memcpy-memcpy xform which exposes redundance for DSE.
853   //   b) call-memcpy xform for return slot optimization.
854   //   c) memcpy from freshly alloca'd space copies undefined data, and we can
855   //      therefore eliminate the memcpy in favor of the data that was already
856   //      at the destination.
857   MemDepResult DepInfo = MD->getDependency(M);
858   if (DepInfo.isClobber()) {
859     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
860       if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
861                                CopySize->getZExtValue(), M->getAlignment(),
862                                C)) {
863         MD->removeInstruction(M);
864         M->eraseFromParent();
865         return true;
866       }
867     }
868   }
869
870   AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
871   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
872                                                          M, M->getParent());
873   if (SrcDepInfo.isClobber()) {
874     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
875       return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
876   } else if (SrcDepInfo.isDef()) {
877     if (isa<AllocaInst>(SrcDepInfo.getInst())) {
878       MD->removeInstruction(M);
879       M->eraseFromParent();
880       ++NumMemCpyInstr;
881       return true;
882     }
883   }
884
885   return false;
886 }
887
888 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
889 /// are guaranteed not to alias.
890 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
891   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
892
893   if (!TLI->has(LibFunc::memmove))
894     return false;
895
896   // See if the pointers alias.
897   if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
898     return false;
899
900   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
901
902   // If not, then we know we can transform this.
903   Module *Mod = M->getParent()->getParent()->getParent();
904   Type *ArgTys[3] = { M->getRawDest()->getType(),
905                       M->getRawSource()->getType(),
906                       M->getLength()->getType() };
907   M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
908                                                  ArgTys));
909
910   // MemDep may have over conservative information about this instruction, just
911   // conservatively flush it from the cache.
912   MD->removeInstruction(M);
913
914   ++NumMoveToCpy;
915   return true;
916 }
917
918 /// processByValArgument - This is called on every byval argument in call sites.
919 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
920   if (DL == 0) return false;
921
922   // Find out what feeds this byval argument.
923   Value *ByValArg = CS.getArgument(ArgNo);
924   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
925   uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
926   MemDepResult DepInfo =
927     MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
928                                  true, CS.getInstruction(),
929                                  CS.getInstruction()->getParent());
930   if (!DepInfo.isClobber())
931     return false;
932
933   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
934   // a memcpy, see if we can byval from the source of the memcpy instead of the
935   // result.
936   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
937   if (MDep == 0 || MDep->isVolatile() ||
938       ByValArg->stripPointerCasts() != MDep->getDest())
939     return false;
940
941   // The length of the memcpy must be larger or equal to the size of the byval.
942   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
943   if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
944     return false;
945
946   // Get the alignment of the byval.  If the call doesn't specify the alignment,
947   // then it is some target specific value that we can't know.
948   unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
949   if (ByValAlign == 0) return false;
950
951   // If it is greater than the memcpy, then we check to see if we can force the
952   // source of the memcpy to the alignment we need.  If we fail, we bail out.
953   if (MDep->getAlignment() < ByValAlign &&
954       getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
955     return false;
956
957   // Verify that the copied-from memory doesn't change in between the memcpy and
958   // the byval call.
959   //    memcpy(a <- b)
960   //    *b = 42;
961   //    foo(*a)
962   // It would be invalid to transform the second memcpy into foo(*b).
963   //
964   // NOTE: This is conservative, it will stop on any read from the source loc,
965   // not just the defining memcpy.
966   MemDepResult SourceDep =
967     MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
968                                  false, CS.getInstruction(), MDep->getParent());
969   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
970     return false;
971
972   Value *TmpCast = MDep->getSource();
973   if (MDep->getSource()->getType() != ByValArg->getType())
974     TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
975                               "tmpcast", CS.getInstruction());
976
977   DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
978                << "  " << *MDep << "\n"
979                << "  " << *CS.getInstruction() << "\n");
980
981   // Otherwise we're good!  Update the byval argument.
982   CS.setArgument(ArgNo, TmpCast);
983   ++NumMemCpyInstr;
984   return true;
985 }
986
987 /// iterateOnFunction - Executes one iteration of MemCpyOpt.
988 bool MemCpyOpt::iterateOnFunction(Function &F) {
989   bool MadeChange = false;
990
991   // Walk all instruction in the function.
992   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
993     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
994       // Avoid invalidating the iterator.
995       Instruction *I = BI++;
996
997       bool RepeatInstruction = false;
998
999       if (StoreInst *SI = dyn_cast<StoreInst>(I))
1000         MadeChange |= processStore(SI, BI);
1001       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1002         RepeatInstruction = processMemSet(M, BI);
1003       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1004         RepeatInstruction = processMemCpy(M);
1005       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1006         RepeatInstruction = processMemMove(M);
1007       else if (CallSite CS = (Value*)I) {
1008         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
1009           if (CS.isByValArgument(i))
1010             MadeChange |= processByValArgument(CS, i);
1011       }
1012
1013       // Reprocess the instruction if desired.
1014       if (RepeatInstruction) {
1015         if (BI != BB->begin()) --BI;
1016         MadeChange = true;
1017       }
1018     }
1019   }
1020
1021   return MadeChange;
1022 }
1023
1024 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1025 // function.
1026 //
1027 bool MemCpyOpt::runOnFunction(Function &F) {
1028   if (skipOptnoneFunction(F))
1029     return false;
1030
1031   bool MadeChange = false;
1032   MD = &getAnalysis<MemoryDependenceAnalysis>();
1033   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1034   DL = DLP ? &DLP->getDataLayout() : 0;
1035   TLI = &getAnalysis<TargetLibraryInfo>();
1036
1037   // If we don't have at least memset and memcpy, there is little point of doing
1038   // anything here.  These are required by a freestanding implementation, so if
1039   // even they are disabled, there is no point in trying hard.
1040   if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1041     return false;
1042
1043   while (1) {
1044     if (!iterateOnFunction(F))
1045       break;
1046     MadeChange = true;
1047   }
1048
1049   MD = 0;
1050   return MadeChange;
1051 }