MemCpyOptimizer.cpp revision 221345
1193323Sed//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This pass performs various transformations related to eliminating memcpy
11193323Sed// calls, or transforming sets of stores into memset's.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#define DEBUG_TYPE "memcpyopt"
16193323Sed#include "llvm/Transforms/Scalar.h"
17218893Sdim#include "llvm/GlobalVariable.h"
18193323Sed#include "llvm/IntrinsicInst.h"
19193323Sed#include "llvm/Instructions.h"
20193323Sed#include "llvm/ADT/SmallVector.h"
21193323Sed#include "llvm/ADT/Statistic.h"
22193323Sed#include "llvm/Analysis/Dominators.h"
23193323Sed#include "llvm/Analysis/AliasAnalysis.h"
24193323Sed#include "llvm/Analysis/MemoryDependenceAnalysis.h"
25218893Sdim#include "llvm/Analysis/ValueTracking.h"
26193323Sed#include "llvm/Support/Debug.h"
27193323Sed#include "llvm/Support/GetElementPtrTypeIterator.h"
28218893Sdim#include "llvm/Support/IRBuilder.h"
29198090Srdivacky#include "llvm/Support/raw_ostream.h"
30193323Sed#include "llvm/Target/TargetData.h"
31221345Sdim#include "llvm/Target/TargetLibraryInfo.h"
32193323Sed#include <list>
33193323Sedusing namespace llvm;
34193323Sed
35193323SedSTATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
36193323SedSTATISTIC(NumMemSetInfer, "Number of memsets inferred");
37198090SrdivackySTATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
38218893SdimSTATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
39193323Sed
40193323Sedstatic int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
41218893Sdim                                  bool &VariableIdxFound, const TargetData &TD){
42193323Sed  // Skip over the first indices.
43193323Sed  gep_type_iterator GTI = gep_type_begin(GEP);
44193323Sed  for (unsigned i = 1; i != Idx; ++i, ++GTI)
45193323Sed    /*skip along*/;
46193323Sed
47193323Sed  // Compute the offset implied by the rest of the indices.
48193323Sed  int64_t Offset = 0;
49193323Sed  for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
50193323Sed    ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
51193323Sed    if (OpC == 0)
52193323Sed      return VariableIdxFound = true;
53193323Sed    if (OpC->isZero()) continue;  // No offset.
54193323Sed
55193323Sed    // Handle struct indices, which add their field offset to the pointer.
56193323Sed    if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
57193323Sed      Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
58193323Sed      continue;
59193323Sed    }
60193323Sed
61193323Sed    // Otherwise, we have a sequential type like an array or vector.  Multiply
62193323Sed    // the index by the ElementSize.
63193323Sed    uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
64193323Sed    Offset += Size*OpC->getSExtValue();
65193323Sed  }
66193323Sed
67193323Sed  return Offset;
68193323Sed}
69193323Sed
70193323Sed/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
71193323Sed/// constant offset, and return that constant offset.  For example, Ptr1 might
72193323Sed/// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
73193323Sedstatic bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
74218893Sdim                            const TargetData &TD) {
75218893Sdim  Ptr1 = Ptr1->stripPointerCasts();
76218893Sdim  Ptr2 = Ptr2->stripPointerCasts();
77218893Sdim  GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
78218893Sdim  GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
79218893Sdim
80218893Sdim  bool VariableIdxFound = false;
81218893Sdim
82218893Sdim  // If one pointer is a GEP and the other isn't, then see if the GEP is a
83218893Sdim  // constant offset from the base, as in "P" and "gep P, 1".
84218893Sdim  if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
85218893Sdim    Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
86218893Sdim    return !VariableIdxFound;
87218893Sdim  }
88218893Sdim
89218893Sdim  if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
90218893Sdim    Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
91218893Sdim    return !VariableIdxFound;
92218893Sdim  }
93218893Sdim
94193323Sed  // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
95193323Sed  // base.  After that base, they may have some number of common (and
96193323Sed  // potentially variable) indices.  After that they handle some constant
97193323Sed  // offset, which determines their offset from each other.  At this point, we
98193323Sed  // handle no other case.
99193323Sed  if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
100193323Sed    return false;
101193323Sed
102193323Sed  // Skip any common indices and track the GEP types.
103193323Sed  unsigned Idx = 1;
104193323Sed  for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
105193323Sed    if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
106193323Sed      break;
107193323Sed
108193323Sed  int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
109193323Sed  int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
110193323Sed  if (VariableIdxFound) return false;
111193323Sed
112193323Sed  Offset = Offset2-Offset1;
113193323Sed  return true;
114193323Sed}
115193323Sed
116193323Sed
117193323Sed/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
118193323Sed/// This allows us to analyze stores like:
119193323Sed///   store 0 -> P+1
120193323Sed///   store 0 -> P+0
121193323Sed///   store 0 -> P+3
122193323Sed///   store 0 -> P+2
123193323Sed/// which sometimes happens with stores to arrays of structs etc.  When we see
124193323Sed/// the first store, we make a range [1, 2).  The second store extends the range
125193323Sed/// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
126193323Sed/// two ranges into [0, 3) which is memset'able.
127193323Sednamespace {
128193323Sedstruct MemsetRange {
129193323Sed  // Start/End - A semi range that describes the span that this range covers.
130193323Sed  // The range is closed at the start and open at the end: [Start, End).
131193323Sed  int64_t Start, End;
132193323Sed
133193323Sed  /// StartPtr - The getelementptr instruction that points to the start of the
134193323Sed  /// range.
135193323Sed  Value *StartPtr;
136193323Sed
137193323Sed  /// Alignment - The known alignment of the first store.
138193323Sed  unsigned Alignment;
139193323Sed
140193323Sed  /// TheStores - The actual stores that make up this range.
141218893Sdim  SmallVector<Instruction*, 16> TheStores;
142193323Sed
143193323Sed  bool isProfitableToUseMemset(const TargetData &TD) const;
144193323Sed
145193323Sed};
146193323Sed} // end anon namespace
147193323Sed
148193323Sedbool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
149193323Sed  // If we found more than 8 stores to merge or 64 bytes, use memset.
150193323Sed  if (TheStores.size() >= 8 || End-Start >= 64) return true;
151218893Sdim
152218893Sdim  // If there is nothing to merge, don't do anything.
153218893Sdim  if (TheStores.size() < 2) return false;
154193323Sed
155218893Sdim  // If any of the stores are a memset, then it is always good to extend the
156218893Sdim  // memset.
157218893Sdim  for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
158218893Sdim    if (!isa<StoreInst>(TheStores[i]))
159218893Sdim      return true;
160218893Sdim
161193323Sed  // Assume that the code generator is capable of merging pairs of stores
162193323Sed  // together if it wants to.
163218893Sdim  if (TheStores.size() == 2) return false;
164193323Sed
165193323Sed  // If we have fewer than 8 stores, it can still be worthwhile to do this.
166193323Sed  // For example, merging 4 i8 stores into an i32 store is useful almost always.
167193323Sed  // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
168193323Sed  // memset will be split into 2 32-bit stores anyway) and doing so can
169193323Sed  // pessimize the llvm optimizer.
170193323Sed  //
171193323Sed  // Since we don't have perfect knowledge here, make some assumptions: assume
172193323Sed  // the maximum GPR width is the same size as the pointer size and assume that
173193323Sed  // this width can be stored.  If so, check to see whether we will end up
174193323Sed  // actually reducing the number of stores used.
175193323Sed  unsigned Bytes = unsigned(End-Start);
176193323Sed  unsigned NumPointerStores = Bytes/TD.getPointerSize();
177193323Sed
178193323Sed  // Assume the remaining bytes if any are done a byte at a time.
179193323Sed  unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
180193323Sed
181193323Sed  // If we will reduce the # stores (according to this heuristic), do the
182193323Sed  // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
183193323Sed  // etc.
184193323Sed  return TheStores.size() > NumPointerStores+NumByteStores;
185193323Sed}
186193323Sed
187193323Sed
188193323Sednamespace {
189193323Sedclass MemsetRanges {
190193323Sed  /// Ranges - A sorted list of the memset ranges.  We use std::list here
191193323Sed  /// because each element is relatively large and expensive to copy.
192193323Sed  std::list<MemsetRange> Ranges;
193193323Sed  typedef std::list<MemsetRange>::iterator range_iterator;
194218893Sdim  const TargetData &TD;
195193323Sedpublic:
196218893Sdim  MemsetRanges(const TargetData &td) : TD(td) {}
197193323Sed
198193323Sed  typedef std::list<MemsetRange>::const_iterator const_iterator;
199193323Sed  const_iterator begin() const { return Ranges.begin(); }
200193323Sed  const_iterator end() const { return Ranges.end(); }
201193323Sed  bool empty() const { return Ranges.empty(); }
202193323Sed
203218893Sdim  void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
204218893Sdim    if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
205218893Sdim      addStore(OffsetFromFirst, SI);
206218893Sdim    else
207218893Sdim      addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
208218893Sdim  }
209218893Sdim
210218893Sdim  void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
211218893Sdim    int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
212218893Sdim
213218893Sdim    addRange(OffsetFromFirst, StoreSize,
214218893Sdim             SI->getPointerOperand(), SI->getAlignment(), SI);
215218893Sdim  }
216218893Sdim
217218893Sdim  void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
218218893Sdim    int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
219218893Sdim    addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
220218893Sdim  }
221218893Sdim
222218893Sdim  void addRange(int64_t Start, int64_t Size, Value *Ptr,
223218893Sdim                unsigned Alignment, Instruction *Inst);
224218893Sdim
225193323Sed};
226193323Sed
227193323Sed} // end anon namespace
228193323Sed
229193323Sed
230218893Sdim/// addRange - Add a new store to the MemsetRanges data structure.  This adds a
231193323Sed/// new range for the specified store at the specified offset, merging into
232193323Sed/// existing ranges as appropriate.
233218893Sdim///
234218893Sdim/// Do a linear search of the ranges to see if this can be joined and/or to
235218893Sdim/// find the insertion point in the list.  We keep the ranges sorted for
236218893Sdim/// simplicity here.  This is a linear search of a linked list, which is ugly,
237218893Sdim/// however the number of ranges is limited, so this won't get crazy slow.
238218893Sdimvoid MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
239218893Sdim                            unsigned Alignment, Instruction *Inst) {
240218893Sdim  int64_t End = Start+Size;
241193323Sed  range_iterator I = Ranges.begin(), E = Ranges.end();
242193323Sed
243193323Sed  while (I != E && Start > I->End)
244193323Sed    ++I;
245193323Sed
246193323Sed  // We now know that I == E, in which case we didn't find anything to merge
247193323Sed  // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
248193323Sed  // to insert a new range.  Handle this now.
249193323Sed  if (I == E || End < I->Start) {
250193323Sed    MemsetRange &R = *Ranges.insert(I, MemsetRange());
251193323Sed    R.Start        = Start;
252193323Sed    R.End          = End;
253218893Sdim    R.StartPtr     = Ptr;
254218893Sdim    R.Alignment    = Alignment;
255218893Sdim    R.TheStores.push_back(Inst);
256193323Sed    return;
257193323Sed  }
258218893Sdim
259193323Sed  // This store overlaps with I, add it.
260218893Sdim  I->TheStores.push_back(Inst);
261193323Sed
262193323Sed  // At this point, we may have an interval that completely contains our store.
263193323Sed  // If so, just add it to the interval and return.
264193323Sed  if (I->Start <= Start && I->End >= End)
265193323Sed    return;
266193323Sed
267193323Sed  // Now we know that Start <= I->End and End >= I->Start so the range overlaps
268193323Sed  // but is not entirely contained within the range.
269193323Sed
270193323Sed  // See if the range extends the start of the range.  In this case, it couldn't
271193323Sed  // possibly cause it to join the prior range, because otherwise we would have
272193323Sed  // stopped on *it*.
273193323Sed  if (Start < I->Start) {
274193323Sed    I->Start = Start;
275218893Sdim    I->StartPtr = Ptr;
276218893Sdim    I->Alignment = Alignment;
277193323Sed  }
278193323Sed
279193323Sed  // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
280193323Sed  // is in or right at the end of I), and that End >= I->Start.  Extend I out to
281193323Sed  // End.
282193323Sed  if (End > I->End) {
283193323Sed    I->End = End;
284193323Sed    range_iterator NextI = I;
285193323Sed    while (++NextI != E && End >= NextI->Start) {
286193323Sed      // Merge the range in.
287193323Sed      I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
288193323Sed      if (NextI->End > I->End)
289193323Sed        I->End = NextI->End;
290193323Sed      Ranges.erase(NextI);
291193323Sed      NextI = I;
292193323Sed    }
293193323Sed  }
294193323Sed}
295193323Sed
296193323Sed//===----------------------------------------------------------------------===//
297193323Sed//                         MemCpyOpt Pass
298193323Sed//===----------------------------------------------------------------------===//
299193323Sed
300193323Sednamespace {
301198090Srdivacky  class MemCpyOpt : public FunctionPass {
302218893Sdim    MemoryDependenceAnalysis *MD;
303221345Sdim    TargetLibraryInfo *TLI;
304218893Sdim    const TargetData *TD;
305193323Sed  public:
306193323Sed    static char ID; // Pass identification, replacement for typeid
307218893Sdim    MemCpyOpt() : FunctionPass(ID) {
308218893Sdim      initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
309218893Sdim      MD = 0;
310221345Sdim      TLI = 0;
311221345Sdim      TD = 0;
312218893Sdim    }
313193323Sed
314218893Sdim    bool runOnFunction(Function &F);
315218893Sdim
316193323Sed  private:
317193323Sed    // This transformation requires dominator postdominator info
318193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
319193323Sed      AU.setPreservesCFG();
320193323Sed      AU.addRequired<DominatorTree>();
321193323Sed      AU.addRequired<MemoryDependenceAnalysis>();
322193323Sed      AU.addRequired<AliasAnalysis>();
323221345Sdim      AU.addRequired<TargetLibraryInfo>();
324193323Sed      AU.addPreserved<AliasAnalysis>();
325193323Sed      AU.addPreserved<MemoryDependenceAnalysis>();
326193323Sed    }
327193323Sed
328193323Sed    // Helper fuctions
329198090Srdivacky    bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
330218893Sdim    bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
331198090Srdivacky    bool processMemCpy(MemCpyInst *M);
332198090Srdivacky    bool processMemMove(MemMoveInst *M);
333218893Sdim    bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
334218893Sdim                              uint64_t cpyLen, CallInst *C);
335218893Sdim    bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
336218893Sdim                                       uint64_t MSize);
337218893Sdim    bool processByValArgument(CallSite CS, unsigned ArgNo);
338218893Sdim    Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
339218893Sdim                                      Value *ByteVal);
340218893Sdim
341193323Sed    bool iterateOnFunction(Function &F);
342193323Sed  };
343193323Sed
344193323Sed  char MemCpyOpt::ID = 0;
345193323Sed}
346193323Sed
347193323Sed// createMemCpyOptPass - The public interface to this file...
348193323SedFunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
349193323Sed
350218893SdimINITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
351218893Sdim                      false, false)
352218893SdimINITIALIZE_PASS_DEPENDENCY(DominatorTree)
353218893SdimINITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
354221345SdimINITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
355218893SdimINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
356218893SdimINITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
357218893Sdim                    false, false)
358193323Sed
359218893Sdim/// tryMergingIntoMemset - When scanning forward over instructions, we look for
360193323Sed/// some other patterns to fold away.  In particular, this looks for stores to
361218893Sdim/// neighboring locations of memory.  If it sees enough consecutive ones, it
362218893Sdim/// attempts to merge them together into a memcpy/memset.
363218893SdimInstruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
364218893Sdim                                             Value *StartPtr, Value *ByteVal) {
365218893Sdim  if (TD == 0) return 0;
366193323Sed
367193323Sed  // Okay, so we now have a single store that can be splatable.  Scan to find
368193323Sed  // all subsequent stores of the same value to offset from the same pointer.
369193323Sed  // Join these together into ranges, so we can decide whether contiguous blocks
370193323Sed  // are stored.
371198090Srdivacky  MemsetRanges Ranges(*TD);
372193323Sed
373218893Sdim  BasicBlock::iterator BI = StartInst;
374193323Sed  for (++BI; !isa<TerminatorInst>(BI); ++BI) {
375218893Sdim    if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
376218893Sdim      // If the instruction is readnone, ignore it, otherwise bail out.  We
377218893Sdim      // don't even allow readonly here because we don't want something like:
378193323Sed      // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
379218893Sdim      if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
380218893Sdim        break;
381218893Sdim      continue;
382218893Sdim    }
383218893Sdim
384218893Sdim    if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
385218893Sdim      // If this is a store, see if we can merge it in.
386218893Sdim      if (NextStore->isVolatile()) break;
387218893Sdim
388218893Sdim      // Check to see if this stored value is of the same byte-splattable value.
389218893Sdim      if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
390218893Sdim        break;
391193323Sed
392218893Sdim      // Check to see if this store is to a constant offset from the start ptr.
393218893Sdim      int64_t Offset;
394218893Sdim      if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
395218893Sdim                           Offset, *TD))
396218893Sdim        break;
397193323Sed
398218893Sdim      Ranges.addStore(Offset, NextStore);
399218893Sdim    } else {
400218893Sdim      MemSetInst *MSI = cast<MemSetInst>(BI);
401218893Sdim
402218893Sdim      if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
403218893Sdim          !isa<ConstantInt>(MSI->getLength()))
404218893Sdim        break;
405218893Sdim
406218893Sdim      // Check to see if this store is to a constant offset from the start ptr.
407218893Sdim      int64_t Offset;
408218893Sdim      if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
409218893Sdim        break;
410218893Sdim
411218893Sdim      Ranges.addMemSet(Offset, MSI);
412218893Sdim    }
413193323Sed  }
414218893Sdim
415193323Sed  // If we have no ranges, then we just had a single store with nothing that
416193323Sed  // could be merged in.  This is a very common case of course.
417193323Sed  if (Ranges.empty())
418218893Sdim    return 0;
419193323Sed
420193323Sed  // If we had at least one store that could be merged in, add the starting
421193323Sed  // store as well.  We try to avoid this unless there is at least something
422193323Sed  // interesting as a small compile-time optimization.
423218893Sdim  Ranges.addInst(0, StartInst);
424218893Sdim
425218893Sdim  // If we create any memsets, we put it right before the first instruction that
426218893Sdim  // isn't part of the memset block.  This ensure that the memset is dominated
427218893Sdim  // by any addressing instruction needed by the start of the block.
428218893Sdim  IRBuilder<> Builder(BI);
429218893Sdim
430193323Sed  // Now that we have full information about ranges, loop over the ranges and
431193323Sed  // emit memset's for anything big enough to be worthwhile.
432218893Sdim  Instruction *AMemSet = 0;
433193323Sed  for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
434193323Sed       I != E; ++I) {
435193323Sed    const MemsetRange &Range = *I;
436218893Sdim
437193323Sed    if (Range.TheStores.size() == 1) continue;
438193323Sed
439193323Sed    // If it is profitable to lower this range to memset, do so now.
440198090Srdivacky    if (!Range.isProfitableToUseMemset(*TD))
441193323Sed      continue;
442193323Sed
443218893Sdim    // Otherwise, we do want to transform this!  Create a new memset.
444193323Sed    // Get the starting pointer of the block.
445193323Sed    StartPtr = Range.StartPtr;
446218893Sdim
447206274Srdivacky    // Determine alignment
448206274Srdivacky    unsigned Alignment = Range.Alignment;
449206274Srdivacky    if (Alignment == 0) {
450206274Srdivacky      const Type *EltType =
451218893Sdim        cast<PointerType>(StartPtr->getType())->getElementType();
452206274Srdivacky      Alignment = TD->getABITypeAlignment(EltType);
453206274Srdivacky    }
454218893Sdim
455218893Sdim    AMemSet =
456218893Sdim      Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
457218893Sdim
458202375Srdivacky    DEBUG(dbgs() << "Replace stores:\n";
459193323Sed          for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
460218893Sdim            dbgs() << *Range.TheStores[i] << '\n';
461218893Sdim          dbgs() << "With: " << *AMemSet << '\n');
462218893Sdim
463193323Sed    // Zap all the stores.
464218893Sdim    for (SmallVector<Instruction*, 16>::const_iterator
465198090Srdivacky         SI = Range.TheStores.begin(),
466218893Sdim         SE = Range.TheStores.end(); SI != SE; ++SI) {
467218893Sdim      MD->removeInstruction(*SI);
468193323Sed      (*SI)->eraseFromParent();
469218893Sdim    }
470193323Sed    ++NumMemSetInfer;
471193323Sed  }
472193323Sed
473218893Sdim  return AMemSet;
474193323Sed}
475193323Sed
476193323Sed
477218893Sdimbool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
478218893Sdim  if (SI->isVolatile()) return false;
479218893Sdim
480218893Sdim  if (TD == 0) return false;
481218893Sdim
482218893Sdim  // Detect cases where we're performing call slot forwarding, but
483218893Sdim  // happen to be using a load-store pair to implement it, rather than
484218893Sdim  // a memcpy.
485218893Sdim  if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
486218893Sdim    if (!LI->isVolatile() && LI->hasOneUse()) {
487218893Sdim      MemDepResult dep = MD->getDependency(LI);
488218893Sdim      CallInst *C = 0;
489218893Sdim      if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
490218893Sdim        C = dyn_cast<CallInst>(dep.getInst());
491218893Sdim
492218893Sdim      if (C) {
493218893Sdim        bool changed = performCallSlotOptzn(LI,
494218893Sdim                        SI->getPointerOperand()->stripPointerCasts(),
495218893Sdim                        LI->getPointerOperand()->stripPointerCasts(),
496218893Sdim                        TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
497218893Sdim        if (changed) {
498218893Sdim          MD->removeInstruction(SI);
499218893Sdim          SI->eraseFromParent();
500218893Sdim          MD->removeInstruction(LI);
501218893Sdim          LI->eraseFromParent();
502218893Sdim          ++NumMemCpyInstr;
503218893Sdim          return true;
504218893Sdim        }
505218893Sdim      }
506218893Sdim    }
507218893Sdim  }
508218893Sdim
509218893Sdim  // There are two cases that are interesting for this code to handle: memcpy
510218893Sdim  // and memset.  Right now we only handle memset.
511218893Sdim
512218893Sdim  // Ensure that the value being stored is something that can be memset'able a
513218893Sdim  // byte at a time like "0" or "-1" or any width, as well as things like
514218893Sdim  // 0xA0A0A0A0 and 0.0.
515218893Sdim  if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
516218893Sdim    if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
517218893Sdim                                              ByteVal)) {
518218893Sdim      BBI = I;  // Don't invalidate iterator.
519218893Sdim      return true;
520218893Sdim    }
521218893Sdim
522218893Sdim  return false;
523218893Sdim}
524218893Sdim
525218893Sdimbool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
526218893Sdim  // See if there is another memset or store neighboring this memset which
527218893Sdim  // allows us to widen out the memset to do a single larger store.
528218893Sdim  if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
529218893Sdim    if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
530218893Sdim                                              MSI->getValue())) {
531218893Sdim      BBI = I;  // Don't invalidate iterator.
532218893Sdim      return true;
533218893Sdim    }
534218893Sdim  return false;
535218893Sdim}
536218893Sdim
537218893Sdim
538193323Sed/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
539193323Sed/// and checks for the possibility of a call slot optimization by having
540193323Sed/// the call write its result directly into the destination of the memcpy.
541218893Sdimbool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
542218893Sdim                                     Value *cpyDest, Value *cpySrc,
543218893Sdim                                     uint64_t cpyLen, CallInst *C) {
544193323Sed  // The general transformation to keep in mind is
545193323Sed  //
546193323Sed  //   call @func(..., src, ...)
547193323Sed  //   memcpy(dest, src, ...)
548193323Sed  //
549193323Sed  // ->
550193323Sed  //
551193323Sed  //   memcpy(dest, src, ...)
552193323Sed  //   call @func(..., dest, ...)
553193323Sed  //
554193323Sed  // Since moving the memcpy is technically awkward, we additionally check that
555193323Sed  // src only holds uninitialized values at the moment of the call, meaning that
556193323Sed  // the memcpy can be discarded rather than moved.
557193323Sed
558193323Sed  // Deliberately get the source and destination with bitcasts stripped away,
559193323Sed  // because we'll need to do type comparisons based on the underlying type.
560212904Sdim  CallSite CS(C);
561193323Sed
562193323Sed  // Require that src be an alloca.  This simplifies the reasoning considerably.
563198090Srdivacky  AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
564193323Sed  if (!srcAlloca)
565193323Sed    return false;
566193323Sed
567193323Sed  // Check that all of src is copied to dest.
568218893Sdim  if (TD == 0) return false;
569193323Sed
570198090Srdivacky  ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
571193323Sed  if (!srcArraySize)
572193323Sed    return false;
573193323Sed
574198090Srdivacky  uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
575193323Sed    srcArraySize->getZExtValue();
576193323Sed
577218893Sdim  if (cpyLen < srcSize)
578193323Sed    return false;
579193323Sed
580193323Sed  // Check that accessing the first srcSize bytes of dest will not cause a
581193323Sed  // trap.  Otherwise the transform is invalid since it might cause a trap
582193323Sed  // to occur earlier than it otherwise would.
583198090Srdivacky  if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
584193323Sed    // The destination is an alloca.  Check it is larger than srcSize.
585198090Srdivacky    ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
586193323Sed    if (!destArraySize)
587193323Sed      return false;
588193323Sed
589198090Srdivacky    uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
590193323Sed      destArraySize->getZExtValue();
591193323Sed
592193323Sed    if (destSize < srcSize)
593193323Sed      return false;
594198090Srdivacky  } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
595193323Sed    // If the destination is an sret parameter then only accesses that are
596193323Sed    // outside of the returned struct type can trap.
597193323Sed    if (!A->hasStructRetAttr())
598193323Sed      return false;
599193323Sed
600198090Srdivacky    const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
601198090Srdivacky    uint64_t destSize = TD->getTypeAllocSize(StructTy);
602193323Sed
603193323Sed    if (destSize < srcSize)
604193323Sed      return false;
605193323Sed  } else {
606193323Sed    return false;
607193323Sed  }
608193323Sed
609193323Sed  // Check that src is not accessed except via the call and the memcpy.  This
610193323Sed  // guarantees that it holds only undefined values when passed in (so the final
611193323Sed  // memcpy can be dropped), that it is not read or written between the call and
612193323Sed  // the memcpy, and that writing beyond the end of it is undefined.
613193323Sed  SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
614193323Sed                                   srcAlloca->use_end());
615193323Sed  while (!srcUseList.empty()) {
616202375Srdivacky    User *UI = srcUseList.pop_back_val();
617193323Sed
618193323Sed    if (isa<BitCastInst>(UI)) {
619193323Sed      for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
620193323Sed           I != E; ++I)
621193323Sed        srcUseList.push_back(*I);
622198090Srdivacky    } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
623193323Sed      if (G->hasAllZeroIndices())
624193323Sed        for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
625193323Sed             I != E; ++I)
626193323Sed          srcUseList.push_back(*I);
627193323Sed      else
628193323Sed        return false;
629193323Sed    } else if (UI != C && UI != cpy) {
630193323Sed      return false;
631193323Sed    }
632193323Sed  }
633193323Sed
634193323Sed  // Since we're changing the parameter to the callsite, we need to make sure
635193323Sed  // that what would be the new parameter dominates the callsite.
636198090Srdivacky  DominatorTree &DT = getAnalysis<DominatorTree>();
637198090Srdivacky  if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
638193323Sed    if (!DT.dominates(cpyDestInst, C))
639193323Sed      return false;
640193323Sed
641193323Sed  // In addition to knowing that the call does not access src in some
642193323Sed  // unexpected manner, for example via a global, which we deduce from
643193323Sed  // the use analysis, we also need to know that it does not sneakily
644193323Sed  // access dest.  We rely on AA to figure this out for us.
645198090Srdivacky  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
646218893Sdim  if (AA.getModRefInfo(C, cpyDest, srcSize) != AliasAnalysis::NoModRef)
647193323Sed    return false;
648193323Sed
649193323Sed  // All the checks have passed, so do the transformation.
650193323Sed  bool changedArgument = false;
651193323Sed  for (unsigned i = 0; i < CS.arg_size(); ++i)
652193323Sed    if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
653193323Sed      if (cpySrc->getType() != cpyDest->getType())
654193323Sed        cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
655193323Sed                                              cpyDest->getName(), C);
656193323Sed      changedArgument = true;
657198090Srdivacky      if (CS.getArgument(i)->getType() == cpyDest->getType())
658198090Srdivacky        CS.setArgument(i, cpyDest);
659198090Srdivacky      else
660193323Sed        CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
661198090Srdivacky                          CS.getArgument(i)->getType(), cpyDest->getName(), C));
662193323Sed    }
663193323Sed
664193323Sed  if (!changedArgument)
665193323Sed    return false;
666193323Sed
667193323Sed  // Drop any cached information about the call, because we may have changed
668193323Sed  // its dependence information by changing its parameter.
669218893Sdim  MD->removeInstruction(C);
670193323Sed
671218893Sdim  // Remove the memcpy.
672218893Sdim  MD->removeInstruction(cpy);
673210299Sed  ++NumMemCpyInstr;
674193323Sed
675193323Sed  return true;
676193323Sed}
677193323Sed
678218893Sdim/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
679218893Sdim/// memory dependence of memcpy 'M' is the memcpy 'MDep'.  Try to simplify M to
680218893Sdim/// copy from MDep's input if we can.  MSize is the size of M's copy.
681218893Sdim///
682218893Sdimbool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
683218893Sdim                                              uint64_t MSize) {
684218893Sdim  // We can only transforms memcpy's where the dest of one is the source of the
685218893Sdim  // other.
686218893Sdim  if (M->getSource() != MDep->getDest() || MDep->isVolatile())
687193323Sed    return false;
688193323Sed
689218893Sdim  // If dep instruction is reading from our current input, then it is a noop
690218893Sdim  // transfer and substituting the input won't change this instruction.  Just
691218893Sdim  // ignore the input and let someone else zap MDep.  This handles cases like:
692218893Sdim  //    memcpy(a <- a)
693218893Sdim  //    memcpy(b <- a)
694218893Sdim  if (M->getSource() == MDep->getSource())
695193323Sed    return false;
696193323Sed
697221345Sdim  // Second, the length of the memcpy's must be the same, or the preceding one
698193323Sed  // must be larger than the following one.
699218893Sdim  ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
700218893Sdim  ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
701218893Sdim  if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
702193323Sed    return false;
703193323Sed
704198090Srdivacky  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
705218893Sdim
706218893Sdim  // Verify that the copied-from memory doesn't change in between the two
707218893Sdim  // transfers.  For example, in:
708218893Sdim  //    memcpy(a <- b)
709218893Sdim  //    *b = 42;
710218893Sdim  //    memcpy(c <- a)
711218893Sdim  // It would be invalid to transform the second memcpy into memcpy(c <- b).
712218893Sdim  //
713218893Sdim  // TODO: If the code between M and MDep is transparent to the destination "c",
714218893Sdim  // then we could still perform the xform by moving M up to the first memcpy.
715218893Sdim  //
716218893Sdim  // NOTE: This is conservative, it will stop on any read from the source loc,
717218893Sdim  // not just the defining memcpy.
718218893Sdim  MemDepResult SourceDep =
719218893Sdim    MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
720218893Sdim                                 false, M, M->getParent());
721218893Sdim  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
722193323Sed    return false;
723193323Sed
724218893Sdim  // If the dest of the second might alias the source of the first, then the
725218893Sdim  // source and dest might overlap.  We still want to eliminate the intermediate
726218893Sdim  // value, but we have to generate a memmove instead of memcpy.
727218893Sdim  bool UseMemMove = false;
728218893Sdim  if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
729218893Sdim    UseMemMove = true;
730193323Sed
731218893Sdim  // If all checks passed, then we can transform M.
732193323Sed
733218893Sdim  // Make sure to use the lesser of the alignment of the source and the dest
734218893Sdim  // since we're changing where we're reading from, but don't want to increase
735218893Sdim  // the alignment past what can be read from or written to.
736218893Sdim  // TODO: Is this worth it if we're creating a less aligned memcpy? For
737218893Sdim  // example we could be moving from movaps -> movq on x86.
738218893Sdim  unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
739193323Sed
740218893Sdim  IRBuilder<> Builder(M);
741218893Sdim  if (UseMemMove)
742218893Sdim    Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
743218893Sdim                          Align, M->isVolatile());
744218893Sdim  else
745218893Sdim    Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
746218893Sdim                         Align, M->isVolatile());
747218893Sdim
748218893Sdim  // Remove the instruction we're replacing.
749218893Sdim  MD->removeInstruction(M);
750218893Sdim  M->eraseFromParent();
751218893Sdim  ++NumMemCpyInstr;
752218893Sdim  return true;
753218893Sdim}
754218893Sdim
755218893Sdim
756218893Sdim/// processMemCpy - perform simplification of memcpy's.  If we have memcpy A
757218893Sdim/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
758218893Sdim/// B to be a memcpy from X to Z (or potentially a memmove, depending on
759218893Sdim/// circumstances). This allows later passes to remove the first memcpy
760218893Sdim/// altogether.
761218893Sdimbool MemCpyOpt::processMemCpy(MemCpyInst *M) {
762218893Sdim  // We can only optimize statically-sized memcpy's that are non-volatile.
763218893Sdim  ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
764218893Sdim  if (CopySize == 0 || M->isVolatile()) return false;
765218893Sdim
766218893Sdim  // If the source and destination of the memcpy are the same, then zap it.
767218893Sdim  if (M->getSource() == M->getDest()) {
768218893Sdim    MD->removeInstruction(M);
769193323Sed    M->eraseFromParent();
770218893Sdim    return false;
771193323Sed  }
772218893Sdim
773218893Sdim  // If copying from a constant, try to turn the memcpy into a memset.
774218893Sdim  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
775218893Sdim    if (GV->isConstant() && GV->hasDefinitiveInitializer())
776218893Sdim      if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
777218893Sdim        IRBuilder<> Builder(M);
778218893Sdim        Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
779218893Sdim                             M->getAlignment(), false);
780218893Sdim        MD->removeInstruction(M);
781218893Sdim        M->eraseFromParent();
782218893Sdim        ++NumCpyToSet;
783218893Sdim        return true;
784218893Sdim      }
785218893Sdim
786218893Sdim  // The are two possible optimizations we can do for memcpy:
787218893Sdim  //   a) memcpy-memcpy xform which exposes redundance for DSE.
788218893Sdim  //   b) call-memcpy xform for return slot optimization.
789218893Sdim  MemDepResult DepInfo = MD->getDependency(M);
790218893Sdim  if (!DepInfo.isClobber())
791218893Sdim    return false;
792193323Sed
793218893Sdim  if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
794218893Sdim    return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
795218893Sdim
796218893Sdim  if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
797218893Sdim    if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
798218893Sdim                             CopySize->getZExtValue(), C)) {
799218893Sdim      MD->removeInstruction(M);
800218893Sdim      M->eraseFromParent();
801218893Sdim      return true;
802218893Sdim    }
803218893Sdim  }
804218893Sdim
805193323Sed  return false;
806193323Sed}
807193323Sed
808198090Srdivacky/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
809198090Srdivacky/// are guaranteed not to alias.
810198090Srdivackybool MemCpyOpt::processMemMove(MemMoveInst *M) {
811198090Srdivacky  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
812198090Srdivacky
813221345Sdim  if (!TLI->has(LibFunc::memmove))
814221345Sdim    return false;
815221345Sdim
816198090Srdivacky  // See if the pointers alias.
817218893Sdim  if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
818198090Srdivacky    return false;
819193323Sed
820202375Srdivacky  DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
821193323Sed
822198090Srdivacky  // If not, then we know we can transform this.
823198090Srdivacky  Module *Mod = M->getParent()->getParent()->getParent();
824206274Srdivacky  const Type *ArgTys[3] = { M->getRawDest()->getType(),
825206274Srdivacky                            M->getRawSource()->getType(),
826206274Srdivacky                            M->getLength()->getType() };
827212904Sdim  M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
828212904Sdim                                                 ArgTys, 3));
829198090Srdivacky
830198090Srdivacky  // MemDep may have over conservative information about this instruction, just
831198090Srdivacky  // conservatively flush it from the cache.
832218893Sdim  MD->removeInstruction(M);
833198090Srdivacky
834198090Srdivacky  ++NumMoveToCpy;
835198090Srdivacky  return true;
836193323Sed}
837198090Srdivacky
838218893Sdim/// processByValArgument - This is called on every byval argument in call sites.
839218893Sdimbool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
840218893Sdim  if (TD == 0) return false;
841193323Sed
842218893Sdim  // Find out what feeds this byval argument.
843218893Sdim  Value *ByValArg = CS.getArgument(ArgNo);
844218893Sdim  const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
845218893Sdim  uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
846218893Sdim  MemDepResult DepInfo =
847218893Sdim    MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
848218893Sdim                                 true, CS.getInstruction(),
849218893Sdim                                 CS.getInstruction()->getParent());
850218893Sdim  if (!DepInfo.isClobber())
851218893Sdim    return false;
852218893Sdim
853218893Sdim  // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
854218893Sdim  // a memcpy, see if we can byval from the source of the memcpy instead of the
855218893Sdim  // result.
856218893Sdim  MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
857218893Sdim  if (MDep == 0 || MDep->isVolatile() ||
858218893Sdim      ByValArg->stripPointerCasts() != MDep->getDest())
859218893Sdim    return false;
860218893Sdim
861218893Sdim  // The length of the memcpy must be larger or equal to the size of the byval.
862218893Sdim  ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
863218893Sdim  if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
864218893Sdim    return false;
865218893Sdim
866218893Sdim  // Get the alignment of the byval.  If it is greater than the memcpy, then we
867218893Sdim  // can't do the substitution.  If the call doesn't specify the alignment, then
868218893Sdim  // it is some target specific value that we can't know.
869218893Sdim  unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
870218893Sdim  if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
871218893Sdim    return false;
872218893Sdim
873218893Sdim  // Verify that the copied-from memory doesn't change in between the memcpy and
874218893Sdim  // the byval call.
875218893Sdim  //    memcpy(a <- b)
876218893Sdim  //    *b = 42;
877218893Sdim  //    foo(*a)
878218893Sdim  // It would be invalid to transform the second memcpy into foo(*b).
879218893Sdim  //
880218893Sdim  // NOTE: This is conservative, it will stop on any read from the source loc,
881218893Sdim  // not just the defining memcpy.
882218893Sdim  MemDepResult SourceDep =
883218893Sdim    MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
884218893Sdim                                 false, CS.getInstruction(), MDep->getParent());
885218893Sdim  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
886218893Sdim    return false;
887218893Sdim
888218893Sdim  Value *TmpCast = MDep->getSource();
889218893Sdim  if (MDep->getSource()->getType() != ByValArg->getType())
890218893Sdim    TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
891218893Sdim                              "tmpcast", CS.getInstruction());
892218893Sdim
893218893Sdim  DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
894218893Sdim               << "  " << *MDep << "\n"
895218893Sdim               << "  " << *CS.getInstruction() << "\n");
896218893Sdim
897218893Sdim  // Otherwise we're good!  Update the byval argument.
898218893Sdim  CS.setArgument(ArgNo, TmpCast);
899218893Sdim  ++NumMemCpyInstr;
900218893Sdim  return true;
901218893Sdim}
902218893Sdim
903218893Sdim/// iterateOnFunction - Executes one iteration of MemCpyOpt.
904193323Sedbool MemCpyOpt::iterateOnFunction(Function &F) {
905198090Srdivacky  bool MadeChange = false;
906193323Sed
907198090Srdivacky  // Walk all instruction in the function.
908193323Sed  for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
909218893Sdim    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
910198090Srdivacky      // Avoid invalidating the iterator.
911198090Srdivacky      Instruction *I = BI++;
912193323Sed
913218893Sdim      bool RepeatInstruction = false;
914218893Sdim
915193323Sed      if (StoreInst *SI = dyn_cast<StoreInst>(I))
916198090Srdivacky        MadeChange |= processStore(SI, BI);
917218893Sdim      else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
918218893Sdim        RepeatInstruction = processMemSet(M, BI);
919198090Srdivacky      else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
920218893Sdim        RepeatInstruction = processMemCpy(M);
921218893Sdim      else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
922218893Sdim        RepeatInstruction = processMemMove(M);
923218893Sdim      else if (CallSite CS = (Value*)I) {
924218893Sdim        for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
925218893Sdim          if (CS.paramHasAttr(i+1, Attribute::ByVal))
926218893Sdim            MadeChange |= processByValArgument(CS, i);
927193323Sed      }
928218893Sdim
929218893Sdim      // Reprocess the instruction if desired.
930218893Sdim      if (RepeatInstruction) {
931218893Sdim        if (BI != BB->begin()) --BI;
932218893Sdim        MadeChange = true;
933218893Sdim      }
934193323Sed    }
935193323Sed  }
936193323Sed
937198090Srdivacky  return MadeChange;
938193323Sed}
939198090Srdivacky
940198090Srdivacky// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
941198090Srdivacky// function.
942198090Srdivacky//
943198090Srdivackybool MemCpyOpt::runOnFunction(Function &F) {
944198090Srdivacky  bool MadeChange = false;
945218893Sdim  MD = &getAnalysis<MemoryDependenceAnalysis>();
946218893Sdim  TD = getAnalysisIfAvailable<TargetData>();
947221345Sdim  TLI = &getAnalysis<TargetLibraryInfo>();
948221345Sdim
949221345Sdim  // If we don't have at least memset and memcpy, there is little point of doing
950221345Sdim  // anything here.  These are required by a freestanding implementation, so if
951221345Sdim  // even they are disabled, there is no point in trying hard.
952221345Sdim  if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
953221345Sdim    return false;
954221345Sdim
955198090Srdivacky  while (1) {
956198090Srdivacky    if (!iterateOnFunction(F))
957198090Srdivacky      break;
958198090Srdivacky    MadeChange = true;
959198090Srdivacky  }
960198090Srdivacky
961218893Sdim  MD = 0;
962198090Srdivacky  return MadeChange;
963198090Srdivacky}
964