blob: 76fab1cd281afd74e297f06a1c30dcaef30b73b2 [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 Lattner9fa11e92011-01-08 21:07:56 +000074 Ptr1 = Ptr1->stripPointerCasts();
75 Ptr2 = Ptr2->stripPointerCasts();
76 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
77 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
78
79 bool VariableIdxFound = false;
80
81 // If one pointer is a GEP and the other isn't, then see if the GEP is a
82 // constant offset from the base, as in "P" and "gep P, 1".
83 if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
84 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
85 return !VariableIdxFound;
86 }
87
88 if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
89 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
90 return !VariableIdxFound;
91 }
92
Owen Andersona723d1e2008-04-09 08:23:16 +000093 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
94 // base. After that base, they may have some number of common (and
95 // potentially variable) indices. After that they handle some constant
96 // offset, which determines their offset from each other. At this point, we
97 // handle no other case.
Owen Andersona723d1e2008-04-09 08:23:16 +000098 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
99 return false;
100
101 // Skip any common indices and track the GEP types.
102 unsigned Idx = 1;
103 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
104 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
105 break;
106
Owen Andersona723d1e2008-04-09 08:23:16 +0000107 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
108 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
109 if (VariableIdxFound) return false;
110
111 Offset = Offset2-Offset1;
112 return true;
113}
114
115
116/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
117/// This allows us to analyze stores like:
118/// store 0 -> P+1
119/// store 0 -> P+0
120/// store 0 -> P+3
121/// store 0 -> P+2
122/// which sometimes happens with stores to arrays of structs etc. When we see
123/// the first store, we make a range [1, 2). The second store extends the range
124/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
125/// two ranges into [0, 3) which is memset'able.
126namespace {
127struct MemsetRange {
128 // Start/End - A semi range that describes the span that this range covers.
129 // The range is closed at the start and open at the end: [Start, End).
130 int64_t Start, End;
131
132 /// StartPtr - The getelementptr instruction that points to the start of the
133 /// range.
134 Value *StartPtr;
135
136 /// Alignment - The known alignment of the first store.
137 unsigned Alignment;
138
139 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000140 SmallVector<Instruction*, 16> TheStores;
Owen Andersona723d1e2008-04-09 08:23:16 +0000141
142 bool isProfitableToUseMemset(const TargetData &TD) const;
143
144};
145} // end anon namespace
146
147bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
148 // If we found more than 8 stores to merge or 64 bytes, use memset.
149 if (TheStores.size() >= 8 || End-Start >= 64) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000150
151 // If there is nothing to merge, don't do anything.
152 if (TheStores.size() < 2) return false;
153
154 // If any of the stores are a memset, then it is always good to extend the
155 // memset.
156 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
157 if (!isa<StoreInst>(TheStores[i]))
158 return true;
Owen Andersona723d1e2008-04-09 08:23:16 +0000159
160 // Assume that the code generator is capable of merging pairs of stores
161 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000162 if (TheStores.size() == 2) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000163
164 // If we have fewer than 8 stores, it can still be worthwhile to do this.
165 // For example, merging 4 i8 stores into an i32 store is useful almost always.
166 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
167 // memset will be split into 2 32-bit stores anyway) and doing so can
168 // pessimize the llvm optimizer.
169 //
170 // Since we don't have perfect knowledge here, make some assumptions: assume
171 // the maximum GPR width is the same size as the pointer size and assume that
172 // this width can be stored. If so, check to see whether we will end up
173 // actually reducing the number of stores used.
174 unsigned Bytes = unsigned(End-Start);
175 unsigned NumPointerStores = Bytes/TD.getPointerSize();
176
177 // Assume the remaining bytes if any are done a byte at a time.
178 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
179
180 // If we will reduce the # stores (according to this heuristic), do the
181 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
182 // etc.
183 return TheStores.size() > NumPointerStores+NumByteStores;
184}
185
186
187namespace {
188class MemsetRanges {
189 /// Ranges - A sorted list of the memset ranges. We use std::list here
190 /// because each element is relatively large and expensive to copy.
191 std::list<MemsetRange> Ranges;
192 typedef std::list<MemsetRange>::iterator range_iterator;
Chris Lattner67a716a2011-01-08 20:24:01 +0000193 const TargetData &TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000194public:
Chris Lattner67a716a2011-01-08 20:24:01 +0000195 MemsetRanges(const TargetData &td) : TD(td) {}
Owen Andersona723d1e2008-04-09 08:23:16 +0000196
197 typedef std::list<MemsetRange>::const_iterator const_iterator;
198 const_iterator begin() const { return Ranges.begin(); }
199 const_iterator end() const { return Ranges.end(); }
200 bool empty() const { return Ranges.empty(); }
201
Chris Lattner67a716a2011-01-08 20:24:01 +0000202 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000203 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
204 addStore(OffsetFromFirst, SI);
205 else
206 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000207 }
Chris Lattner06511262011-01-08 20:54:51 +0000208
209 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
210 int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
211
212 addRange(OffsetFromFirst, StoreSize,
213 SI->getPointerOperand(), SI->getAlignment(), SI);
214 }
215
216 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
217 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
218 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
219 }
220
221 void addRange(int64_t Start, int64_t Size, Value *Ptr,
222 unsigned Alignment, Instruction *Inst);
223
Owen Andersona723d1e2008-04-09 08:23:16 +0000224};
225
226} // end anon namespace
227
228
Chris Lattner06511262011-01-08 20:54:51 +0000229/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000230/// new range for the specified store at the specified offset, merging into
231/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000232///
233/// Do a linear search of the ranges to see if this can be joined and/or to
234/// find the insertion point in the list. We keep the ranges sorted for
235/// simplicity here. This is a linear search of a linked list, which is ugly,
236/// however the number of ranges is limited, so this won't get crazy slow.
237void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
238 unsigned Alignment, Instruction *Inst) {
239 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000240 range_iterator I = Ranges.begin(), E = Ranges.end();
241
242 while (I != E && Start > I->End)
243 ++I;
244
245 // We now know that I == E, in which case we didn't find anything to merge
246 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
247 // to insert a new range. Handle this now.
248 if (I == E || End < I->Start) {
249 MemsetRange &R = *Ranges.insert(I, MemsetRange());
250 R.Start = Start;
251 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000252 R.StartPtr = Ptr;
253 R.Alignment = Alignment;
254 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000255 return;
256 }
Chris Lattner06511262011-01-08 20:54:51 +0000257
Owen Andersona723d1e2008-04-09 08:23:16 +0000258 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000259 I->TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000260
261 // At this point, we may have an interval that completely contains our store.
262 // If so, just add it to the interval and return.
263 if (I->Start <= Start && I->End >= End)
264 return;
265
266 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
267 // but is not entirely contained within the range.
268
269 // See if the range extends the start of the range. In this case, it couldn't
270 // possibly cause it to join the prior range, because otherwise we would have
271 // stopped on *it*.
272 if (Start < I->Start) {
273 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000274 I->StartPtr = Ptr;
275 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000276 }
277
278 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
279 // is in or right at the end of I), and that End >= I->Start. Extend I out to
280 // End.
281 if (End > I->End) {
282 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000283 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000284 while (++NextI != E && End >= NextI->Start) {
285 // Merge the range in.
286 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
287 if (NextI->End > I->End)
288 I->End = NextI->End;
289 Ranges.erase(NextI);
290 NextI = I;
291 }
292 }
293}
294
295//===----------------------------------------------------------------------===//
296// MemCpyOpt Pass
297//===----------------------------------------------------------------------===//
298
299namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000300 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000301 MemoryDependenceAnalysis *MD;
Chris Lattner67a716a2011-01-08 20:24:01 +0000302 const TargetData *TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000303 public:
304 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000305 MemCpyOpt() : FunctionPass(ID) {
306 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000307 MD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000308 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000309
Chris Lattner67a716a2011-01-08 20:24:01 +0000310 bool runOnFunction(Function &F);
311
Owen Andersona723d1e2008-04-09 08:23:16 +0000312 private:
313 // This transformation requires dominator postdominator info
314 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
315 AU.setPreservesCFG();
316 AU.addRequired<DominatorTree>();
317 AU.addRequired<MemoryDependenceAnalysis>();
318 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000319 AU.addPreserved<AliasAnalysis>();
320 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000321 }
322
323 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000324 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000325 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000326 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000327 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000328 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
329 uint64_t cpyLen, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000330 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
331 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000332 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000333 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
334 Value *ByteVal);
335
Owen Andersona723d1e2008-04-09 08:23:16 +0000336 bool iterateOnFunction(Function &F);
337 };
338
339 char MemCpyOpt::ID = 0;
340}
341
342// createMemCpyOptPass - The public interface to this file...
343FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
344
Owen Anderson2ab36d32010-10-12 19:48:12 +0000345INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
346 false, false)
347INITIALIZE_PASS_DEPENDENCY(DominatorTree)
348INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
349INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
350INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
351 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000352
Chris Lattner67a716a2011-01-08 20:24:01 +0000353/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000354/// some other patterns to fold away. In particular, this looks for stores to
Chris Lattner67a716a2011-01-08 20:24:01 +0000355/// neighboring locations of memory. If it sees enough consequtive ones, it
356/// attempts to merge them together into a memcpy/memset.
357Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
358 Value *StartPtr, Value *ByteVal) {
359 if (TD == 0) return 0;
360
Chris Lattner67a716a2011-01-08 20:24:01 +0000361 // Okay, so we now have a single store that can be splatable. Scan to find
362 // all subsequent stores of the same value to offset from the same pointer.
363 // Join these together into ranges, so we can decide whether contiguous blocks
364 // are stored.
365 MemsetRanges Ranges(*TD);
366
367 BasicBlock::iterator BI = StartInst;
368 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000369 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
370 // If the instruction is readnone, ignore it, otherwise bail out. We
371 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000372 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000373 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
374 break;
375 continue;
376 }
377
378 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
379 // If this is a store, see if we can merge it in.
380 if (NextStore->isVolatile()) break;
381
382 // Check to see if this stored value is of the same byte-splattable value.
383 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
384 break;
Chris Lattner67a716a2011-01-08 20:24:01 +0000385
Chris Lattner06511262011-01-08 20:54:51 +0000386 // Check to see if this store is to a constant offset from the start ptr.
387 int64_t Offset;
388 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
389 break;
Chris Lattner67a716a2011-01-08 20:24:01 +0000390
Chris Lattner06511262011-01-08 20:54:51 +0000391 Ranges.addStore(Offset, NextStore);
392 } else {
393 MemSetInst *MSI = cast<MemSetInst>(BI);
394
395 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
396 !isa<ConstantInt>(MSI->getLength()))
397 break;
398
399 // Check to see if this store is to a constant offset from the start ptr.
400 int64_t Offset;
401 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
402 break;
403
404 Ranges.addMemSet(Offset, MSI);
405 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000406 }
407
408 // If we have no ranges, then we just had a single store with nothing that
409 // could be merged in. This is a very common case of course.
410 if (Ranges.empty())
411 return 0;
412
413 // If we had at least one store that could be merged in, add the starting
414 // store as well. We try to avoid this unless there is at least something
415 // interesting as a small compile-time optimization.
416 Ranges.addInst(0, StartInst);
417
418 // If we create any memsets, we put it right before the first instruction that
419 // isn't part of the memset block. This ensure that the memset is dominated
420 // by any addressing instruction needed by the start of the block.
421 IRBuilder<> Builder(BI);
422
423 // Now that we have full information about ranges, loop over the ranges and
424 // emit memset's for anything big enough to be worthwhile.
425 Instruction *AMemSet = 0;
426 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
427 I != E; ++I) {
428 const MemsetRange &Range = *I;
429
430 if (Range.TheStores.size() == 1) continue;
431
432 // If it is profitable to lower this range to memset, do so now.
433 if (!Range.isProfitableToUseMemset(*TD))
434 continue;
435
436 // Otherwise, we do want to transform this! Create a new memset.
437 // Get the starting pointer of the block.
438 StartPtr = Range.StartPtr;
439
440 // Determine alignment
441 unsigned Alignment = Range.Alignment;
442 if (Alignment == 0) {
443 const Type *EltType =
444 cast<PointerType>(StartPtr->getType())->getElementType();
445 Alignment = TD->getABITypeAlignment(EltType);
446 }
447
448 AMemSet =
449 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
450
451 DEBUG(dbgs() << "Replace stores:\n";
452 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
453 dbgs() << *Range.TheStores[i] << '\n';
454 dbgs() << "With: " << *AMemSet << '\n');
455
456 // Zap all the stores.
Chris Lattner06511262011-01-08 20:54:51 +0000457 for (SmallVector<Instruction*, 16>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000458 SI = Range.TheStores.begin(),
459 SE = Range.TheStores.end(); SI != SE; ++SI)
460 (*SI)->eraseFromParent();
461 ++NumMemSetInfer;
462 }
463
464 return AMemSet;
465}
466
467
Chris Lattner61c6ba82009-09-01 17:09:55 +0000468bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000469 if (SI->isVolatile()) return false;
470
Chris Lattner67a716a2011-01-08 20:24:01 +0000471 if (TD == 0) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000472
473 // Detect cases where we're performing call slot forwarding, but
474 // happen to be using a load-store pair to implement it, rather than
475 // a memcpy.
476 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
477 if (!LI->isVolatile() && LI->hasOneUse()) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000478 MemDepResult dep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000479 CallInst *C = 0;
480 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
481 C = dyn_cast<CallInst>(dep.getInst());
482
483 if (C) {
484 bool changed = performCallSlotOptzn(LI,
485 SI->getPointerOperand()->stripPointerCasts(),
486 LI->getPointerOperand()->stripPointerCasts(),
487 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
488 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000489 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000490 SI->eraseFromParent();
491 LI->eraseFromParent();
492 ++NumMemCpyInstr;
493 return true;
494 }
495 }
496 }
497 }
498
Owen Andersona723d1e2008-04-09 08:23:16 +0000499 // There are two cases that are interesting for this code to handle: memcpy
500 // and memset. Right now we only handle memset.
501
502 // Ensure that the value being stored is something that can be memset'able a
503 // byte at a time like "0" or "-1" or any width, as well as things like
504 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000505 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
506 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
507 ByteVal)) {
508 BBI = I; // Don't invalidate iterator.
509 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000510 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000511
Chris Lattner67a716a2011-01-08 20:24:01 +0000512 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000513}
514
Chris Lattnerd90a1922011-01-08 21:19:19 +0000515bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
516 // See if there is another memset or store neighboring this memset which
517 // allows us to widen out the memset to do a single larger store.
Chris Lattner0468e3e2011-01-08 22:11:56 +0000518 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
519 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
520 MSI->getValue())) {
521 BBI = I; // Don't invalidate iterator.
522 return true;
523 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000524 return false;
525}
526
Owen Andersona723d1e2008-04-09 08:23:16 +0000527
528/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
529/// and checks for the possibility of a call slot optimization by having
530/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000531bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
532 Value *cpyDest, Value *cpySrc,
533 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000534 // The general transformation to keep in mind is
535 //
536 // call @func(..., src, ...)
537 // memcpy(dest, src, ...)
538 //
539 // ->
540 //
541 // memcpy(dest, src, ...)
542 // call @func(..., dest, ...)
543 //
544 // Since moving the memcpy is technically awkward, we additionally check that
545 // src only holds uninitialized values at the moment of the call, meaning that
546 // the memcpy can be discarded rather than moved.
547
548 // Deliberately get the source and destination with bitcasts stripped away,
549 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000550 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000551
Owen Andersona723d1e2008-04-09 08:23:16 +0000552 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000553 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000554 if (!srcAlloca)
555 return false;
556
557 // Check that all of src is copied to dest.
Chris Lattner67a716a2011-01-08 20:24:01 +0000558 if (TD == 0) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000559
Chris Lattner61c6ba82009-09-01 17:09:55 +0000560 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000561 if (!srcArraySize)
562 return false;
563
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000564 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000565 srcArraySize->getZExtValue();
566
Owen Anderson65491212010-10-15 22:52:12 +0000567 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000568 return false;
569
570 // Check that accessing the first srcSize bytes of dest will not cause a
571 // trap. Otherwise the transform is invalid since it might cause a trap
572 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000573 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000574 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000575 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000576 if (!destArraySize)
577 return false;
578
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000579 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000580 destArraySize->getZExtValue();
581
582 if (destSize < srcSize)
583 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000584 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000585 // If the destination is an sret parameter then only accesses that are
586 // outside of the returned struct type can trap.
587 if (!A->hasStructRetAttr())
588 return false;
589
Chris Lattner61c6ba82009-09-01 17:09:55 +0000590 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000591 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000592
593 if (destSize < srcSize)
594 return false;
595 } else {
596 return false;
597 }
598
599 // Check that src is not accessed except via the call and the memcpy. This
600 // guarantees that it holds only undefined values when passed in (so the final
601 // memcpy can be dropped), that it is not read or written between the call and
602 // the memcpy, and that writing beyond the end of it is undefined.
603 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
604 srcAlloca->use_end());
605 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000606 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000607
Owen Anderson009e4f72008-06-01 22:26:26 +0000608 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000609 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
610 I != E; ++I)
611 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000612 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000613 if (G->hasAllZeroIndices())
614 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
615 I != E; ++I)
616 srcUseList.push_back(*I);
617 else
618 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000619 } else if (UI != C && UI != cpy) {
620 return false;
621 }
622 }
623
624 // Since we're changing the parameter to the callsite, we need to make sure
625 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000626 DominatorTree &DT = getAnalysis<DominatorTree>();
627 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000628 if (!DT.dominates(cpyDestInst, C))
629 return false;
630
631 // In addition to knowing that the call does not access src in some
632 // unexpected manner, for example via a global, which we deduce from
633 // the use analysis, we also need to know that it does not sneakily
634 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000635 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner06511262011-01-08 20:54:51 +0000636 if (AA.getModRefInfo(C, cpyDest, srcSize) != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000637 return false;
638
639 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000640 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000641 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000642 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000643 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000644 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000645 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000646 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000647 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000648 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000649 else
650 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
651 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000652 }
653
Owen Anderson12cb36c2008-06-01 21:52:16 +0000654 if (!changedArgument)
655 return false;
656
Owen Andersona723d1e2008-04-09 08:23:16 +0000657 // Drop any cached information about the call, because we may have changed
658 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000659 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000660
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000661 // Remove the memcpy.
662 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000663 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000664
665 return true;
666}
667
Chris Lattner43f8e432010-11-18 07:02:37 +0000668/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
669/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
670/// copy from MDep's input if we can. MSize is the size of M's copy.
671///
672bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
673 uint64_t MSize) {
674 // We can only transforms memcpy's where the dest of one is the source of the
675 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000676 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000677 return false;
678
Chris Lattnerf7f35462010-12-09 07:39:50 +0000679 // If dep instruction is reading from our current input, then it is a noop
680 // transfer and substituting the input won't change this instruction. Just
681 // ignore the input and let someone else zap MDep. This handles cases like:
682 // memcpy(a <- a)
683 // memcpy(b <- a)
684 if (M->getSource() == MDep->getSource())
685 return false;
686
Chris Lattner43f8e432010-11-18 07:02:37 +0000687 // Second, the length of the memcpy's must be the same, or the preceeding one
688 // must be larger than the following one.
689 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
690 if (!C1) return false;
691
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000692 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000693
694 // Verify that the copied-from memory doesn't change in between the two
695 // transfers. For example, in:
696 // memcpy(a <- b)
697 // *b = 42;
698 // memcpy(c <- a)
699 // It would be invalid to transform the second memcpy into memcpy(c <- b).
700 //
701 // TODO: If the code between M and MDep is transparent to the destination "c",
702 // then we could still perform the xform by moving M up to the first memcpy.
703 //
704 // NOTE: This is conservative, it will stop on any read from the source loc,
705 // not just the defining memcpy.
706 MemDepResult SourceDep =
707 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
708 false, M, M->getParent());
709 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
710 return false;
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000711
712 // If the dest of the second might alias the source of the first, then the
713 // source and dest might overlap. We still want to eliminate the intermediate
714 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000715 bool UseMemMove = false;
716 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
717 UseMemMove = true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000718
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000719 // If all checks passed, then we can transform M.
Chris Lattner43f8e432010-11-18 07:02:37 +0000720
721 // Make sure to use the lesser of the alignment of the source and the dest
722 // since we're changing where we're reading from, but don't want to increase
723 // the alignment past what can be read from or written to.
724 // TODO: Is this worth it if we're creating a less aligned memcpy? For
725 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000726 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Chris Lattner61db1f52010-12-26 22:57:41 +0000727
728 IRBuilder<> Builder(M);
729 if (UseMemMove)
730 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
731 Align, M->isVolatile());
732 else
733 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
734 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000735
Chris Lattner604f6fe2010-11-21 08:06:10 +0000736 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000737 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000738 M->eraseFromParent();
739 ++NumMemCpyInstr;
740 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000741}
742
743
Gabor Greif7d3056b2010-07-28 22:50:26 +0000744/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
745/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
746/// B to be a memcpy from X to Z (or potentially a memmove, depending on
747/// circumstances). This allows later passes to remove the first memcpy
748/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000749bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000750 // We can only optimize statically-sized memcpy's that are non-volatile.
751 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
752 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000753
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000754 // If the source and destination of the memcpy are the same, then zap it.
755 if (M->getSource() == M->getDest()) {
756 MD->removeInstruction(M);
757 M->eraseFromParent();
758 return false;
759 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000760
761 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000762 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000763 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000764 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000765 IRBuilder<> Builder(M);
766 Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
767 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000768 MD->removeInstruction(M);
769 M->eraseFromParent();
770 ++NumCpyToSet;
771 return true;
772 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000773
Owen Andersona8bd6582008-04-21 07:45:10 +0000774 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000775 // a) memcpy-memcpy xform which exposes redundance for DSE.
776 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000777 MemDepResult DepInfo = MD->getDependency(M);
778 if (!DepInfo.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000779 return false;
Owen Andersona8bd6582008-04-21 07:45:10 +0000780
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000781 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
782 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Owen Andersona723d1e2008-04-09 08:23:16 +0000783
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000784 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000785 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
786 CopySize->getZExtValue(), C)) {
787 M->eraseFromParent();
788 return true;
789 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000790 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000791
Owen Anderson02e99882008-04-29 21:51:00 +0000792 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000793}
794
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000795/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
796/// are guaranteed not to alias.
797bool MemCpyOpt::processMemMove(MemMoveInst *M) {
798 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
799
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000800 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000801 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000802 return false;
803
David Greenecb33fd12010-01-05 01:27:47 +0000804 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000805
806 // If not, then we know we can transform this.
807 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000808 const Type *ArgTys[3] = { M->getRawDest()->getType(),
809 M->getRawSource()->getType(),
810 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000811 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
812 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000813
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000814 // MemDep may have over conservative information about this instruction, just
815 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000816 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000817
818 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000819 return true;
820}
821
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000822/// processByValArgument - This is called on every byval argument in call sites.
823bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Chris Lattner67a716a2011-01-08 20:24:01 +0000824 if (TD == 0) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000825
Chris Lattner604f6fe2010-11-21 08:06:10 +0000826 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000827 Value *ByValArg = CS.getArgument(ArgNo);
Chris Lattnerb5a31962010-12-01 01:24:55 +0000828 const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
829 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000830 MemDepResult DepInfo =
831 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
832 true, CS.getInstruction(),
833 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000834 if (!DepInfo.isClobber())
835 return false;
836
837 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
838 // a memcpy, see if we can byval from the source of the memcpy instead of the
839 // result.
840 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
841 if (MDep == 0 || MDep->isVolatile() ||
842 ByValArg->stripPointerCasts() != MDep->getDest())
843 return false;
844
845 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000846 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000847 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000848 return false;
849
850 // Get the alignment of the byval. If it is greater than the memcpy, then we
851 // can't do the substitution. If the call doesn't specify the alignment, then
852 // it is some target specific value that we can't know.
853 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
854 if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
855 return false;
856
857 // Verify that the copied-from memory doesn't change in between the memcpy and
858 // the byval call.
859 // memcpy(a <- b)
860 // *b = 42;
861 // foo(*a)
862 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000863 //
864 // NOTE: This is conservative, it will stop on any read from the source loc,
865 // not just the defining memcpy.
866 MemDepResult SourceDep =
867 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
868 false, CS.getInstruction(), MDep->getParent());
869 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
870 return false;
871
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000872 Value *TmpCast = MDep->getSource();
873 if (MDep->getSource()->getType() != ByValArg->getType())
874 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
875 "tmpcast", CS.getInstruction());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000876
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000877 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
878 << " " << *MDep << "\n"
879 << " " << *CS.getInstruction() << "\n");
880
881 // Otherwise we're good! Update the byval argument.
882 CS.setArgument(ArgNo, TmpCast);
883 ++NumMemCpyInstr;
884 return true;
885}
886
887/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000888bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000889 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000890
Chris Lattner61c6ba82009-09-01 17:09:55 +0000891 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000892 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000893 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000894 // Avoid invalidating the iterator.
895 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000896
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000897 bool RepeatInstruction = false;
898
Owen Andersona8bd6582008-04-21 07:45:10 +0000899 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000900 MadeChange |= processStore(SI, BI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000901 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
902 RepeatInstruction = processMemSet(M, BI);
903 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000904 RepeatInstruction = processMemCpy(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000905 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000906 RepeatInstruction = processMemMove(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000907 else if (CallSite CS = (Value*)I) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000908 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
909 if (CS.paramHasAttr(i+1, Attribute::ByVal))
910 MadeChange |= processByValArgument(CS, i);
911 }
912
913 // Reprocess the instruction if desired.
914 if (RepeatInstruction) {
915 --BI;
916 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000917 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000918 }
919 }
920
Chris Lattner61c6ba82009-09-01 17:09:55 +0000921 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000922}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000923
924// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
925// function.
926//
927bool MemCpyOpt::runOnFunction(Function &F) {
928 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000929 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner67a716a2011-01-08 20:24:01 +0000930 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000931 while (1) {
932 if (!iterateOnFunction(F))
933 break;
934 MadeChange = true;
935 }
936
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000937 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000938 return MadeChange;
939}