blob: e4f329fdad7155a30e603d2290a0fb21882eedef [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");
Duncan Sands05cd03b2009-09-03 13:37:16 +000034STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Owen Andersona723d1e2008-04-09 08:23:16 +000035
Owen Andersona723d1e2008-04-09 08:23:16 +000036/// isBytewiseValue - If the specified value can be set by repeating the same
37/// byte in memory, return the i8 value that it is represented with. This is
38/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
39/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
40/// byte store (e.g. i16 0x1234), return null.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +000041static Value *isBytewiseValue(Value *V) {
42 LLVMContext &Context = V->getContext();
43
Owen Andersona723d1e2008-04-09 08:23:16 +000044 // All byte-wide stores are splatable, even of arbitrary variables.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000045 if (V->getType()->isIntegerTy(8)) return V;
Owen Andersona723d1e2008-04-09 08:23:16 +000046
47 // Constant float and double values can be handled as integer values if the
48 // corresponding integer value is "byteable". An important case is 0.0.
49 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +000050 if (CFP->getType()->isFloatTy())
Owen Anderson1d0be152009-08-13 21:58:54 +000051 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(Context));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +000052 if (CFP->getType()->isDoubleTy())
Owen Anderson1d0be152009-08-13 21:58:54 +000053 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(Context));
Owen Andersona723d1e2008-04-09 08:23:16 +000054 // Don't handle long double formats, which have strange constraints.
55 }
56
57 // We can handle constant integers that are power of two in size and a
58 // multiple of 8 bits.
59 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
60 unsigned Width = CI->getBitWidth();
61 if (isPowerOf2_32(Width) && Width > 8) {
62 // We can handle this value if the recursive binary decomposition is the
63 // same at all levels.
64 APInt Val = CI->getValue();
65 APInt Val2;
66 while (Val.getBitWidth() != 8) {
67 unsigned NextWidth = Val.getBitWidth()/2;
68 Val2 = Val.lshr(NextWidth);
69 Val2.trunc(Val.getBitWidth()/2);
70 Val.trunc(Val.getBitWidth()/2);
71
72 // If the top/bottom halves aren't the same, reject it.
73 if (Val != Val2)
74 return 0;
75 }
Owen Andersoneed707b2009-07-24 23:12:02 +000076 return ConstantInt::get(Context, Val);
Owen Andersona723d1e2008-04-09 08:23:16 +000077 }
78 }
79
80 // Conceptually, we could handle things like:
81 // %a = zext i8 %X to i16
82 // %b = shl i16 %a, 8
83 // %c = or i16 %a, %b
84 // but until there is an example that actually needs this, it doesn't seem
85 // worth worrying about.
86 return 0;
87}
88
89static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
90 bool &VariableIdxFound, TargetData &TD) {
91 // Skip over the first indices.
92 gep_type_iterator GTI = gep_type_begin(GEP);
93 for (unsigned i = 1; i != Idx; ++i, ++GTI)
94 /*skip along*/;
95
96 // Compute the offset implied by the rest of the indices.
97 int64_t Offset = 0;
98 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
99 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
100 if (OpC == 0)
101 return VariableIdxFound = true;
102 if (OpC->isZero()) continue; // No offset.
103
104 // Handle struct indices, which add their field offset to the pointer.
105 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
106 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
107 continue;
108 }
109
110 // Otherwise, we have a sequential type like an array or vector. Multiply
111 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +0000112 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +0000113 Offset += Size*OpC->getSExtValue();
114 }
115
116 return Offset;
117}
118
119/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
120/// constant offset, and return that constant offset. For example, Ptr1 might
121/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
122static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
123 TargetData &TD) {
124 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
125 // base. After that base, they may have some number of common (and
126 // potentially variable) indices. After that they handle some constant
127 // offset, which determines their offset from each other. At this point, we
128 // handle no other case.
129 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
130 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
131 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
132 return false;
133
134 // Skip any common indices and track the GEP types.
135 unsigned Idx = 1;
136 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
137 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
138 break;
139
140 bool VariableIdxFound = false;
141 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
142 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
143 if (VariableIdxFound) return false;
144
145 Offset = Offset2-Offset1;
146 return true;
147}
148
149
150/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
151/// This allows us to analyze stores like:
152/// store 0 -> P+1
153/// store 0 -> P+0
154/// store 0 -> P+3
155/// store 0 -> P+2
156/// which sometimes happens with stores to arrays of structs etc. When we see
157/// the first store, we make a range [1, 2). The second store extends the range
158/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
159/// two ranges into [0, 3) which is memset'able.
160namespace {
161struct MemsetRange {
162 // Start/End - A semi range that describes the span that this range covers.
163 // The range is closed at the start and open at the end: [Start, End).
164 int64_t Start, End;
165
166 /// StartPtr - The getelementptr instruction that points to the start of the
167 /// range.
168 Value *StartPtr;
169
170 /// Alignment - The known alignment of the first store.
171 unsigned Alignment;
172
173 /// TheStores - The actual stores that make up this range.
174 SmallVector<StoreInst*, 16> TheStores;
175
176 bool isProfitableToUseMemset(const TargetData &TD) const;
177
178};
179} // end anon namespace
180
181bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
182 // If we found more than 8 stores to merge or 64 bytes, use memset.
183 if (TheStores.size() >= 8 || End-Start >= 64) return true;
184
185 // Assume that the code generator is capable of merging pairs of stores
186 // together if it wants to.
187 if (TheStores.size() <= 2) return false;
188
189 // If we have fewer than 8 stores, it can still be worthwhile to do this.
190 // For example, merging 4 i8 stores into an i32 store is useful almost always.
191 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
192 // memset will be split into 2 32-bit stores anyway) and doing so can
193 // pessimize the llvm optimizer.
194 //
195 // Since we don't have perfect knowledge here, make some assumptions: assume
196 // the maximum GPR width is the same size as the pointer size and assume that
197 // this width can be stored. If so, check to see whether we will end up
198 // actually reducing the number of stores used.
199 unsigned Bytes = unsigned(End-Start);
200 unsigned NumPointerStores = Bytes/TD.getPointerSize();
201
202 // Assume the remaining bytes if any are done a byte at a time.
203 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
204
205 // If we will reduce the # stores (according to this heuristic), do the
206 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
207 // etc.
208 return TheStores.size() > NumPointerStores+NumByteStores;
209}
210
211
212namespace {
213class MemsetRanges {
214 /// Ranges - A sorted list of the memset ranges. We use std::list here
215 /// because each element is relatively large and expensive to copy.
216 std::list<MemsetRange> Ranges;
217 typedef std::list<MemsetRange>::iterator range_iterator;
218 TargetData &TD;
219public:
220 MemsetRanges(TargetData &td) : TD(td) {}
221
222 typedef std::list<MemsetRange>::const_iterator const_iterator;
223 const_iterator begin() const { return Ranges.begin(); }
224 const_iterator end() const { return Ranges.end(); }
225 bool empty() const { return Ranges.empty(); }
226
227 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
228};
229
230} // end anon namespace
231
232
233/// addStore - Add a new store to the MemsetRanges data structure. This adds a
234/// new range for the specified store at the specified offset, merging into
235/// existing ranges as appropriate.
236void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
237 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
238
239 // Do a linear search of the ranges to see if this can be joined and/or to
240 // find the insertion point in the list. We keep the ranges sorted for
241 // simplicity here. This is a linear search of a linked list, which is ugly,
242 // however the number of ranges is limited, so this won't get crazy slow.
243 range_iterator I = Ranges.begin(), E = Ranges.end();
244
245 while (I != E && Start > I->End)
246 ++I;
247
248 // We now know that I == E, in which case we didn't find anything to merge
249 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
250 // to insert a new range. Handle this now.
251 if (I == E || End < I->Start) {
252 MemsetRange &R = *Ranges.insert(I, MemsetRange());
253 R.Start = Start;
254 R.End = End;
255 R.StartPtr = SI->getPointerOperand();
256 R.Alignment = SI->getAlignment();
257 R.TheStores.push_back(SI);
258 return;
259 }
260
261 // This store overlaps with I, add it.
262 I->TheStores.push_back(SI);
263
264 // At this point, we may have an interval that completely contains our store.
265 // If so, just add it to the interval and return.
266 if (I->Start <= Start && I->End >= End)
267 return;
268
269 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
270 // but is not entirely contained within the range.
271
272 // See if the range extends the start of the range. In this case, it couldn't
273 // possibly cause it to join the prior range, because otherwise we would have
274 // stopped on *it*.
275 if (Start < I->Start) {
276 I->Start = Start;
277 I->StartPtr = SI->getPointerOperand();
Dan Gohman264d2452009-09-14 23:39:10 +0000278 I->Alignment = SI->getAlignment();
Owen Andersona723d1e2008-04-09 08:23:16 +0000279 }
280
281 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
282 // is in or right at the end of I), and that End >= I->Start. Extend I out to
283 // End.
284 if (End > I->End) {
285 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000286 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000287 while (++NextI != E && End >= NextI->Start) {
288 // Merge the range in.
289 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
290 if (NextI->End > I->End)
291 I->End = NextI->End;
292 Ranges.erase(NextI);
293 NextI = I;
294 }
295 }
296}
297
298//===----------------------------------------------------------------------===//
299// MemCpyOpt Pass
300//===----------------------------------------------------------------------===//
301
302namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000303 class MemCpyOpt : public FunctionPass {
Owen Andersona723d1e2008-04-09 08:23:16 +0000304 bool runOnFunction(Function &F);
305 public:
306 static char ID; // Pass identification, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +0000307 MemCpyOpt() : FunctionPass(ID) {}
Owen Andersona723d1e2008-04-09 08:23:16 +0000308
309 private:
310 // This transformation requires dominator postdominator info
311 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
312 AU.setPreservesCFG();
313 AU.addRequired<DominatorTree>();
314 AU.addRequired<MemoryDependenceAnalysis>();
315 AU.addRequired<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000316 AU.addPreserved<AliasAnalysis>();
317 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000318 }
319
320 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000321 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
322 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000323 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000324 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
325 uint64_t cpyLen, CallInst *C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000326 bool iterateOnFunction(Function &F);
327 };
328
329 char MemCpyOpt::ID = 0;
330}
331
332// createMemCpyOptPass - The public interface to this file...
333FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
334
Owen Anderson2ab36d32010-10-12 19:48:12 +0000335INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
336 false, false)
337INITIALIZE_PASS_DEPENDENCY(DominatorTree)
338INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
339INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
340INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
341 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000342
Owen Andersona723d1e2008-04-09 08:23:16 +0000343/// processStore - When GVN is scanning forward over instructions, we look for
344/// some other patterns to fold away. In particular, this looks for stores to
345/// neighboring locations of memory. If it sees enough consequtive ones
346/// (currently 4) it attempts to merge them together into a memcpy/memset.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000347bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000348 if (SI->isVolatile()) return false;
349
Owen Anderson65491212010-10-15 22:52:12 +0000350 TargetData *TD = getAnalysisIfAvailable<TargetData>();
351 if (!TD) return false;
352
353 // Detect cases where we're performing call slot forwarding, but
354 // happen to be using a load-store pair to implement it, rather than
355 // a memcpy.
356 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
357 if (!LI->isVolatile() && LI->hasOneUse()) {
358 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
359
360 MemDepResult dep = MD.getDependency(LI);
361 CallInst *C = 0;
362 if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst()))
363 C = dyn_cast<CallInst>(dep.getInst());
364
365 if (C) {
366 bool changed = performCallSlotOptzn(LI,
367 SI->getPointerOperand()->stripPointerCasts(),
368 LI->getPointerOperand()->stripPointerCasts(),
369 TD->getTypeStoreSize(SI->getOperand(0)->getType()), C);
370 if (changed) {
371 MD.removeInstruction(SI);
372 SI->eraseFromParent();
373 LI->eraseFromParent();
374 ++NumMemCpyInstr;
375 return true;
376 }
377 }
378 }
379 }
380
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000381 LLVMContext &Context = SI->getContext();
382
Owen Andersona723d1e2008-04-09 08:23:16 +0000383 // There are two cases that are interesting for this code to handle: memcpy
384 // and memset. Right now we only handle memset.
385
386 // Ensure that the value being stored is something that can be memset'able a
387 // byte at a time like "0" or "-1" or any width, as well as things like
388 // 0xA0A0A0A0 and 0.0.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000389 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
Owen Andersona723d1e2008-04-09 08:23:16 +0000390 if (!ByteVal)
391 return false;
392
Owen Andersona723d1e2008-04-09 08:23:16 +0000393 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmana195b7f2009-07-28 00:37:06 +0000394 Module *M = SI->getParent()->getParent()->getParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000395
396 // Okay, so we now have a single store that can be splatable. Scan to find
397 // all subsequent stores of the same value to offset from the same pointer.
398 // Join these together into ranges, so we can decide whether contiguous blocks
399 // are stored.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000400 MemsetRanges Ranges(*TD);
Owen Andersona723d1e2008-04-09 08:23:16 +0000401
402 Value *StartPtr = SI->getPointerOperand();
403
404 BasicBlock::iterator BI = SI;
405 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
406 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
407 // If the call is readnone, ignore it, otherwise bail out. We don't even
408 // allow readonly here because we don't want something like:
409 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Gabor Greifa292b2f2010-07-27 16:44:23 +0000410 if (AA.getModRefBehavior(CallSite(BI)) ==
Owen Andersona723d1e2008-04-09 08:23:16 +0000411 AliasAnalysis::DoesNotAccessMemory)
412 continue;
413
414 // TODO: If this is a memset, try to join it in.
415
416 break;
417 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
418 break;
419
420 // If this is a non-store instruction it is fine, ignore it.
421 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
422 if (NextStore == 0) continue;
423
424 // If this is a store, see if we can merge it in.
425 if (NextStore->isVolatile()) break;
426
427 // Check to see if this stored value is of the same byte-splattable value.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000428 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
Owen Andersona723d1e2008-04-09 08:23:16 +0000429 break;
430
431 // Check to see if this store is to a constant offset from the start ptr.
432 int64_t Offset;
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000433 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000434 break;
435
436 Ranges.addStore(Offset, NextStore);
437 }
438
439 // If we have no ranges, then we just had a single store with nothing that
440 // could be merged in. This is a very common case of course.
441 if (Ranges.empty())
442 return false;
443
444 // If we had at least one store that could be merged in, add the starting
445 // store as well. We try to avoid this unless there is at least something
446 // interesting as a small compile-time optimization.
447 Ranges.addStore(0, SI);
Owen Andersona723d1e2008-04-09 08:23:16 +0000448
Owen Andersona723d1e2008-04-09 08:23:16 +0000449
450 // Now that we have full information about ranges, loop over the ranges and
451 // emit memset's for anything big enough to be worthwhile.
452 bool MadeChange = false;
453 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
454 I != E; ++I) {
455 const MemsetRange &Range = *I;
456
457 if (Range.TheStores.size() == 1) continue;
458
459 // If it is profitable to lower this range to memset, do so now.
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000460 if (!Range.isProfitableToUseMemset(*TD))
Owen Andersona723d1e2008-04-09 08:23:16 +0000461 continue;
462
463 // Otherwise, we do want to transform this! Create a new memset. We put
464 // the memset right before the first instruction that isn't part of this
465 // memset block. This ensure that the memset is dominated by any addressing
466 // instruction needed by the start of the block.
467 BasicBlock::iterator InsertPt = BI;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000468
Owen Andersona723d1e2008-04-09 08:23:16 +0000469 // Get the starting pointer of the block.
470 StartPtr = Range.StartPtr;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000471
472 // Determine alignment
473 unsigned Alignment = Range.Alignment;
474 if (Alignment == 0) {
475 const Type *EltType =
476 cast<PointerType>(StartPtr->getType())->getElementType();
477 Alignment = TD->getABITypeAlignment(EltType);
478 }
479
Owen Andersona723d1e2008-04-09 08:23:16 +0000480 // Cast the start ptr to be i8* as memset requires.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000481 const PointerType* StartPTy = cast<PointerType>(StartPtr->getType());
482 const PointerType *i8Ptr = Type::getInt8PtrTy(Context,
483 StartPTy->getAddressSpace());
484 if (StartPTy!= i8Ptr)
Daniel Dunbar460f6562009-07-26 09:48:23 +0000485 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getName(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000486 InsertPt);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000487
Owen Andersona723d1e2008-04-09 08:23:16 +0000488 Value *Ops[] = {
489 StartPtr, ByteVal, // Start, value
Owen Andersone922c022009-07-22 00:24:57 +0000490 // size
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000491 ConstantInt::get(Type::getInt64Ty(Context), Range.End-Range.Start),
Owen Andersone922c022009-07-22 00:24:57 +0000492 // align
Mon P Wang20adc9d2010-04-04 03:10:48 +0000493 ConstantInt::get(Type::getInt32Ty(Context), Alignment),
494 // volatile
495 ConstantInt::get(Type::getInt1Ty(Context), 0),
Owen Andersona723d1e2008-04-09 08:23:16 +0000496 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000497 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
498
499 Function *MemSetF = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
500
501 Value *C = CallInst::Create(MemSetF, Ops, Ops+5, "", InsertPt);
David Greenecb33fd12010-01-05 01:27:47 +0000502 DEBUG(dbgs() << "Replace stores:\n";
Owen Andersona723d1e2008-04-09 08:23:16 +0000503 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
David Greenecb33fd12010-01-05 01:27:47 +0000504 dbgs() << *Range.TheStores[i];
505 dbgs() << "With: " << *C); C=C;
Owen Andersona723d1e2008-04-09 08:23:16 +0000506
Owen Andersona8bd6582008-04-21 07:45:10 +0000507 // Don't invalidate the iterator
508 BBI = BI;
509
Owen Andersona723d1e2008-04-09 08:23:16 +0000510 // Zap all the stores.
Chris Lattnerff1e98c2009-09-08 00:27:14 +0000511 for (SmallVector<StoreInst*, 16>::const_iterator
512 SI = Range.TheStores.begin(),
Owen Andersona8bd6582008-04-21 07:45:10 +0000513 SE = Range.TheStores.end(); SI != SE; ++SI)
514 (*SI)->eraseFromParent();
Owen Andersona723d1e2008-04-09 08:23:16 +0000515 ++NumMemSetInfer;
516 MadeChange = true;
517 }
518
519 return MadeChange;
520}
521
522
523/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
524/// and checks for the possibility of a call slot optimization by having
525/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000526bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
527 Value *cpyDest, Value *cpySrc,
528 uint64_t cpyLen, CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000529 // The general transformation to keep in mind is
530 //
531 // call @func(..., src, ...)
532 // memcpy(dest, src, ...)
533 //
534 // ->
535 //
536 // memcpy(dest, src, ...)
537 // call @func(..., dest, ...)
538 //
539 // Since moving the memcpy is technically awkward, we additionally check that
540 // src only holds uninitialized values at the moment of the call, meaning that
541 // the memcpy can be discarded rather than moved.
542
543 // Deliberately get the source and destination with bitcasts stripped away,
544 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000545 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000546
Owen Andersona723d1e2008-04-09 08:23:16 +0000547 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000548 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000549 if (!srcAlloca)
550 return false;
551
552 // Check that all of src is copied to dest.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000553 TargetData *TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000554 if (!TD) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000555
Chris Lattner61c6ba82009-09-01 17:09:55 +0000556 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000557 if (!srcArraySize)
558 return false;
559
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000560 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000561 srcArraySize->getZExtValue();
562
Owen Anderson65491212010-10-15 22:52:12 +0000563 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000564 return false;
565
566 // Check that accessing the first srcSize bytes of dest will not cause a
567 // trap. Otherwise the transform is invalid since it might cause a trap
568 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000569 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000570 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000571 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000572 if (!destArraySize)
573 return false;
574
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000575 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000576 destArraySize->getZExtValue();
577
578 if (destSize < srcSize)
579 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000580 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000581 // If the destination is an sret parameter then only accesses that are
582 // outside of the returned struct type can trap.
583 if (!A->hasStructRetAttr())
584 return false;
585
Chris Lattner61c6ba82009-09-01 17:09:55 +0000586 const Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000587 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000588
589 if (destSize < srcSize)
590 return false;
591 } else {
592 return false;
593 }
594
595 // Check that src is not accessed except via the call and the memcpy. This
596 // guarantees that it holds only undefined values when passed in (so the final
597 // memcpy can be dropped), that it is not read or written between the call and
598 // the memcpy, and that writing beyond the end of it is undefined.
599 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
600 srcAlloca->use_end());
601 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000602 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000603
Owen Anderson009e4f72008-06-01 22:26:26 +0000604 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000605 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
606 I != E; ++I)
607 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000608 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000609 if (G->hasAllZeroIndices())
610 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
611 I != E; ++I)
612 srcUseList.push_back(*I);
613 else
614 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000615 } else if (UI != C && UI != cpy) {
616 return false;
617 }
618 }
619
620 // Since we're changing the parameter to the callsite, we need to make sure
621 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000622 DominatorTree &DT = getAnalysis<DominatorTree>();
623 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000624 if (!DT.dominates(cpyDestInst, C))
625 return false;
626
627 // In addition to knowing that the call does not access src in some
628 // unexpected manner, for example via a global, which we deduce from
629 // the use analysis, we also need to know that it does not sneakily
630 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000631 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson65491212010-10-15 22:52:12 +0000632 if (AA.getModRefInfo(C, cpyDest, srcSize) !=
Owen Andersona723d1e2008-04-09 08:23:16 +0000633 AliasAnalysis::NoModRef)
634 return false;
635
636 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000637 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000638 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000639 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000640 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000641 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000642 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000643 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000644 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000645 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000646 else
647 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
648 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000649 }
650
Owen Anderson12cb36c2008-06-01 21:52:16 +0000651 if (!changedArgument)
652 return false;
653
Owen Andersona723d1e2008-04-09 08:23:16 +0000654 // Drop any cached information about the call, because we may have changed
655 // its dependence information by changing its parameter.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000656 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000657 MD.removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000658
659 // Remove the memcpy
660 MD.removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000661 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000662
663 return true;
664}
665
Gabor Greif7d3056b2010-07-28 22:50:26 +0000666/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
667/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
668/// B to be a memcpy from X to Z (or potentially a memmove, depending on
669/// circumstances). This allows later passes to remove the first memcpy
670/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000671bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
672 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersona8bd6582008-04-21 07:45:10 +0000673
Owen Anderson65491212010-10-15 22:52:12 +0000674 // We can only optimize statically-sized memcpy's.
675 ConstantInt *cpyLen = dyn_cast<ConstantInt>(M->getLength());
676 if (!cpyLen) return false;
677
Owen Andersona8bd6582008-04-21 07:45:10 +0000678 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000679 // a) memcpy-memcpy xform which exposes redundance for DSE.
680 // b) call-memcpy xform for return slot optimization.
Chris Lattner4c724002008-11-29 02:29:27 +0000681 MemDepResult dep = MD.getDependency(M);
Chris Lattnerb51deb92008-12-05 21:04:20 +0000682 if (!dep.isClobber())
Owen Andersona8bd6582008-04-21 07:45:10 +0000683 return false;
Chris Lattnerb51deb92008-12-05 21:04:20 +0000684 if (!isa<MemCpyInst>(dep.getInst())) {
Owen Anderson65491212010-10-15 22:52:12 +0000685 if (CallInst *C = dyn_cast<CallInst>(dep.getInst())) {
686 bool changed = performCallSlotOptzn(M, M->getDest(), M->getSource(),
687 cpyLen->getZExtValue(), C);
688 if (changed) M->eraseFromParent();
689 return changed;
690 }
Chris Lattnerb51deb92008-12-05 21:04:20 +0000691 return false;
Owen Anderson9dcace32008-04-29 21:26:06 +0000692 }
Owen Andersona8bd6582008-04-21 07:45:10 +0000693
Chris Lattner61c6ba82009-09-01 17:09:55 +0000694 MemCpyInst *MDep = cast<MemCpyInst>(dep.getInst());
Owen Andersona8bd6582008-04-21 07:45:10 +0000695
Owen Andersona723d1e2008-04-09 08:23:16 +0000696 // We can only transforms memcpy's where the dest of one is the source of the
697 // other
698 if (M->getSource() != MDep->getDest())
699 return false;
700
701 // Second, the length of the memcpy's must be the same, or the preceeding one
702 // must be larger than the following one.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000703 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
704 ConstantInt *C2 = dyn_cast<ConstantInt>(M->getLength());
Owen Andersona723d1e2008-04-09 08:23:16 +0000705 if (!C1 || !C2)
706 return false;
707
708 uint64_t DepSize = C1->getValue().getZExtValue();
709 uint64_t CpySize = C2->getValue().getZExtValue();
710
711 if (DepSize < CpySize)
712 return false;
713
714 // Finally, we have to make sure that the dest of the second does not
715 // alias the source of the first
Chris Lattner61c6ba82009-09-01 17:09:55 +0000716 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000717 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
718 AliasAnalysis::NoAlias)
719 return false;
720 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
721 AliasAnalysis::NoAlias)
722 return false;
723 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
724 != AliasAnalysis::NoAlias)
725 return false;
726
727 // If all checks passed, then we can transform these memcpy's
Mon P Wang20adc9d2010-04-04 03:10:48 +0000728 const Type *ArgTys[3] = { M->getRawDest()->getType(),
729 MDep->getRawSource()->getType(),
730 M->getLength()->getType() };
Chris Lattner61c6ba82009-09-01 17:09:55 +0000731 Function *MemCpyFun = Intrinsic::getDeclaration(
Owen Andersona723d1e2008-04-09 08:23:16 +0000732 M->getParent()->getParent()->getParent(),
Mon P Wang20adc9d2010-04-04 03:10:48 +0000733 M->getIntrinsicID(), ArgTys, 3);
Owen Andersona723d1e2008-04-09 08:23:16 +0000734
Eric Christopher04fcbf92010-10-01 09:02:05 +0000735 // Make sure to use the lesser of the alignment of the source and the dest
736 // since we're changing where we're reading from, but don't want to increase
737 // the alignment past what can be read from or written to.
Eric Christopherc69a0002010-09-25 00:57:26 +0000738 // TODO: Is this worth it if we're creating a less aligned memcpy? For
739 // example we could be moving from movaps -> movq on x86.
Eric Christopher04fcbf92010-10-01 09:02:05 +0000740 unsigned Align = std::min(MDep->getAlignmentCst()->getZExtValue(),
741 M->getAlignmentCst()->getZExtValue());
742 LLVMContext &Context = M->getContext();
743 ConstantInt *AlignCI = ConstantInt::get(Type::getInt32Ty(Context), Align);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000744 Value *Args[5] = {
745 M->getRawDest(), MDep->getRawSource(), M->getLength(),
Eric Christopher04fcbf92010-10-01 09:02:05 +0000746 AlignCI, M->getVolatileCst()
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000747 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000748 CallInst *C = CallInst::Create(MemCpyFun, Args, Args+5, "", M);
Owen Andersona723d1e2008-04-09 08:23:16 +0000749
Owen Anderson02e99882008-04-29 21:51:00 +0000750 // If C and M don't interfere, then this is a valid transformation. If they
751 // did, this would mean that the two sources overlap, which would be bad.
Chris Lattner39f372e2008-11-29 01:43:36 +0000752 if (MD.getDependency(C) == dep) {
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000753 MD.removeInstruction(M);
Owen Andersona8bd6582008-04-21 07:45:10 +0000754 M->eraseFromParent();
Dan Gohmanfe601042010-06-22 15:08:57 +0000755 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000756 return true;
757 }
758
Owen Anderson02e99882008-04-29 21:51:00 +0000759 // Otherwise, there was no point in doing this, so we remove the call we
760 // inserted and act like nothing happened.
Owen Andersona723d1e2008-04-09 08:23:16 +0000761 MD.removeInstruction(C);
Owen Andersona8bd6582008-04-21 07:45:10 +0000762 C->eraseFromParent();
Owen Anderson02e99882008-04-29 21:51:00 +0000763 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000764}
765
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000766/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
767/// are guaranteed not to alias.
768bool MemCpyOpt::processMemMove(MemMoveInst *M) {
769 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
770
771 // If the memmove is a constant size, use it for the alias query, this allows
772 // us to optimize things like: memmove(P, P+64, 64);
773 uint64_t MemMoveSize = ~0ULL;
774 if (ConstantInt *Len = dyn_cast<ConstantInt>(M->getLength()))
775 MemMoveSize = Len->getZExtValue();
776
777 // See if the pointers alias.
778 if (AA.alias(M->getRawDest(), MemMoveSize, M->getRawSource(), MemMoveSize) !=
779 AliasAnalysis::NoAlias)
780 return false;
781
David Greenecb33fd12010-01-05 01:27:47 +0000782 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000783
784 // If not, then we know we can transform this.
785 Module *Mod = M->getParent()->getParent()->getParent();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000786 const Type *ArgTys[3] = { M->getRawDest()->getType(),
787 M->getRawSource()->getType(),
788 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000789 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
790 ArgTys, 3));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000791
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000792 // MemDep may have over conservative information about this instruction, just
793 // conservatively flush it from the cache.
794 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000795
796 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000797 return true;
798}
799
800
Chris Lattner61c6ba82009-09-01 17:09:55 +0000801// MemCpyOpt::iterateOnFunction - Executes one iteration of GVN.
Owen Andersona723d1e2008-04-09 08:23:16 +0000802bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000803 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000804
Chris Lattner61c6ba82009-09-01 17:09:55 +0000805 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000806 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000807 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
808 BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000809 // Avoid invalidating the iterator.
810 Instruction *I = BI++;
Owen Andersona8bd6582008-04-21 07:45:10 +0000811
812 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000813 MadeChange |= processStore(SI, BI);
814 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
815 MadeChange |= processMemCpy(M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000816 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) {
817 if (processMemMove(M)) {
818 --BI; // Reprocess the new memcpy.
819 MadeChange = true;
820 }
821 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000822 }
823 }
824
Chris Lattner61c6ba82009-09-01 17:09:55 +0000825 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000826}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000827
828// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
829// function.
830//
831bool MemCpyOpt::runOnFunction(Function &F) {
832 bool MadeChange = false;
833 while (1) {
834 if (!iterateOnFunction(F))
835 break;
836 MadeChange = true;
837 }
838
839 return MadeChange;
840}
841
842
843