blob: 8d47e53762e5a6b4a7c6c416911358512f35d74d [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"
Owen Andersona723d1e2008-04-09 08:23:16 +000017#include "llvm/IntrinsicInst.h"
18#include "llvm/Instructions.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000019#include "llvm/LLVMContext.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"
Owen Andersona723d1e2008-04-09 08:23:16 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000027#include "llvm/Support/raw_ostream.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000028#include "llvm/Target/TargetData.h"
29#include <list>
30using namespace llvm;
31
32STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
33STATISTIC(NumMemSetInfer, "Number of memsets inferred");
34
Owen Andersona723d1e2008-04-09 08:23:16 +000035/// isBytewiseValue - If the specified value can be set by repeating the same
36/// byte in memory, return the i8 value that it is represented with. This is
37/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
38/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
39/// byte store (e.g. i16 0x1234), return null.
Owen Andersone922c022009-07-22 00:24:57 +000040static Value *isBytewiseValue(Value *V, LLVMContext& Context) {
Owen Andersona723d1e2008-04-09 08:23:16 +000041 // All byte-wide stores are splatable, even of arbitrary variables.
Owen Anderson1d0be152009-08-13 21:58:54 +000042 if (V->getType() == Type::getInt8Ty(Context)) return V;
Owen Andersona723d1e2008-04-09 08:23:16 +000043
44 // Constant float and double values can be handled as integer values if the
45 // corresponding integer value is "byteable". An important case is 0.0.
46 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000047 if (CFP->getType() == Type::getFloatTy(Context))
48 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(Context));
49 if (CFP->getType() == Type::getDoubleTy(Context))
50 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(Context));
Owen Andersona723d1e2008-04-09 08:23:16 +000051 // Don't handle long double formats, which have strange constraints.
52 }
53
54 // We can handle constant integers that are power of two in size and a
55 // multiple of 8 bits.
56 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
57 unsigned Width = CI->getBitWidth();
58 if (isPowerOf2_32(Width) && Width > 8) {
59 // We can handle this value if the recursive binary decomposition is the
60 // same at all levels.
61 APInt Val = CI->getValue();
62 APInt Val2;
63 while (Val.getBitWidth() != 8) {
64 unsigned NextWidth = Val.getBitWidth()/2;
65 Val2 = Val.lshr(NextWidth);
66 Val2.trunc(Val.getBitWidth()/2);
67 Val.trunc(Val.getBitWidth()/2);
68
69 // If the top/bottom halves aren't the same, reject it.
70 if (Val != Val2)
71 return 0;
72 }
Owen Andersoneed707b2009-07-24 23:12:02 +000073 return ConstantInt::get(Context, Val);
Owen Andersona723d1e2008-04-09 08:23:16 +000074 }
75 }
76
77 // Conceptually, we could handle things like:
78 // %a = zext i8 %X to i16
79 // %b = shl i16 %a, 8
80 // %c = or i16 %a, %b
81 // but until there is an example that actually needs this, it doesn't seem
82 // worth worrying about.
83 return 0;
84}
85
86static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
87 bool &VariableIdxFound, TargetData &TD) {
88 // Skip over the first indices.
89 gep_type_iterator GTI = gep_type_begin(GEP);
90 for (unsigned i = 1; i != Idx; ++i, ++GTI)
91 /*skip along*/;
92
93 // Compute the offset implied by the rest of the indices.
94 int64_t Offset = 0;
95 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
96 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
97 if (OpC == 0)
98 return VariableIdxFound = true;
99 if (OpC->isZero()) continue; // No offset.
100
101 // Handle struct indices, which add their field offset to the pointer.
102 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
103 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
104 continue;
105 }
106
107 // Otherwise, we have a sequential type like an array or vector. Multiply
108 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +0000109 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +0000110 Offset += Size*OpC->getSExtValue();
111 }
112
113 return Offset;
114}
115
116/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
117/// constant offset, and return that constant offset. For example, Ptr1 might
118/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
119static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
120 TargetData &TD) {
121 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
122 // base. After that base, they may have some number of common (and
123 // potentially variable) indices. After that they handle some constant
124 // offset, which determines their offset from each other. At this point, we
125 // handle no other case.
126 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
127 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
128 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
129 return false;
130
131 // Skip any common indices and track the GEP types.
132 unsigned Idx = 1;
133 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
134 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
135 break;
136
137 bool VariableIdxFound = false;
138 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
139 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
140 if (VariableIdxFound) return false;
141
142 Offset = Offset2-Offset1;
143 return true;
144}
145
146
147/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
148/// This allows us to analyze stores like:
149/// store 0 -> P+1
150/// store 0 -> P+0
151/// store 0 -> P+3
152/// store 0 -> P+2
153/// which sometimes happens with stores to arrays of structs etc. When we see
154/// the first store, we make a range [1, 2). The second store extends the range
155/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
156/// two ranges into [0, 3) which is memset'able.
157namespace {
158struct MemsetRange {
159 // Start/End - A semi range that describes the span that this range covers.
160 // The range is closed at the start and open at the end: [Start, End).
161 int64_t Start, End;
162
163 /// StartPtr - The getelementptr instruction that points to the start of the
164 /// range.
165 Value *StartPtr;
166
167 /// Alignment - The known alignment of the first store.
168 unsigned Alignment;
169
170 /// TheStores - The actual stores that make up this range.
171 SmallVector<StoreInst*, 16> TheStores;
172
173 bool isProfitableToUseMemset(const TargetData &TD) const;
174
175};
176} // end anon namespace
177
178bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
179 // If we found more than 8 stores to merge or 64 bytes, use memset.
180 if (TheStores.size() >= 8 || End-Start >= 64) return true;
181
182 // Assume that the code generator is capable of merging pairs of stores
183 // together if it wants to.
184 if (TheStores.size() <= 2) return false;
185
186 // If we have fewer than 8 stores, it can still be worthwhile to do this.
187 // For example, merging 4 i8 stores into an i32 store is useful almost always.
188 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
189 // memset will be split into 2 32-bit stores anyway) and doing so can
190 // pessimize the llvm optimizer.
191 //
192 // Since we don't have perfect knowledge here, make some assumptions: assume
193 // the maximum GPR width is the same size as the pointer size and assume that
194 // this width can be stored. If so, check to see whether we will end up
195 // actually reducing the number of stores used.
196 unsigned Bytes = unsigned(End-Start);
197 unsigned NumPointerStores = Bytes/TD.getPointerSize();
198
199 // Assume the remaining bytes if any are done a byte at a time.
200 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
201
202 // If we will reduce the # stores (according to this heuristic), do the
203 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
204 // etc.
205 return TheStores.size() > NumPointerStores+NumByteStores;
206}
207
208
209namespace {
210class MemsetRanges {
211 /// Ranges - A sorted list of the memset ranges. We use std::list here
212 /// because each element is relatively large and expensive to copy.
213 std::list<MemsetRange> Ranges;
214 typedef std::list<MemsetRange>::iterator range_iterator;
215 TargetData &TD;
216public:
217 MemsetRanges(TargetData &td) : TD(td) {}
218
219 typedef std::list<MemsetRange>::const_iterator const_iterator;
220 const_iterator begin() const { return Ranges.begin(); }
221 const_iterator end() const { return Ranges.end(); }
222 bool empty() const { return Ranges.empty(); }
223
224 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
225};
226
227} // end anon namespace
228
229
230/// addStore - Add a new store to the MemsetRanges data structure. This adds a
231/// new range for the specified store at the specified offset, merging into
232/// existing ranges as appropriate.
233void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
234 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
235
236 // Do a linear search of the ranges to see if this can be joined and/or to
237 // find the insertion point in the list. We keep the ranges sorted for
238 // simplicity here. This is a linear search of a linked list, which is ugly,
239 // however the number of ranges is limited, so this won't get crazy slow.
240 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;
252 R.StartPtr = SI->getPointerOperand();
253 R.Alignment = SI->getAlignment();
254 R.TheStores.push_back(SI);
255 return;
256 }
257
258 // This store overlaps with I, add it.
259 I->TheStores.push_back(SI);
260
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;
274 I->StartPtr = SI->getPointerOperand();
275 }
276
277 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
278 // is in or right at the end of I), and that End >= I->Start. Extend I out to
279 // End.
280 if (End > I->End) {
281 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000282 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000283 while (++NextI != E && End >= NextI->Start) {
284 // Merge the range in.
285 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
286 if (NextI->End > I->End)
287 I->End = NextI->End;
288 Ranges.erase(NextI);
289 NextI = I;
290 }
291 }
292}
293
294//===----------------------------------------------------------------------===//
295// MemCpyOpt Pass
296//===----------------------------------------------------------------------===//
297
298namespace {
299
300 class VISIBILITY_HIDDEN MemCpyOpt : public FunctionPass {
301 bool runOnFunction(Function &F);
302 public:
303 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000304 MemCpyOpt() : FunctionPass(&ID) {}
Owen Andersona723d1e2008-04-09 08:23:16 +0000305
306 private:
307 // This transformation requires dominator postdominator info
308 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
309 AU.setPreservesCFG();
310 AU.addRequired<DominatorTree>();
311 AU.addRequired<MemoryDependenceAnalysis>();
312 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000313 AU.addPreserved<AliasAnalysis>();
314 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000315 }
316
317 // Helper fuctions
Owen Andersona8bd6582008-04-21 07:45:10 +0000318 bool processStore(StoreInst *SI, BasicBlock::iterator& BBI);
319 bool processMemCpy(MemCpyInst* M);
320 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000321 bool iterateOnFunction(Function &F);
322 };
323
324 char MemCpyOpt::ID = 0;
325}
326
327// createMemCpyOptPass - The public interface to this file...
328FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
329
330static RegisterPass<MemCpyOpt> X("memcpyopt",
331 "MemCpy Optimization");
332
333
334
335/// processStore - When GVN is scanning forward over instructions, we look for
336/// some other patterns to fold away. In particular, this looks for stores to
337/// neighboring locations of memory. If it sees enough consequtive ones
338/// (currently 4) it attempts to merge them together into a memcpy/memset.
Owen Andersona8bd6582008-04-21 07:45:10 +0000339bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator& BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000340 if (SI->isVolatile()) return false;
341
342 // There are two cases that are interesting for this code to handle: memcpy
343 // and memset. Right now we only handle memset.
344
345 // Ensure that the value being stored is something that can be memset'able a
346 // byte at a time like "0" or "-1" or any width, as well as things like
347 // 0xA0A0A0A0 and 0.0.
Owen Andersone922c022009-07-22 00:24:57 +0000348 Value *ByteVal = isBytewiseValue(SI->getOperand(0), SI->getContext());
Owen Andersona723d1e2008-04-09 08:23:16 +0000349 if (!ByteVal)
350 return false;
351
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000352 TargetData *TD = getAnalysisIfAvailable<TargetData>();
353 if (!TD) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000354 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmana195b7f2009-07-28 00:37:06 +0000355 Module *M = SI->getParent()->getParent()->getParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000356
357 // Okay, so we now have a single store that can be splatable. Scan to find
358 // all subsequent stores of the same value to offset from the same pointer.
359 // Join these together into ranges, so we can decide whether contiguous blocks
360 // are stored.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000361 MemsetRanges Ranges(*TD);
Owen Andersona723d1e2008-04-09 08:23:16 +0000362
363 Value *StartPtr = SI->getPointerOperand();
364
365 BasicBlock::iterator BI = SI;
366 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
367 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
368 // If the call is readnone, ignore it, otherwise bail out. We don't even
369 // allow readonly here because we don't want something like:
370 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
371 if (AA.getModRefBehavior(CallSite::get(BI)) ==
372 AliasAnalysis::DoesNotAccessMemory)
373 continue;
374
375 // TODO: If this is a memset, try to join it in.
376
377 break;
378 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
379 break;
380
381 // If this is a non-store instruction it is fine, ignore it.
382 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
383 if (NextStore == 0) continue;
384
385 // If this is a store, see if we can merge it in.
386 if (NextStore->isVolatile()) break;
387
388 // Check to see if this stored value is of the same byte-splattable value.
Owen Andersone922c022009-07-22 00:24:57 +0000389 if (ByteVal != isBytewiseValue(NextStore->getOperand(0),
390 NextStore->getContext()))
Owen Andersona723d1e2008-04-09 08:23:16 +0000391 break;
392
393 // Check to see if this store is to a constant offset from the start ptr.
394 int64_t Offset;
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000395 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000396 break;
397
398 Ranges.addStore(Offset, NextStore);
399 }
400
401 // If we have no ranges, then we just had a single store with nothing that
402 // could be merged in. This is a very common case of course.
403 if (Ranges.empty())
404 return false;
405
406 // If we had at least one store that could be merged in, add the starting
407 // store as well. We try to avoid this unless there is at least something
408 // interesting as a small compile-time optimization.
409 Ranges.addStore(0, SI);
410
411
412 Function *MemSetF = 0;
413
414 // Now that we have full information about ranges, loop over the ranges and
415 // emit memset's for anything big enough to be worthwhile.
416 bool MadeChange = false;
417 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
418 I != E; ++I) {
419 const MemsetRange &Range = *I;
420
421 if (Range.TheStores.size() == 1) continue;
422
423 // If it is profitable to lower this range to memset, do so now.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000424 if (!Range.isProfitableToUseMemset(*TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000425 continue;
426
427 // Otherwise, we do want to transform this! Create a new memset. We put
428 // the memset right before the first instruction that isn't part of this
429 // memset block. This ensure that the memset is dominated by any addressing
430 // instruction needed by the start of the block.
431 BasicBlock::iterator InsertPt = BI;
432
Chris Lattner824b9582008-11-21 16:42:48 +0000433 if (MemSetF == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000434 const Type *Tys[] = {Type::getInt64Ty(SI->getContext())};
Dan Gohmana195b7f2009-07-28 00:37:06 +0000435 MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset,
Chris Lattner824b9582008-11-21 16:42:48 +0000436 Tys, 1);
437 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000438
439 // Get the starting pointer of the block.
440 StartPtr = Range.StartPtr;
441
442 // Cast the start ptr to be i8* as memset requires.
Owen Anderson1d0be152009-08-13 21:58:54 +0000443 const Type *i8Ptr =
444 PointerType::getUnqual(Type::getInt8Ty(SI->getContext()));
Owen Andersona723d1e2008-04-09 08:23:16 +0000445 if (StartPtr->getType() != i8Ptr)
Daniel Dunbar460f6562009-07-26 09:48:23 +0000446 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000447 InsertPt);
448
449 Value *Ops[] = {
450 StartPtr, ByteVal, // Start, value
Owen Andersone922c022009-07-22 00:24:57 +0000451 // size
Owen Anderson1d0be152009-08-13 21:58:54 +0000452 ConstantInt::get(Type::getInt64Ty(SI->getContext()),
453 Range.End-Range.Start),
Owen Andersone922c022009-07-22 00:24:57 +0000454 // align
Owen Anderson1d0be152009-08-13 21:58:54 +0000455 ConstantInt::get(Type::getInt32Ty(SI->getContext()), Range.Alignment)
Owen Andersona723d1e2008-04-09 08:23:16 +0000456 };
457 Value *C = CallInst::Create(MemSetF, Ops, Ops+4, "", InsertPt);
Chris Lattnerbdff5482009-08-23 04:37:46 +0000458 DEBUG(errs() << "Replace stores:\n";
Owen Andersona723d1e2008-04-09 08:23:16 +0000459 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
Chris Lattnerbdff5482009-08-23 04:37:46 +0000460 errs() << *Range.TheStores[i];
461 errs() << "With: " << *C); C=C;
Owen Andersona723d1e2008-04-09 08:23:16 +0000462
Owen Andersona8bd6582008-04-21 07:45:10 +0000463 // Don't invalidate the iterator
464 BBI = BI;
465
Owen Andersona723d1e2008-04-09 08:23:16 +0000466 // Zap all the stores.
Owen Andersona8bd6582008-04-21 07:45:10 +0000467 for (SmallVector<StoreInst*, 16>::const_iterator SI = Range.TheStores.begin(),
468 SE = Range.TheStores.end(); SI != SE; ++SI)
469 (*SI)->eraseFromParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000470 ++NumMemSetInfer;
471 MadeChange = true;
472 }
473
474 return MadeChange;
475}
476
477
478/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
479/// and checks for the possibility of a call slot optimization by having
480/// the call write its result directly into the destination of the memcpy.
Owen Andersona8bd6582008-04-21 07:45:10 +0000481bool MemCpyOpt::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000482 // The general transformation to keep in mind is
483 //
484 // call @func(..., src, ...)
485 // memcpy(dest, src, ...)
486 //
487 // ->
488 //
489 // memcpy(dest, src, ...)
490 // call @func(..., dest, ...)
491 //
492 // Since moving the memcpy is technically awkward, we additionally check that
493 // src only holds uninitialized values at the moment of the call, meaning that
494 // the memcpy can be discarded rather than moved.
495
496 // Deliberately get the source and destination with bitcasts stripped away,
497 // because we'll need to do type comparisons based on the underlying type.
498 Value* cpyDest = cpy->getDest();
499 Value* cpySrc = cpy->getSource();
500 CallSite CS = CallSite::get(C);
501
502 // We need to be able to reason about the size of the memcpy, so we require
503 // that it be a constant.
504 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
505 if (!cpyLength)
506 return false;
507
508 // Require that src be an alloca. This simplifies the reasoning considerably.
509 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
510 if (!srcAlloca)
511 return false;
512
513 // Check that all of src is copied to dest.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000514 TargetData* TD = getAnalysisIfAvailable<TargetData>();
515 if (!TD) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000516
517 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
518 if (!srcArraySize)
519 return false;
520
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000521 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000522 srcArraySize->getZExtValue();
523
524 if (cpyLength->getZExtValue() < srcSize)
525 return false;
526
527 // Check that accessing the first srcSize bytes of dest will not cause a
528 // trap. Otherwise the transform is invalid since it might cause a trap
529 // to occur earlier than it otherwise would.
530 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
531 // The destination is an alloca. Check it is larger than srcSize.
532 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
533 if (!destArraySize)
534 return false;
535
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000536 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000537 destArraySize->getZExtValue();
538
539 if (destSize < srcSize)
540 return false;
541 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
542 // If the destination is an sret parameter then only accesses that are
543 // outside of the returned struct type can trap.
544 if (!A->hasStructRetAttr())
545 return false;
546
547 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000548 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000549
550 if (destSize < srcSize)
551 return false;
552 } else {
553 return false;
554 }
555
556 // Check that src is not accessed except via the call and the memcpy. This
557 // guarantees that it holds only undefined values when passed in (so the final
558 // memcpy can be dropped), that it is not read or written between the call and
559 // the memcpy, and that writing beyond the end of it is undefined.
560 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
561 srcAlloca->use_end());
562 while (!srcUseList.empty()) {
563 User* UI = srcUseList.back();
564 srcUseList.pop_back();
565
Owen Anderson009e4f72008-06-01 22:26:26 +0000566 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000567 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
568 I != E; ++I)
569 srcUseList.push_back(*I);
Owen Anderson009e4f72008-06-01 22:26:26 +0000570 } else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(UI)) {
571 if (G->hasAllZeroIndices())
572 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
573 I != E; ++I)
574 srcUseList.push_back(*I);
575 else
576 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000577 } else if (UI != C && UI != cpy) {
578 return false;
579 }
580 }
581
582 // Since we're changing the parameter to the callsite, we need to make sure
583 // that what would be the new parameter dominates the callsite.
584 DominatorTree& DT = getAnalysis<DominatorTree>();
585 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
586 if (!DT.dominates(cpyDestInst, C))
587 return false;
588
589 // In addition to knowing that the call does not access src in some
590 // unexpected manner, for example via a global, which we deduce from
591 // the use analysis, we also need to know that it does not sneakily
592 // access dest. We rely on AA to figure this out for us.
593 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
594 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
595 AliasAnalysis::NoModRef)
596 return false;
597
598 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000599 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000600 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000601 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000602 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000603 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000604 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000605 changedArgument = true;
Owen Anderson009e4f72008-06-01 22:26:26 +0000606 if (CS.getArgument(i)->getType() != cpyDest->getType())
607 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
608 CS.getArgument(i)->getType(), cpyDest->getName(), C));
609 else
610 CS.setArgument(i, cpyDest);
Owen Andersona723d1e2008-04-09 08:23:16 +0000611 }
612
Owen Anderson12cb36c2008-06-01 21:52:16 +0000613 if (!changedArgument)
614 return false;
615
Owen Andersona723d1e2008-04-09 08:23:16 +0000616 // Drop any cached information about the call, because we may have changed
617 // its dependence information by changing its parameter.
618 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000619 MD.removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000620
621 // Remove the memcpy
622 MD.removeInstruction(cpy);
Owen Andersona8bd6582008-04-21 07:45:10 +0000623 cpy->eraseFromParent();
624 NumMemCpyInstr++;
Owen Andersona723d1e2008-04-09 08:23:16 +0000625
626 return true;
627}
628
629/// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
630/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
631/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
632/// This allows later passes to remove the first memcpy altogether.
Owen Andersona8bd6582008-04-21 07:45:10 +0000633bool MemCpyOpt::processMemCpy(MemCpyInst* M) {
634 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
635
636 // The are two possible optimizations we can do for memcpy:
637 // a) memcpy-memcpy xform which exposes redundance for DSE
638 // b) call-memcpy xform for return slot optimization
Chris Lattner4c724002008-11-29 02:29:27 +0000639 MemDepResult dep = MD.getDependency(M);
Chris Lattnerb51deb92008-12-05 21:04:20 +0000640 if (!dep.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000641 return false;
Chris Lattnerb51deb92008-12-05 21:04:20 +0000642 if (!isa<MemCpyInst>(dep.getInst())) {
Chris Lattner4c724002008-11-29 02:29:27 +0000643 if (CallInst* C = dyn_cast<CallInst>(dep.getInst()))
Owen Anderson9dcace32008-04-29 21:26:06 +0000644 return performCallSlotOptzn(M, C);
Chris Lattnerb51deb92008-12-05 21:04:20 +0000645 return false;
Owen Anderson9dcace32008-04-29 21:26:06 +0000646 }
Owen Andersona8bd6582008-04-21 07:45:10 +0000647
Chris Lattner4c724002008-11-29 02:29:27 +0000648 MemCpyInst* MDep = cast<MemCpyInst>(dep.getInst());
Owen Andersona8bd6582008-04-21 07:45:10 +0000649
Owen Andersona723d1e2008-04-09 08:23:16 +0000650 // We can only transforms memcpy's where the dest of one is the source of the
651 // other
652 if (M->getSource() != MDep->getDest())
653 return false;
654
655 // Second, the length of the memcpy's must be the same, or the preceeding one
656 // must be larger than the following one.
657 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
658 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
659 if (!C1 || !C2)
660 return false;
661
662 uint64_t DepSize = C1->getValue().getZExtValue();
663 uint64_t CpySize = C2->getValue().getZExtValue();
664
665 if (DepSize < CpySize)
666 return false;
667
668 // Finally, we have to make sure that the dest of the second does not
669 // alias the source of the first
670 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
671 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
672 AliasAnalysis::NoAlias)
673 return false;
674 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
675 AliasAnalysis::NoAlias)
676 return false;
677 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
678 != AliasAnalysis::NoAlias)
679 return false;
680
681 // If all checks passed, then we can transform these memcpy's
Chris Lattner824b9582008-11-21 16:42:48 +0000682 const Type *Tys[1];
683 Tys[0] = M->getLength()->getType();
Owen Andersona723d1e2008-04-09 08:23:16 +0000684 Function* MemCpyFun = Intrinsic::getDeclaration(
685 M->getParent()->getParent()->getParent(),
Chris Lattner824b9582008-11-21 16:42:48 +0000686 M->getIntrinsicID(), Tys, 1);
Owen Andersona723d1e2008-04-09 08:23:16 +0000687
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000688 Value *Args[4] = {
689 M->getRawDest(), MDep->getRawSource(), M->getLength(), M->getAlignmentCst()
690 };
Owen Andersona723d1e2008-04-09 08:23:16 +0000691
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000692 CallInst* C = CallInst::Create(MemCpyFun, Args, Args+4, "", M);
Owen Andersona723d1e2008-04-09 08:23:16 +0000693
Owen Anderson02e99882008-04-29 21:51:00 +0000694
695 // If C and M don't interfere, then this is a valid transformation. If they
696 // did, this would mean that the two sources overlap, which would be bad.
Chris Lattner39f372e2008-11-29 01:43:36 +0000697 if (MD.getDependency(C) == dep) {
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000698 MD.removeInstruction(M);
Owen Andersona8bd6582008-04-21 07:45:10 +0000699 M->eraseFromParent();
Owen Anderson02e99882008-04-29 21:51:00 +0000700 NumMemCpyInstr++;
Owen Andersona723d1e2008-04-09 08:23:16 +0000701 return true;
702 }
703
Owen Anderson02e99882008-04-29 21:51:00 +0000704 // Otherwise, there was no point in doing this, so we remove the call we
705 // inserted and act like nothing happened.
Owen Andersona723d1e2008-04-09 08:23:16 +0000706 MD.removeInstruction(C);
Owen Andersona8bd6582008-04-21 07:45:10 +0000707 C->eraseFromParent();
Owen Anderson02e99882008-04-29 21:51:00 +0000708 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000709}
710
711// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
712// function.
713//
714bool MemCpyOpt::runOnFunction(Function& F) {
715
716 bool changed = false;
717 bool shouldContinue = true;
718
719 while (shouldContinue) {
720 shouldContinue = iterateOnFunction(F);
721 changed |= shouldContinue;
722 }
723
724 return changed;
725}
726
727
728// MemCpyOpt::iterateOnFunction - Executes one iteration of GVN
729bool MemCpyOpt::iterateOnFunction(Function &F) {
730 bool changed_function = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000731
Owen Andersona8bd6582008-04-21 07:45:10 +0000732 // Walk all instruction in the function
733 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000734 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
735 BI != BE;) {
Owen Andersona8bd6582008-04-21 07:45:10 +0000736 // Avoid invalidating the iterator
737 Instruction* I = BI++;
738
739 if (StoreInst *SI = dyn_cast<StoreInst>(I))
740 changed_function |= processStore(SI, BI);
Torok Edwin529bd532008-05-04 08:51:25 +0000741 else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
Owen Andersona8bd6582008-04-21 07:45:10 +0000742 changed_function |= processMemCpy(M);
Owen Andersona723d1e2008-04-09 08:23:16 +0000743 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000744 }
745 }
746
747 return changed_function;
748}