blob: 6de5ef1d770a1ef79911d3ae5758f3f855f53e3a [file] [log] [blame]
Owen Andersona723d1e2008-04-09 08:23:16 +00001//===- 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"
Benjamin Kramera1120872010-12-24 21:17:12 +000017#include "llvm/GlobalVariable.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000018#include "llvm/IntrinsicInst.h"
19#include "llvm/Instructions.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000020#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattnerbb897102010-12-26 20:15:01 +000025#include "llvm/Analysis/ValueTracking.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner61db1f52010-12-26 22:57:41 +000028#include "llvm/Support/IRBuilder.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000029#include "llvm/Support/raw_ostream.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000030#include "llvm/Target/TargetData.h"
31#include <list>
32using namespace llvm;
33
34STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
35STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000036STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000037STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000038
Owen Andersona723d1e2008-04-09 08:23:16 +000039static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
Chris Lattner67a716a2011-01-08 20:24:01 +000040 bool &VariableIdxFound, const TargetData &TD){
Owen Andersona723d1e2008-04-09 08:23:16 +000041 // Skip over the first indices.
42 gep_type_iterator GTI = gep_type_begin(GEP);
43 for (unsigned i = 1; i != Idx; ++i, ++GTI)
44 /*skip along*/;
45
46 // Compute the offset implied by the rest of the indices.
47 int64_t Offset = 0;
48 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
49 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
50 if (OpC == 0)
51 return VariableIdxFound = true;
52 if (OpC->isZero()) continue; // No offset.
53
54 // Handle struct indices, which add their field offset to the pointer.
55 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
56 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
57 continue;
58 }
59
60 // Otherwise, we have a sequential type like an array or vector. Multiply
61 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000062 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000063 Offset += Size*OpC->getSExtValue();
64 }
65
66 return Offset;
67}
68
69/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
70/// constant offset, and return that constant offset. For example, Ptr1 might
71/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
72static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Chris Lattner67a716a2011-01-08 20:24:01 +000073 const TargetData &TD) {
Chris Lattnerf4afaa82011-01-10 02:34:11 +000074 //Ptr1 = Ptr1->stripPointerCasts();
75 //Ptr2 = Ptr2->stripPointerCasts();
Chris Lattner9fa11e92011-01-08 21:07:56 +000076 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
77 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
78
79 bool VariableIdxFound = false;
80
Chris Lattnerf4afaa82011-01-10 02:34:11 +000081#if 0
Chris Lattner9fa11e92011-01-08 21:07:56 +000082 // If one pointer is a GEP and the other isn't, then see if the GEP is a
83 // constant offset from the base, as in "P" and "gep P, 1".
84 if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
85 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
86 return !VariableIdxFound;
87 }
88
89 if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
90 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
91 return !VariableIdxFound;
92 }
Chris Lattnerf4afaa82011-01-10 02:34:11 +000093#endif
Chris Lattner9fa11e92011-01-08 21:07:56 +000094
Owen Andersona723d1e2008-04-09 08:23:16 +000095 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
96 // base. After that base, they may have some number of common (and
97 // potentially variable) indices. After that they handle some constant
98 // offset, which determines their offset from each other. At this point, we
99 // handle no other case.
Owen Andersona723d1e2008-04-09 08:23:16 +0000100 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
101 return false;
102
103 // Skip any common indices and track the GEP types.
104 unsigned Idx = 1;
105 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
106 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
107 break;
108
Owen Andersona723d1e2008-04-09 08:23:16 +0000109 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
110 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
111 if (VariableIdxFound) return false;
112
113 Offset = Offset2-Offset1;
114 return true;
115}
116
117
118/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
119/// This allows us to analyze stores like:
120/// store 0 -> P+1
121/// store 0 -> P+0
122/// store 0 -> P+3
123/// store 0 -> P+2
124/// which sometimes happens with stores to arrays of structs etc. When we see
125/// the first store, we make a range [1, 2). The second store extends the range
126/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
127/// two ranges into [0, 3) which is memset'able.
128namespace {
129struct MemsetRange {
130 // Start/End - A semi range that describes the span that this range covers.
131 // The range is closed at the start and open at the end: [Start, End).
132 int64_t Start, End;
133
134 /// StartPtr - The getelementptr instruction that points to the start of the
135 /// range.
136 Value *StartPtr;
137
138 /// Alignment - The known alignment of the first store.
139 unsigned Alignment;
140
141 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000142 SmallVector<Instruction*, 16> TheStores;
Owen Andersona723d1e2008-04-09 08:23:16 +0000143
144 bool isProfitableToUseMemset(const TargetData &TD) const;
145
146};
147} // end anon namespace
148
149bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
150 // If we found more than 8 stores to merge or 64 bytes, use memset.
151 if (TheStores.size() >= 8 || End-Start >= 64) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000152
153 // If there is nothing to merge, don't do anything.
154 if (TheStores.size() < 2) return false;
155
156 // If any of the stores are a memset, then it is always good to extend the
157 // memset.
158 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
159 if (!isa<StoreInst>(TheStores[i]))
160 return true;
Owen Andersona723d1e2008-04-09 08:23:16 +0000161
162 // Assume that the code generator is capable of merging pairs of stores
163 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000164 if (TheStores.size() == 2) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000165
166 // If we have fewer than 8 stores, it can still be worthwhile to do this.
167 // For example, merging 4 i8 stores into an i32 store is useful almost always.
168 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
169 // memset will be split into 2 32-bit stores anyway) and doing so can
170 // pessimize the llvm optimizer.
171 //
172 // Since we don't have perfect knowledge here, make some assumptions: assume
173 // the maximum GPR width is the same size as the pointer size and assume that
174 // this width can be stored. If so, check to see whether we will end up
175 // actually reducing the number of stores used.
176 unsigned Bytes = unsigned(End-Start);
177 unsigned NumPointerStores = Bytes/TD.getPointerSize();
178
179 // Assume the remaining bytes if any are done a byte at a time.
180 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
181
182 // If we will reduce the # stores (according to this heuristic), do the
183 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
184 // etc.
185 return TheStores.size() > NumPointerStores+NumByteStores;
186}
187
188
189namespace {
190class MemsetRanges {
191 /// Ranges - A sorted list of the memset ranges. We use std::list here
192 /// because each element is relatively large and expensive to copy.
193 std::list<MemsetRange> Ranges;
194 typedef std::list<MemsetRange>::iterator range_iterator;
Chris Lattner67a716a2011-01-08 20:24:01 +0000195 const TargetData &TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000196public:
Chris Lattner67a716a2011-01-08 20:24:01 +0000197 MemsetRanges(const TargetData &td) : TD(td) {}
Owen Andersona723d1e2008-04-09 08:23:16 +0000198
199 typedef std::list<MemsetRange>::const_iterator const_iterator;
200 const_iterator begin() const { return Ranges.begin(); }
201 const_iterator end() const { return Ranges.end(); }
202 bool empty() const { return Ranges.empty(); }
203
Chris Lattner67a716a2011-01-08 20:24:01 +0000204 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000205 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
206 addStore(OffsetFromFirst, SI);
207 else
208 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000209 }
Chris Lattner06511262011-01-08 20:54:51 +0000210
211 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
212 int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
213
214 addRange(OffsetFromFirst, StoreSize,
215 SI->getPointerOperand(), SI->getAlignment(), SI);
216 }
217
218 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
219 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
220 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
221 }
222
223 void addRange(int64_t Start, int64_t Size, Value *Ptr,
224 unsigned Alignment, Instruction *Inst);
225
Owen Andersona723d1e2008-04-09 08:23:16 +0000226};
227
228} // end anon namespace
229
230
Chris Lattner06511262011-01-08 20:54:51 +0000231/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000232/// new range for the specified store at the specified offset, merging into
233/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000234///
235/// Do a linear search of the ranges to see if this can be joined and/or to
236/// find the insertion point in the list. We keep the ranges sorted for
237/// simplicity here. This is a linear search of a linked list, which is ugly,
238/// however the number of ranges is limited, so this won't get crazy slow.
239void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
240 unsigned Alignment, Instruction *Inst) {
241 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000242 range_iterator I = Ranges.begin(), E = Ranges.end();
243
244 while (I != E && Start > I->End)
245 ++I;
246
247 // We now know that I == E, in which case we didn't find anything to merge
248 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
249 // to insert a new range. Handle this now.
250 if (I == E || End < I->Start) {
251 MemsetRange &R = *Ranges.insert(I, MemsetRange());
252 R.Start = Start;
253 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000254 R.StartPtr = Ptr;
255 R.Alignment = Alignment;
256 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000257 return;
258 }
Chris Lattner06511262011-01-08 20:54:51 +0000259
Owen Andersona723d1e2008-04-09 08:23:16 +0000260 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000261 I->TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000262
263 // At this point, we may have an interval that completely contains our store.
264 // If so, just add it to the interval and return.
265 if (I->Start <= Start && I->End >= End)
266 return;
267
268 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
269 // but is not entirely contained within the range.
270
271 // See if the range extends the start of the range. In this case, it couldn't
272 // possibly cause it to join the prior range, because otherwise we would have
273 // stopped on *it*.
274 if (Start < I->Start) {
275 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000276 I->StartPtr = Ptr;
277 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000278 }
279
280 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
281 // is in or right at the end of I), and that End >= I->Start. Extend I out to
282 // End.
283 if (End > I->End) {
284 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000285 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000286 while (++NextI != E && End >= NextI->Start) {
287 // Merge the range in.
288 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
289 if (NextI->End > I->End)
290 I->End = NextI->End;
291 Ranges.erase(NextI);
292 NextI = I;
293 }
294 }
295}
296
297//===----------------------------------------------------------------------===//
298// MemCpyOpt Pass
299//===----------------------------------------------------------------------===//
300
301namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000302 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000303 MemoryDependenceAnalysis *MD;
Chris Lattner67a716a2011-01-08 20:24:01 +0000304 const TargetData *TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000305 public:
306 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000307 MemCpyOpt() : FunctionPass(ID) {
308 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000309 MD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000310 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000311
Chris Lattner67a716a2011-01-08 20:24:01 +0000312 bool runOnFunction(Function &F);
313
Owen Andersona723d1e2008-04-09 08:23:16 +0000314 private:
315 // This transformation requires dominator postdominator info
316 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
317 AU.setPreservesCFG();
318 AU.addRequired<DominatorTree>();
319 AU.addRequired<MemoryDependenceAnalysis>();
320 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000321 AU.addPreserved<AliasAnalysis>();
322 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000323 }
324
325 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000326 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000327 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000328 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000329 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000330 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
331 uint64_t cpyLen, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000332 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
333 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000334 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000335 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
336 Value *ByteVal);
337
Owen Andersona723d1e2008-04-09 08:23:16 +0000338 bool iterateOnFunction(Function &F);
339 };
340
341 char MemCpyOpt::ID = 0;
342}
343
344// createMemCpyOptPass - The public interface to this file...
345FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
346
Owen Anderson2ab36d32010-10-12 19:48:12 +0000347INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
348 false, false)
349INITIALIZE_PASS_DEPENDENCY(DominatorTree)
350INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
351INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
352INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
353 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000354
Chris Lattner67a716a2011-01-08 20:24:01 +0000355/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000356/// some other patterns to fold away. In particular, this looks for stores to
Chris Lattner67a716a2011-01-08 20:24:01 +0000357/// neighboring locations of memory. If it sees enough consequtive ones, it
358/// attempts to merge them together into a memcpy/memset.
359Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
360 Value *StartPtr, Value *ByteVal) {
361 if (TD == 0) return 0;
362
Chris Lattner67a716a2011-01-08 20:24:01 +0000363 // Okay, so we now have a single store that can be splatable. Scan to find
364 // all subsequent stores of the same value to offset from the same pointer.
365 // Join these together into ranges, so we can decide whether contiguous blocks
366 // are stored.
367 MemsetRanges Ranges(*TD);
368
369 BasicBlock::iterator BI = StartInst;
370 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000371 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
372 // If the instruction is readnone, ignore it, otherwise bail out. We
373 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000374 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000375 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
376 break;
377 continue;
378 }
379
380 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
381 // If this is a store, see if we can merge it in.
382 if (NextStore->isVolatile()) break;
383
384 // Check to see if this stored value is of the same byte-splattable value.
385 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
386 break;
Chris Lattner67a716a2011-01-08 20:24:01 +0000387
Chris Lattner06511262011-01-08 20:54:51 +0000388 // Check to see if this store is to a constant offset from the start ptr.
389 int64_t Offset;
Chris Lattnerf4268502011-01-09 19:26:10 +0000390 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
391 Offset, *TD))
Chris Lattner06511262011-01-08 20:54:51 +0000392 break;
Chris Lattner67a716a2011-01-08 20:24:01 +0000393
Chris Lattner06511262011-01-08 20:54:51 +0000394 Ranges.addStore(Offset, NextStore);
395 } else {
Chris Lattnera806be62011-01-10 00:47:34 +0000396 break;
397
Chris Lattner06511262011-01-08 20:54:51 +0000398 MemSetInst *MSI = cast<MemSetInst>(BI);
399
400 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
401 !isa<ConstantInt>(MSI->getLength()))
402 break;
403
404 // Check to see if this store is to a constant offset from the start ptr.
405 int64_t Offset;
406 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
407 break;
408
409 Ranges.addMemSet(Offset, MSI);
410 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000411 }
412
413 // If we have no ranges, then we just had a single store with nothing that
414 // could be merged in. This is a very common case of course.
415 if (Ranges.empty())
416 return 0;
417
418 // If we had at least one store that could be merged in, add the starting
419 // store as well. We try to avoid this unless there is at least something
420 // interesting as a small compile-time optimization.
421 Ranges.addInst(0, StartInst);
422
423 // If we create any memsets, we put it right before the first instruction that
424 // isn't part of the memset block. This ensure that the memset is dominated
425 // by any addressing instruction needed by the start of the block.
426 IRBuilder<> Builder(BI);
427
428 // Now that we have full information about ranges, loop over the ranges and
429 // emit memset's for anything big enough to be worthwhile.
430 Instruction *AMemSet = 0;
431 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
432 I != E; ++I) {
433 const MemsetRange &Range = *I;
434
435 if (Range.TheStores.size() == 1) continue;
436
437 // If it is profitable to lower this range to memset, do so now.
438 if (!Range.isProfitableToUseMemset(*TD))
439 continue;
440
441 // Otherwise, we do want to transform this! Create a new memset.
442 // Get the starting pointer of the block.
443 StartPtr = Range.StartPtr;
444
445 // Determine alignment
446 unsigned Alignment = Range.Alignment;
447 if (Alignment == 0) {
448 const Type *EltType =
449 cast<PointerType>(StartPtr->getType())->getElementType();
450 Alignment = TD->getABITypeAlignment(EltType);
451 }
452
453 AMemSet =
454 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
455
456 DEBUG(dbgs() << "Replace stores:\n";
457 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
458 dbgs() << *Range.TheStores[i] << '\n';
459 dbgs() << "With: " << *AMemSet << '\n');
460
461 // Zap all the stores.
Chris Lattner06511262011-01-08 20:54:51 +0000462 for (SmallVector<Instruction*, 16>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000463 SI = Range.TheStores.begin(),
Chris Lattner8a629572011-01-08 22:19:21 +0000464 SE = Range.TheStores.end(); SI != SE; ++SI) {
465 MD->removeInstruction(*SI);
Chris Lattner67a716a2011-01-08 20:24:01 +0000466 (*SI)->eraseFromParent();
Chris Lattner8a629572011-01-08 22:19:21 +0000467 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000468 ++NumMemSetInfer;
469 }
470
471 return AMemSet;
472}
473
474
Chris Lattner61c6ba82009-09-01 17:09:55 +0000475bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000476 if (SI->isVolatile()) return false;
477
Chris Lattner67a716a2011-01-08 20:24:01 +0000478 if (TD == 0) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000479
480 // Detect cases where we're performing call slot forwarding, but
481 // happen to be using a load-store pair to implement it, rather than
482 // a memcpy.
483 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
484 if (!LI->isVolatile() && LI->hasOneUse()) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000485 MemDepResult dep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000486 CallInst *C = 0;
487 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
488 C = dyn_cast<CallInst>(dep.getInst());
489
490 if (C) {
491 bool changed = performCallSlotOptzn(LI,
492 SI->getPointerOperand()->stripPointerCasts(),
493 LI->getPointerOperand()->stripPointerCasts(),
494 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
495 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000496 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000497 SI->eraseFromParent();
Chris Lattnerf4268502011-01-09 19:26:10 +0000498 MD->removeInstruction(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000499 LI->eraseFromParent();
500 ++NumMemCpyInstr;
501 return true;
502 }
503 }
504 }
505 }
506
Owen Andersona723d1e2008-04-09 08:23:16 +0000507 // There are two cases that are interesting for this code to handle: memcpy
508 // and memset. Right now we only handle memset.
509
510 // Ensure that the value being stored is something that can be memset'able a
511 // byte at a time like "0" or "-1" or any width, as well as things like
512 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000513 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
514 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
515 ByteVal)) {
516 BBI = I; // Don't invalidate iterator.
517 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000518 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000519
Chris Lattner67a716a2011-01-08 20:24:01 +0000520 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000521}
522
Chris Lattnerd90a1922011-01-08 21:19:19 +0000523bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
Chris Lattnerd8408272011-01-09 23:52:48 +0000524 // Temporarily disable this.
525 return false;
526
Chris Lattnerd90a1922011-01-08 21:19:19 +0000527 // See if there is another memset or store neighboring this memset which
528 // allows us to widen out the memset to do a single larger store.
Chris Lattner0468e3e2011-01-08 22:11:56 +0000529 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
530 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
531 MSI->getValue())) {
532 BBI = I; // Don't invalidate iterator.
533 return true;
534 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000535 return false;
536}
537
Owen Andersona723d1e2008-04-09 08:23:16 +0000538
539/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
540/// and checks for the possibility of a call slot optimization by having
541/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000542bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
543 Value *cpyDest, Value *cpySrc,
544 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000545 // The general transformation to keep in mind is
546 //
547 // call @func(..., src, ...)
548 // memcpy(dest, src, ...)
549 //
550 // ->
551 //
552 // memcpy(dest, src, ...)
553 // call @func(..., dest, ...)
554 //
555 // Since moving the memcpy is technically awkward, we additionally check that
556 // src only holds uninitialized values at the moment of the call, meaning that
557 // the memcpy can be discarded rather than moved.
558
559 // Deliberately get the source and destination with bitcasts stripped away,
560 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000561 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000562
Owen Andersona723d1e2008-04-09 08:23:16 +0000563 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000564 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000565 if (!srcAlloca)
566 return false;
567
568 // Check that all of src is copied to dest.
Chris Lattner67a716a2011-01-08 20:24:01 +0000569 if (TD == 0) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000570
Chris Lattner61c6ba82009-09-01 17:09:55 +0000571 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000572 if (!srcArraySize)
573 return false;
574
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000575 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000576 srcArraySize->getZExtValue();
577
Owen Anderson65491212010-10-15 22:52:12 +0000578 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000579 return false;
580
581 // Check that accessing the first srcSize bytes of dest will not cause a
582 // trap. Otherwise the transform is invalid since it might cause a trap
583 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000584 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000585 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000586 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000587 if (!destArraySize)
588 return false;
589
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000590 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000591 destArraySize->getZExtValue();
592
593 if (destSize < srcSize)
594 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000595 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000596 // If the destination is an sret parameter then only accesses that are
597 // outside of the returned struct type can trap.
598 if (!A->hasStructRetAttr())
599 return false;
600
Chris Lattner61c6ba82009-09-01 17:09:55 +0000601 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000602 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000603
604 if (destSize < srcSize)
605 return false;
606 } else {
607 return false;
608 }
609
610 // Check that src is not accessed except via the call and the memcpy. This
611 // guarantees that it holds only undefined values when passed in (so the final
612 // memcpy can be dropped), that it is not read or written between the call and
613 // the memcpy, and that writing beyond the end of it is undefined.
614 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
615 srcAlloca->use_end());
616 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000617 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000618
Owen Anderson009e4f72008-06-01 22:26:26 +0000619 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000620 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
621 I != E; ++I)
622 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000623 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000624 if (G->hasAllZeroIndices())
625 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
626 I != E; ++I)
627 srcUseList.push_back(*I);
628 else
629 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000630 } else if (UI != C && UI != cpy) {
631 return false;
632 }
633 }
634
635 // Since we're changing the parameter to the callsite, we need to make sure
636 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000637 DominatorTree &DT = getAnalysis<DominatorTree>();
638 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000639 if (!DT.dominates(cpyDestInst, C))
640 return false;
641
642 // In addition to knowing that the call does not access src in some
643 // unexpected manner, for example via a global, which we deduce from
644 // the use analysis, we also need to know that it does not sneakily
645 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000646 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner06511262011-01-08 20:54:51 +0000647 if (AA.getModRefInfo(C, cpyDest, srcSize) != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000648 return false;
649
650 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000651 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000652 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000653 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000654 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000655 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000656 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000657 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000658 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000659 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000660 else
661 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
662 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000663 }
664
Owen Anderson12cb36c2008-06-01 21:52:16 +0000665 if (!changedArgument)
666 return false;
667
Owen Andersona723d1e2008-04-09 08:23:16 +0000668 // Drop any cached information about the call, because we may have changed
669 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000670 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000671
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000672 // Remove the memcpy.
673 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000674 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000675
676 return true;
677}
678
Chris Lattner43f8e432010-11-18 07:02:37 +0000679/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
680/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
681/// copy from MDep's input if we can. MSize is the size of M's copy.
682///
683bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
684 uint64_t MSize) {
685 // We can only transforms memcpy's where the dest of one is the source of the
686 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000687 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000688 return false;
689
Chris Lattnerf7f35462010-12-09 07:39:50 +0000690 // If dep instruction is reading from our current input, then it is a noop
691 // transfer and substituting the input won't change this instruction. Just
692 // ignore the input and let someone else zap MDep. This handles cases like:
693 // memcpy(a <- a)
694 // memcpy(b <- a)
695 if (M->getSource() == MDep->getSource())
696 return false;
697
Chris Lattner43f8e432010-11-18 07:02:37 +0000698 // Second, the length of the memcpy's must be the same, or the preceeding one
699 // must be larger than the following one.
700 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
701 if (!C1) return false;
702
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000703 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000704
705 // Verify that the copied-from memory doesn't change in between the two
706 // transfers. For example, in:
707 // memcpy(a <- b)
708 // *b = 42;
709 // memcpy(c <- a)
710 // It would be invalid to transform the second memcpy into memcpy(c <- b).
711 //
712 // TODO: If the code between M and MDep is transparent to the destination "c",
713 // then we could still perform the xform by moving M up to the first memcpy.
714 //
715 // NOTE: This is conservative, it will stop on any read from the source loc,
716 // not just the defining memcpy.
717 MemDepResult SourceDep =
718 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
719 false, M, M->getParent());
720 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
721 return false;
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000722
723 // If the dest of the second might alias the source of the first, then the
724 // source and dest might overlap. We still want to eliminate the intermediate
725 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000726 bool UseMemMove = false;
727 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
728 UseMemMove = true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000729
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000730 // If all checks passed, then we can transform M.
Chris Lattner43f8e432010-11-18 07:02:37 +0000731
732 // Make sure to use the lesser of the alignment of the source and the dest
733 // since we're changing where we're reading from, but don't want to increase
734 // the alignment past what can be read from or written to.
735 // TODO: Is this worth it if we're creating a less aligned memcpy? For
736 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000737 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Chris Lattner61db1f52010-12-26 22:57:41 +0000738
739 IRBuilder<> Builder(M);
740 if (UseMemMove)
741 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
742 Align, M->isVolatile());
743 else
744 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
745 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000746
Chris Lattner604f6fe2010-11-21 08:06:10 +0000747 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000748 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000749 M->eraseFromParent();
750 ++NumMemCpyInstr;
751 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000752}
753
754
Gabor Greif7d3056b2010-07-28 22:50:26 +0000755/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
756/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
757/// B to be a memcpy from X to Z (or potentially a memmove, depending on
758/// circumstances). This allows later passes to remove the first memcpy
759/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000760bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000761 // We can only optimize statically-sized memcpy's that are non-volatile.
762 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
763 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000764
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000765 // If the source and destination of the memcpy are the same, then zap it.
766 if (M->getSource() == M->getDest()) {
767 MD->removeInstruction(M);
768 M->eraseFromParent();
769 return false;
770 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000771
772 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000773 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000774 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000775 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000776 IRBuilder<> Builder(M);
777 Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
778 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000779 MD->removeInstruction(M);
780 M->eraseFromParent();
781 ++NumCpyToSet;
782 return true;
783 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000784
Owen Andersona8bd6582008-04-21 07:45:10 +0000785 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000786 // a) memcpy-memcpy xform which exposes redundance for DSE.
787 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000788 MemDepResult DepInfo = MD->getDependency(M);
789 if (!DepInfo.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000790 return false;
Owen Andersona8bd6582008-04-21 07:45:10 +0000791
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000792 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
793 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Owen Andersona723d1e2008-04-09 08:23:16 +0000794
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000795 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000796 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
797 CopySize->getZExtValue(), C)) {
Chris Lattnerf4268502011-01-09 19:26:10 +0000798 MD->removeInstruction(M);
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000799 M->eraseFromParent();
800 return true;
801 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000802 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000803
Owen Anderson02e99882008-04-29 21:51:00 +0000804 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000805}
806
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000807/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
808/// are guaranteed not to alias.
809bool MemCpyOpt::processMemMove(MemMoveInst *M) {
810 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
811
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000812 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000813 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000814 return false;
815
David Greenecb33fd12010-01-05 01:27:47 +0000816 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000817
818 // If not, then we know we can transform this.
819 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000820 const Type *ArgTys[3] = { M->getRawDest()->getType(),
821 M->getRawSource()->getType(),
822 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000823 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
824 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000825
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000826 // MemDep may have over conservative information about this instruction, just
827 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000828 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000829
830 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000831 return true;
832}
833
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000834/// processByValArgument - This is called on every byval argument in call sites.
835bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Chris Lattner67a716a2011-01-08 20:24:01 +0000836 if (TD == 0) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000837
Chris Lattner604f6fe2010-11-21 08:06:10 +0000838 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000839 Value *ByValArg = CS.getArgument(ArgNo);
Chris Lattnerb5a31962010-12-01 01:24:55 +0000840 const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
841 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000842 MemDepResult DepInfo =
843 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
844 true, CS.getInstruction(),
845 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000846 if (!DepInfo.isClobber())
847 return false;
848
849 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
850 // a memcpy, see if we can byval from the source of the memcpy instead of the
851 // result.
852 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
853 if (MDep == 0 || MDep->isVolatile() ||
854 ByValArg->stripPointerCasts() != MDep->getDest())
855 return false;
856
857 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000858 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000859 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000860 return false;
861
862 // Get the alignment of the byval. If it is greater than the memcpy, then we
863 // can't do the substitution. If the call doesn't specify the alignment, then
864 // it is some target specific value that we can't know.
865 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
866 if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
867 return false;
868
869 // Verify that the copied-from memory doesn't change in between the memcpy and
870 // the byval call.
871 // memcpy(a <- b)
872 // *b = 42;
873 // foo(*a)
874 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000875 //
876 // NOTE: This is conservative, it will stop on any read from the source loc,
877 // not just the defining memcpy.
878 MemDepResult SourceDep =
879 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
880 false, CS.getInstruction(), MDep->getParent());
881 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
882 return false;
883
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000884 Value *TmpCast = MDep->getSource();
885 if (MDep->getSource()->getType() != ByValArg->getType())
886 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
887 "tmpcast", CS.getInstruction());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000888
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000889 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
890 << " " << *MDep << "\n"
891 << " " << *CS.getInstruction() << "\n");
892
893 // Otherwise we're good! Update the byval argument.
894 CS.setArgument(ArgNo, TmpCast);
895 ++NumMemCpyInstr;
896 return true;
897}
898
899/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000900bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000901 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000902
Chris Lattner61c6ba82009-09-01 17:09:55 +0000903 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000904 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000905 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000906 // Avoid invalidating the iterator.
907 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000908
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000909 bool RepeatInstruction = false;
910
Owen Andersona8bd6582008-04-21 07:45:10 +0000911 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000912 MadeChange |= processStore(SI, BI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000913 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
914 RepeatInstruction = processMemSet(M, BI);
915 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000916 RepeatInstruction = processMemCpy(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000917 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000918 RepeatInstruction = processMemMove(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000919 else if (CallSite CS = (Value*)I) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000920 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
921 if (CS.paramHasAttr(i+1, Attribute::ByVal))
922 MadeChange |= processByValArgument(CS, i);
923 }
924
925 // Reprocess the instruction if desired.
926 if (RepeatInstruction) {
Chris Lattner8a629572011-01-08 22:19:21 +0000927 if (BI != BB->begin()) --BI;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000928 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000929 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000930 }
931 }
932
Chris Lattner61c6ba82009-09-01 17:09:55 +0000933 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000934}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000935
936// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
937// function.
938//
939bool MemCpyOpt::runOnFunction(Function &F) {
940 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000941 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner67a716a2011-01-08 20:24:01 +0000942 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000943 while (1) {
944 if (!iterateOnFunction(F))
945 break;
946 MadeChange = true;
947 }
948
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000949 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000950 return MadeChange;
951}