blob: a4f60878e6fed2c3eec2a15a00257f1cc73dc283 [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) {
Owen Andersona723d1e2008-04-09 08:23:16 +000074 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
75 // base. After that base, they may have some number of common (and
76 // potentially variable) indices. After that they handle some constant
77 // offset, which determines their offset from each other. At this point, we
78 // handle no other case.
79 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
80 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
81 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
82 return false;
83
84 // Skip any common indices and track the GEP types.
85 unsigned Idx = 1;
86 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
87 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
88 break;
89
90 bool VariableIdxFound = false;
91 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
92 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
93 if (VariableIdxFound) return false;
94
95 Offset = Offset2-Offset1;
96 return true;
97}
98
99
100/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
101/// This allows us to analyze stores like:
102/// store 0 -> P+1
103/// store 0 -> P+0
104/// store 0 -> P+3
105/// store 0 -> P+2
106/// which sometimes happens with stores to arrays of structs etc. When we see
107/// the first store, we make a range [1, 2). The second store extends the range
108/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
109/// two ranges into [0, 3) which is memset'able.
110namespace {
111struct MemsetRange {
112 // Start/End - A semi range that describes the span that this range covers.
113 // The range is closed at the start and open at the end: [Start, End).
114 int64_t Start, End;
115
116 /// StartPtr - The getelementptr instruction that points to the start of the
117 /// range.
118 Value *StartPtr;
119
120 /// Alignment - The known alignment of the first store.
121 unsigned Alignment;
122
123 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000124 SmallVector<Instruction*, 16> TheStores;
Owen Andersona723d1e2008-04-09 08:23:16 +0000125
126 bool isProfitableToUseMemset(const TargetData &TD) const;
127
128};
129} // end anon namespace
130
131bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
132 // If we found more than 8 stores to merge or 64 bytes, use memset.
133 if (TheStores.size() >= 8 || End-Start >= 64) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000134
135 // If there is nothing to merge, don't do anything.
136 if (TheStores.size() < 2) return false;
137
138 // If any of the stores are a memset, then it is always good to extend the
139 // memset.
140 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
141 if (!isa<StoreInst>(TheStores[i]))
142 return true;
Owen Andersona723d1e2008-04-09 08:23:16 +0000143
144 // Assume that the code generator is capable of merging pairs of stores
145 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000146 if (TheStores.size() == 2) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000147
148 // If we have fewer than 8 stores, it can still be worthwhile to do this.
149 // For example, merging 4 i8 stores into an i32 store is useful almost always.
150 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
151 // memset will be split into 2 32-bit stores anyway) and doing so can
152 // pessimize the llvm optimizer.
153 //
154 // Since we don't have perfect knowledge here, make some assumptions: assume
155 // the maximum GPR width is the same size as the pointer size and assume that
156 // this width can be stored. If so, check to see whether we will end up
157 // actually reducing the number of stores used.
158 unsigned Bytes = unsigned(End-Start);
159 unsigned NumPointerStores = Bytes/TD.getPointerSize();
160
161 // Assume the remaining bytes if any are done a byte at a time.
162 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
163
164 // If we will reduce the # stores (according to this heuristic), do the
165 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
166 // etc.
167 return TheStores.size() > NumPointerStores+NumByteStores;
168}
169
170
171namespace {
172class MemsetRanges {
173 /// Ranges - A sorted list of the memset ranges. We use std::list here
174 /// because each element is relatively large and expensive to copy.
175 std::list<MemsetRange> Ranges;
176 typedef std::list<MemsetRange>::iterator range_iterator;
Chris Lattner67a716a2011-01-08 20:24:01 +0000177 const TargetData &TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000178public:
Chris Lattner67a716a2011-01-08 20:24:01 +0000179 MemsetRanges(const TargetData &td) : TD(td) {}
Owen Andersona723d1e2008-04-09 08:23:16 +0000180
181 typedef std::list<MemsetRange>::const_iterator const_iterator;
182 const_iterator begin() const { return Ranges.begin(); }
183 const_iterator end() const { return Ranges.end(); }
184 bool empty() const { return Ranges.empty(); }
185
Chris Lattner67a716a2011-01-08 20:24:01 +0000186 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000187 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
188 addStore(OffsetFromFirst, SI);
189 else
190 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000191 }
Chris Lattner06511262011-01-08 20:54:51 +0000192
193 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
194 int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
195
196 addRange(OffsetFromFirst, StoreSize,
197 SI->getPointerOperand(), SI->getAlignment(), SI);
198 }
199
200 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
201 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
202 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
203 }
204
205 void addRange(int64_t Start, int64_t Size, Value *Ptr,
206 unsigned Alignment, Instruction *Inst);
207
Owen Andersona723d1e2008-04-09 08:23:16 +0000208};
209
210} // end anon namespace
211
212
Chris Lattner06511262011-01-08 20:54:51 +0000213/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000214/// new range for the specified store at the specified offset, merging into
215/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000216///
217/// Do a linear search of the ranges to see if this can be joined and/or to
218/// find the insertion point in the list. We keep the ranges sorted for
219/// simplicity here. This is a linear search of a linked list, which is ugly,
220/// however the number of ranges is limited, so this won't get crazy slow.
221void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
222 unsigned Alignment, Instruction *Inst) {
223 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000224 range_iterator I = Ranges.begin(), E = Ranges.end();
225
226 while (I != E && Start > I->End)
227 ++I;
228
229 // We now know that I == E, in which case we didn't find anything to merge
230 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
231 // to insert a new range. Handle this now.
232 if (I == E || End < I->Start) {
233 MemsetRange &R = *Ranges.insert(I, MemsetRange());
234 R.Start = Start;
235 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000236 R.StartPtr = Ptr;
237 R.Alignment = Alignment;
238 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000239 return;
240 }
Chris Lattner06511262011-01-08 20:54:51 +0000241
Owen Andersona723d1e2008-04-09 08:23:16 +0000242 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000243 I->TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000244
245 // At this point, we may have an interval that completely contains our store.
246 // If so, just add it to the interval and return.
247 if (I->Start <= Start && I->End >= End)
248 return;
249
250 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
251 // but is not entirely contained within the range.
252
253 // See if the range extends the start of the range. In this case, it couldn't
254 // possibly cause it to join the prior range, because otherwise we would have
255 // stopped on *it*.
256 if (Start < I->Start) {
257 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000258 I->StartPtr = Ptr;
259 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000260 }
261
262 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
263 // is in or right at the end of I), and that End >= I->Start. Extend I out to
264 // End.
265 if (End > I->End) {
266 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000267 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000268 while (++NextI != E && End >= NextI->Start) {
269 // Merge the range in.
270 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
271 if (NextI->End > I->End)
272 I->End = NextI->End;
273 Ranges.erase(NextI);
274 NextI = I;
275 }
276 }
277}
278
279//===----------------------------------------------------------------------===//
280// MemCpyOpt Pass
281//===----------------------------------------------------------------------===//
282
283namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000284 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000285 MemoryDependenceAnalysis *MD;
Chris Lattner67a716a2011-01-08 20:24:01 +0000286 const TargetData *TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000287 public:
288 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000289 MemCpyOpt() : FunctionPass(ID) {
290 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000291 MD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000292 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000293
Chris Lattner67a716a2011-01-08 20:24:01 +0000294 bool runOnFunction(Function &F);
295
Owen Andersona723d1e2008-04-09 08:23:16 +0000296 private:
297 // This transformation requires dominator postdominator info
298 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
299 AU.setPreservesCFG();
300 AU.addRequired<DominatorTree>();
301 AU.addRequired<MemoryDependenceAnalysis>();
302 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000303 AU.addPreserved<AliasAnalysis>();
304 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000305 }
306
307 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000308 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
309 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000310 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000311 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
312 uint64_t cpyLen, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000313 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
314 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000315 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000316 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
317 Value *ByteVal);
318
Owen Andersona723d1e2008-04-09 08:23:16 +0000319 bool iterateOnFunction(Function &F);
320 };
321
322 char MemCpyOpt::ID = 0;
323}
324
325// createMemCpyOptPass - The public interface to this file...
326FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
327
Owen Anderson2ab36d32010-10-12 19:48:12 +0000328INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
329 false, false)
330INITIALIZE_PASS_DEPENDENCY(DominatorTree)
331INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
332INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
333INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
334 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000335
Chris Lattner67a716a2011-01-08 20:24:01 +0000336/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000337/// some other patterns to fold away. In particular, this looks for stores to
Chris Lattner67a716a2011-01-08 20:24:01 +0000338/// neighboring locations of memory. If it sees enough consequtive ones, it
339/// attempts to merge them together into a memcpy/memset.
340Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
341 Value *StartPtr, Value *ByteVal) {
342 if (TD == 0) return 0;
343
Chris Lattner67a716a2011-01-08 20:24:01 +0000344 // Okay, so we now have a single store that can be splatable. Scan to find
345 // all subsequent stores of the same value to offset from the same pointer.
346 // Join these together into ranges, so we can decide whether contiguous blocks
347 // are stored.
348 MemsetRanges Ranges(*TD);
349
350 BasicBlock::iterator BI = StartInst;
351 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000352 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
353 // If the instruction is readnone, ignore it, otherwise bail out. We
354 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000355 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000356 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
357 break;
358 continue;
359 }
360
361 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
362 // If this is a store, see if we can merge it in.
363 if (NextStore->isVolatile()) break;
364
365 // Check to see if this stored value is of the same byte-splattable value.
366 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
367 break;
Chris Lattner67a716a2011-01-08 20:24:01 +0000368
Chris Lattner06511262011-01-08 20:54:51 +0000369 // Check to see if this store is to a constant offset from the start ptr.
370 int64_t Offset;
371 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
372 break;
Chris Lattner67a716a2011-01-08 20:24:01 +0000373
Chris Lattner06511262011-01-08 20:54:51 +0000374 Ranges.addStore(Offset, NextStore);
375 } else {
376 MemSetInst *MSI = cast<MemSetInst>(BI);
377
378 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
379 !isa<ConstantInt>(MSI->getLength()))
380 break;
381
382 // Check to see if this store is to a constant offset from the start ptr.
383 int64_t Offset;
384 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
385 break;
386
387 Ranges.addMemSet(Offset, MSI);
388 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000389 }
390
391 // If we have no ranges, then we just had a single store with nothing that
392 // could be merged in. This is a very common case of course.
393 if (Ranges.empty())
394 return 0;
395
396 // If we had at least one store that could be merged in, add the starting
397 // store as well. We try to avoid this unless there is at least something
398 // interesting as a small compile-time optimization.
399 Ranges.addInst(0, StartInst);
400
401 // If we create any memsets, we put it right before the first instruction that
402 // isn't part of the memset block. This ensure that the memset is dominated
403 // by any addressing instruction needed by the start of the block.
404 IRBuilder<> Builder(BI);
405
406 // Now that we have full information about ranges, loop over the ranges and
407 // emit memset's for anything big enough to be worthwhile.
408 Instruction *AMemSet = 0;
409 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
410 I != E; ++I) {
411 const MemsetRange &Range = *I;
412
413 if (Range.TheStores.size() == 1) continue;
414
415 // If it is profitable to lower this range to memset, do so now.
416 if (!Range.isProfitableToUseMemset(*TD))
417 continue;
418
419 // Otherwise, we do want to transform this! Create a new memset.
420 // Get the starting pointer of the block.
421 StartPtr = Range.StartPtr;
422
423 // Determine alignment
424 unsigned Alignment = Range.Alignment;
425 if (Alignment == 0) {
426 const Type *EltType =
427 cast<PointerType>(StartPtr->getType())->getElementType();
428 Alignment = TD->getABITypeAlignment(EltType);
429 }
430
431 AMemSet =
432 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
433
434 DEBUG(dbgs() << "Replace stores:\n";
435 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
436 dbgs() << *Range.TheStores[i] << '\n';
437 dbgs() << "With: " << *AMemSet << '\n');
438
439 // Zap all the stores.
Chris Lattner06511262011-01-08 20:54:51 +0000440 for (SmallVector<Instruction*, 16>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000441 SI = Range.TheStores.begin(),
442 SE = Range.TheStores.end(); SI != SE; ++SI)
443 (*SI)->eraseFromParent();
444 ++NumMemSetInfer;
445 }
446
447 return AMemSet;
448}
449
450
Chris Lattner61c6ba82009-09-01 17:09:55 +0000451bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000452 if (SI->isVolatile()) return false;
453
Chris Lattner67a716a2011-01-08 20:24:01 +0000454 if (TD == 0) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000455
456 // Detect cases where we're performing call slot forwarding, but
457 // happen to be using a load-store pair to implement it, rather than
458 // a memcpy.
459 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
460 if (!LI->isVolatile() && LI->hasOneUse()) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000461 MemDepResult dep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000462 CallInst *C = 0;
463 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
464 C = dyn_cast<CallInst>(dep.getInst());
465
466 if (C) {
467 bool changed = performCallSlotOptzn(LI,
468 SI->getPointerOperand()->stripPointerCasts(),
469 LI->getPointerOperand()->stripPointerCasts(),
470 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
471 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000472 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000473 SI->eraseFromParent();
474 LI->eraseFromParent();
475 ++NumMemCpyInstr;
476 return true;
477 }
478 }
479 }
480 }
481
Owen Andersona723d1e2008-04-09 08:23:16 +0000482 // There are two cases that are interesting for this code to handle: memcpy
483 // and memset. Right now we only handle memset.
484
485 // Ensure that the value being stored is something that can be memset'able a
486 // byte at a time like "0" or "-1" or any width, as well as things like
487 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000488 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
489 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
490 ByteVal)) {
491 BBI = I; // Don't invalidate iterator.
492 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000493 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000494
Chris Lattner67a716a2011-01-08 20:24:01 +0000495 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000496}
497
498
499/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
500/// and checks for the possibility of a call slot optimization by having
501/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000502bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
503 Value *cpyDest, Value *cpySrc,
504 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000505 // The general transformation to keep in mind is
506 //
507 // call @func(..., src, ...)
508 // memcpy(dest, src, ...)
509 //
510 // ->
511 //
512 // memcpy(dest, src, ...)
513 // call @func(..., dest, ...)
514 //
515 // Since moving the memcpy is technically awkward, we additionally check that
516 // src only holds uninitialized values at the moment of the call, meaning that
517 // the memcpy can be discarded rather than moved.
518
519 // Deliberately get the source and destination with bitcasts stripped away,
520 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000521 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000522
Owen Andersona723d1e2008-04-09 08:23:16 +0000523 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000524 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000525 if (!srcAlloca)
526 return false;
527
528 // Check that all of src is copied to dest.
Chris Lattner67a716a2011-01-08 20:24:01 +0000529 if (TD == 0) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000530
Chris Lattner61c6ba82009-09-01 17:09:55 +0000531 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000532 if (!srcArraySize)
533 return false;
534
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000535 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000536 srcArraySize->getZExtValue();
537
Owen Anderson65491212010-10-15 22:52:12 +0000538 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000539 return false;
540
541 // Check that accessing the first srcSize bytes of dest will not cause a
542 // trap. Otherwise the transform is invalid since it might cause a trap
543 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000544 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000545 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000546 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000547 if (!destArraySize)
548 return false;
549
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000550 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000551 destArraySize->getZExtValue();
552
553 if (destSize < srcSize)
554 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000555 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000556 // If the destination is an sret parameter then only accesses that are
557 // outside of the returned struct type can trap.
558 if (!A->hasStructRetAttr())
559 return false;
560
Chris Lattner61c6ba82009-09-01 17:09:55 +0000561 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000562 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000563
564 if (destSize < srcSize)
565 return false;
566 } else {
567 return false;
568 }
569
570 // Check that src is not accessed except via the call and the memcpy. This
571 // guarantees that it holds only undefined values when passed in (so the final
572 // memcpy can be dropped), that it is not read or written between the call and
573 // the memcpy, and that writing beyond the end of it is undefined.
574 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
575 srcAlloca->use_end());
576 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000577 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000578
Owen Anderson009e4f72008-06-01 22:26:26 +0000579 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000580 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
581 I != E; ++I)
582 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000583 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000584 if (G->hasAllZeroIndices())
585 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
586 I != E; ++I)
587 srcUseList.push_back(*I);
588 else
589 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000590 } else if (UI != C && UI != cpy) {
591 return false;
592 }
593 }
594
595 // Since we're changing the parameter to the callsite, we need to make sure
596 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000597 DominatorTree &DT = getAnalysis<DominatorTree>();
598 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000599 if (!DT.dominates(cpyDestInst, C))
600 return false;
601
602 // In addition to knowing that the call does not access src in some
603 // unexpected manner, for example via a global, which we deduce from
604 // the use analysis, we also need to know that it does not sneakily
605 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000606 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner06511262011-01-08 20:54:51 +0000607 if (AA.getModRefInfo(C, cpyDest, srcSize) != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000608 return false;
609
610 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000611 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000612 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000613 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000614 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000615 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000616 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000617 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000618 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000619 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000620 else
621 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
622 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000623 }
624
Owen Anderson12cb36c2008-06-01 21:52:16 +0000625 if (!changedArgument)
626 return false;
627
Owen Andersona723d1e2008-04-09 08:23:16 +0000628 // Drop any cached information about the call, because we may have changed
629 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000630 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000631
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000632 // Remove the memcpy.
633 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000634 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000635
636 return true;
637}
638
Chris Lattner43f8e432010-11-18 07:02:37 +0000639/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
640/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
641/// copy from MDep's input if we can. MSize is the size of M's copy.
642///
643bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
644 uint64_t MSize) {
645 // We can only transforms memcpy's where the dest of one is the source of the
646 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000647 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000648 return false;
649
Chris Lattnerf7f35462010-12-09 07:39:50 +0000650 // If dep instruction is reading from our current input, then it is a noop
651 // transfer and substituting the input won't change this instruction. Just
652 // ignore the input and let someone else zap MDep. This handles cases like:
653 // memcpy(a <- a)
654 // memcpy(b <- a)
655 if (M->getSource() == MDep->getSource())
656 return false;
657
Chris Lattner43f8e432010-11-18 07:02:37 +0000658 // Second, the length of the memcpy's must be the same, or the preceeding one
659 // must be larger than the following one.
660 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
661 if (!C1) return false;
662
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000663 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000664
665 // Verify that the copied-from memory doesn't change in between the two
666 // transfers. For example, in:
667 // memcpy(a <- b)
668 // *b = 42;
669 // memcpy(c <- a)
670 // It would be invalid to transform the second memcpy into memcpy(c <- b).
671 //
672 // TODO: If the code between M and MDep is transparent to the destination "c",
673 // then we could still perform the xform by moving M up to the first memcpy.
674 //
675 // NOTE: This is conservative, it will stop on any read from the source loc,
676 // not just the defining memcpy.
677 MemDepResult SourceDep =
678 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
679 false, M, M->getParent());
680 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
681 return false;
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000682
683 // If the dest of the second might alias the source of the first, then the
684 // source and dest might overlap. We still want to eliminate the intermediate
685 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000686 bool UseMemMove = false;
687 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
688 UseMemMove = true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000689
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000690 // If all checks passed, then we can transform M.
Chris Lattner43f8e432010-11-18 07:02:37 +0000691
692 // Make sure to use the lesser of the alignment of the source and the dest
693 // since we're changing where we're reading from, but don't want to increase
694 // the alignment past what can be read from or written to.
695 // TODO: Is this worth it if we're creating a less aligned memcpy? For
696 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000697 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Chris Lattner61db1f52010-12-26 22:57:41 +0000698
699 IRBuilder<> Builder(M);
700 if (UseMemMove)
701 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
702 Align, M->isVolatile());
703 else
704 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
705 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000706
Chris Lattner604f6fe2010-11-21 08:06:10 +0000707 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000708 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000709 M->eraseFromParent();
710 ++NumMemCpyInstr;
711 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000712}
713
714
Gabor Greif7d3056b2010-07-28 22:50:26 +0000715/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
716/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
717/// B to be a memcpy from X to Z (or potentially a memmove, depending on
718/// circumstances). This allows later passes to remove the first memcpy
719/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000720bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000721 // We can only optimize statically-sized memcpy's that are non-volatile.
722 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
723 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000724
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000725 // If the source and destination of the memcpy are the same, then zap it.
726 if (M->getSource() == M->getDest()) {
727 MD->removeInstruction(M);
728 M->eraseFromParent();
729 return false;
730 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000731
732 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000733 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000734 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000735 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000736 IRBuilder<> Builder(M);
737 Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
738 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000739 MD->removeInstruction(M);
740 M->eraseFromParent();
741 ++NumCpyToSet;
742 return true;
743 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000744
Owen Andersona8bd6582008-04-21 07:45:10 +0000745 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000746 // a) memcpy-memcpy xform which exposes redundance for DSE.
747 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000748 MemDepResult DepInfo = MD->getDependency(M);
749 if (!DepInfo.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000750 return false;
Owen Andersona8bd6582008-04-21 07:45:10 +0000751
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000752 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()))
753 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Owen Andersona723d1e2008-04-09 08:23:16 +0000754
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000755 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000756 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
757 CopySize->getZExtValue(), C)) {
758 M->eraseFromParent();
759 return true;
760 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000761 }
Owen Anderson02e99882008-04-29 21:51:00 +0000762 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000763}
764
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000765/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
766/// are guaranteed not to alias.
767bool MemCpyOpt::processMemMove(MemMoveInst *M) {
768 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
769
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000770 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000771 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000772 return false;
773
David Greenecb33fd12010-01-05 01:27:47 +0000774 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000775
776 // If not, then we know we can transform this.
777 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000778 const Type *ArgTys[3] = { M->getRawDest()->getType(),
779 M->getRawSource()->getType(),
780 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000781 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
782 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000783
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000784 // MemDep may have over conservative information about this instruction, just
785 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000786 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000787
788 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000789 return true;
790}
791
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000792/// processByValArgument - This is called on every byval argument in call sites.
793bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Chris Lattner67a716a2011-01-08 20:24:01 +0000794 if (TD == 0) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000795
Chris Lattner604f6fe2010-11-21 08:06:10 +0000796 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000797 Value *ByValArg = CS.getArgument(ArgNo);
Chris Lattnerb5a31962010-12-01 01:24:55 +0000798 const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType();
799 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000800 MemDepResult DepInfo =
801 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
802 true, CS.getInstruction(),
803 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000804 if (!DepInfo.isClobber())
805 return false;
806
807 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
808 // a memcpy, see if we can byval from the source of the memcpy instead of the
809 // result.
810 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
811 if (MDep == 0 || MDep->isVolatile() ||
812 ByValArg->stripPointerCasts() != MDep->getDest())
813 return false;
814
815 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000816 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000817 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000818 return false;
819
820 // Get the alignment of the byval. If it is greater than the memcpy, then we
821 // can't do the substitution. If the call doesn't specify the alignment, then
822 // it is some target specific value that we can't know.
823 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
824 if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign)
825 return false;
826
827 // Verify that the copied-from memory doesn't change in between the memcpy and
828 // the byval call.
829 // memcpy(a <- b)
830 // *b = 42;
831 // foo(*a)
832 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000833 //
834 // NOTE: This is conservative, it will stop on any read from the source loc,
835 // not just the defining memcpy.
836 MemDepResult SourceDep =
837 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
838 false, CS.getInstruction(), MDep->getParent());
839 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
840 return false;
841
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000842 Value *TmpCast = MDep->getSource();
843 if (MDep->getSource()->getType() != ByValArg->getType())
844 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
845 "tmpcast", CS.getInstruction());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000846
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000847 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
848 << " " << *MDep << "\n"
849 << " " << *CS.getInstruction() << "\n");
850
851 // Otherwise we're good! Update the byval argument.
852 CS.setArgument(ArgNo, TmpCast);
853 ++NumMemCpyInstr;
854 return true;
855}
856
857/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000858bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000859 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000860
Chris Lattner61c6ba82009-09-01 17:09:55 +0000861 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000862 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000863 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000864 // Avoid invalidating the iterator.
865 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000866
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000867 bool RepeatInstruction = false;
868
Owen Andersona8bd6582008-04-21 07:45:10 +0000869 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000870 MadeChange |= processStore(SI, BI);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000871 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) {
872 RepeatInstruction = processMemCpy(M);
873 } else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) {
874 RepeatInstruction = processMemMove(M);
875 } else if (CallSite CS = (Value*)I) {
876 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
877 if (CS.paramHasAttr(i+1, Attribute::ByVal))
878 MadeChange |= processByValArgument(CS, i);
879 }
880
881 // Reprocess the instruction if desired.
882 if (RepeatInstruction) {
883 --BI;
884 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000885 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000886 }
887 }
888
Chris Lattner61c6ba82009-09-01 17:09:55 +0000889 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000890}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000891
892// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
893// function.
894//
895bool MemCpyOpt::runOnFunction(Function &F) {
896 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000897 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner67a716a2011-01-08 20:24:01 +0000898 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner61c6ba82009-09-01 17:09:55 +0000899 while (1) {
900 if (!iterateOnFunction(F))
901 break;
902 MadeChange = true;
903 }
904
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000905 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000906 return MadeChange;
907}