blob: 68be3b7c77fd55f4bdac2a1d6d859a33e0e8d5f0 [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"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000018#include "llvm/IRBuilder.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000019#include "llvm/Instructions.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000020#include "llvm/IntrinsicInst.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000023#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000024#include "llvm/Analysis/Dominators.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000025#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattnerbb897102010-12-26 20:15:01 +000026#include "llvm/Analysis/ValueTracking.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/GetElementPtrTypeIterator.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"
Chris Lattner149f5282011-05-01 18:27:11 +000031#include "llvm/Target/TargetLibraryInfo.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000032#include "llvm/Transforms/Utils/Local.h"
Owen Andersona723d1e2008-04-09 08:23:16 +000033#include <list>
34using namespace llvm;
35
36STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
37STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands05cd03b2009-09-03 13:37:16 +000038STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramera1120872010-12-24 21:17:12 +000039STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersona723d1e2008-04-09 08:23:16 +000040
Benjamin Kramer39acdb02012-09-13 16:29:49 +000041static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Chris Lattner67a716a2011-01-08 20:24:01 +000042 bool &VariableIdxFound, const TargetData &TD){
Owen Andersona723d1e2008-04-09 08:23:16 +000043 // Skip over the first indices.
44 gep_type_iterator GTI = gep_type_begin(GEP);
45 for (unsigned i = 1; i != Idx; ++i, ++GTI)
46 /*skip along*/;
Nadav Rotema94d6e82012-07-24 10:51:42 +000047
Owen Andersona723d1e2008-04-09 08:23:16 +000048 // Compute the offset implied by the rest of the indices.
49 int64_t Offset = 0;
50 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
51 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
52 if (OpC == 0)
53 return VariableIdxFound = true;
54 if (OpC->isZero()) continue; // No offset.
55
56 // Handle struct indices, which add their field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000057 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +000058 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
59 continue;
60 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000061
Owen Andersona723d1e2008-04-09 08:23:16 +000062 // Otherwise, we have a sequential type like an array or vector. Multiply
63 // the index by the ElementSize.
Duncan Sands777d2302009-05-09 07:06:46 +000064 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersona723d1e2008-04-09 08:23:16 +000065 Offset += Size*OpC->getSExtValue();
66 }
67
68 return Offset;
69}
70
71/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
72/// constant offset, and return that constant offset. For example, Ptr1 might
73/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
74static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Chris Lattner67a716a2011-01-08 20:24:01 +000075 const TargetData &TD) {
Chris Lattner2d5c0cd2011-01-12 01:43:46 +000076 Ptr1 = Ptr1->stripPointerCasts();
77 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer39acdb02012-09-13 16:29:49 +000078 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
79 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotema94d6e82012-07-24 10:51:42 +000080
Chris Lattner9fa11e92011-01-08 21:07:56 +000081 bool VariableIdxFound = false;
82
83 // If one pointer is a GEP and the other isn't, then see if the GEP is a
84 // constant offset from the base, as in "P" and "gep P, 1".
85 if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
86 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
87 return !VariableIdxFound;
88 }
89
90 if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
91 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
92 return !VariableIdxFound;
93 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000094
Owen Andersona723d1e2008-04-09 08:23:16 +000095 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
96 // base. After that base, they may have some number of common (and
97 // potentially variable) indices. After that they handle some constant
98 // offset, which determines their offset from each other. At this point, we
99 // handle no other case.
Owen Andersona723d1e2008-04-09 08:23:16 +0000100 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
101 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000102
Owen Andersona723d1e2008-04-09 08:23:16 +0000103 // Skip any common indices and track the GEP types.
104 unsigned Idx = 1;
105 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
106 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
107 break;
108
Owen Andersona723d1e2008-04-09 08:23:16 +0000109 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
110 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
111 if (VariableIdxFound) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000112
Owen Andersona723d1e2008-04-09 08:23:16 +0000113 Offset = Offset2-Offset1;
114 return true;
115}
116
117
118/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
119/// This allows us to analyze stores like:
120/// store 0 -> P+1
121/// store 0 -> P+0
122/// store 0 -> P+3
123/// store 0 -> P+2
124/// which sometimes happens with stores to arrays of structs etc. When we see
125/// the first store, we make a range [1, 2). The second store extends the range
126/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
127/// two ranges into [0, 3) which is memset'able.
128namespace {
129struct MemsetRange {
130 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000131 // The range is closed at the start and open at the end: [Start, End).
Owen Andersona723d1e2008-04-09 08:23:16 +0000132 int64_t Start, End;
133
134 /// StartPtr - The getelementptr instruction that points to the start of the
135 /// range.
136 Value *StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000137
Owen Andersona723d1e2008-04-09 08:23:16 +0000138 /// Alignment - The known alignment of the first store.
139 unsigned Alignment;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000140
Owen Andersona723d1e2008-04-09 08:23:16 +0000141 /// TheStores - The actual stores that make up this range.
Chris Lattner06511262011-01-08 20:54:51 +0000142 SmallVector<Instruction*, 16> TheStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000143
Owen Andersona723d1e2008-04-09 08:23:16 +0000144 bool isProfitableToUseMemset(const TargetData &TD) const;
145
146};
147} // end anon namespace
148
149bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
Chad Rosiera4b6fd52011-12-05 22:53:09 +0000150 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosierd8bd26e2011-12-05 22:37:00 +0000151 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner06511262011-01-08 20:54:51 +0000152
153 // If there is nothing to merge, don't do anything.
154 if (TheStores.size() < 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000155
Chris Lattner06511262011-01-08 20:54:51 +0000156 // If any of the stores are a memset, then it is always good to extend the
157 // memset.
158 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
159 if (!isa<StoreInst>(TheStores[i]))
160 return true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000161
Owen Andersona723d1e2008-04-09 08:23:16 +0000162 // Assume that the code generator is capable of merging pairs of stores
163 // together if it wants to.
Chris Lattner06511262011-01-08 20:54:51 +0000164 if (TheStores.size() == 2) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000165
Owen Andersona723d1e2008-04-09 08:23:16 +0000166 // If we have fewer than 8 stores, it can still be worthwhile to do this.
167 // For example, merging 4 i8 stores into an i32 store is useful almost always.
168 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
169 // memset will be split into 2 32-bit stores anyway) and doing so can
170 // pessimize the llvm optimizer.
171 //
172 // Since we don't have perfect knowledge here, make some assumptions: assume
173 // the maximum GPR width is the same size as the pointer size and assume that
174 // this width can be stored. If so, check to see whether we will end up
175 // actually reducing the number of stores used.
176 unsigned Bytes = unsigned(End-Start);
177 unsigned NumPointerStores = Bytes/TD.getPointerSize();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000178
Owen Andersona723d1e2008-04-09 08:23:16 +0000179 // Assume the remaining bytes if any are done a byte at a time.
180 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000181
Owen Andersona723d1e2008-04-09 08:23:16 +0000182 // If we will reduce the # stores (according to this heuristic), do the
183 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
184 // etc.
185 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000186}
Owen Andersona723d1e2008-04-09 08:23:16 +0000187
188
189namespace {
190class MemsetRanges {
191 /// Ranges - A sorted list of the memset ranges. We use std::list here
192 /// because each element is relatively large and expensive to copy.
193 std::list<MemsetRange> Ranges;
194 typedef std::list<MemsetRange>::iterator range_iterator;
Chris Lattner67a716a2011-01-08 20:24:01 +0000195 const TargetData &TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000196public:
Chris Lattner67a716a2011-01-08 20:24:01 +0000197 MemsetRanges(const TargetData &td) : TD(td) {}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000198
Owen Andersona723d1e2008-04-09 08:23:16 +0000199 typedef std::list<MemsetRange>::const_iterator const_iterator;
200 const_iterator begin() const { return Ranges.begin(); }
201 const_iterator end() const { return Ranges.end(); }
202 bool empty() const { return Ranges.empty(); }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000203
Chris Lattner67a716a2011-01-08 20:24:01 +0000204 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner06511262011-01-08 20:54:51 +0000205 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
206 addStore(OffsetFromFirst, SI);
207 else
208 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattner67a716a2011-01-08 20:24:01 +0000209 }
Chris Lattner06511262011-01-08 20:54:51 +0000210
211 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
212 int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000213
Chris Lattner06511262011-01-08 20:54:51 +0000214 addRange(OffsetFromFirst, StoreSize,
215 SI->getPointerOperand(), SI->getAlignment(), SI);
216 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000217
Chris Lattner06511262011-01-08 20:54:51 +0000218 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
219 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
220 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
221 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000222
Chris Lattner06511262011-01-08 20:54:51 +0000223 void addRange(int64_t Start, int64_t Size, Value *Ptr,
224 unsigned Alignment, Instruction *Inst);
225
Owen Andersona723d1e2008-04-09 08:23:16 +0000226};
Nadav Rotema94d6e82012-07-24 10:51:42 +0000227
Owen Andersona723d1e2008-04-09 08:23:16 +0000228} // end anon namespace
229
230
Chris Lattner06511262011-01-08 20:54:51 +0000231/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersona723d1e2008-04-09 08:23:16 +0000232/// new range for the specified store at the specified offset, merging into
233/// existing ranges as appropriate.
Chris Lattner06511262011-01-08 20:54:51 +0000234///
235/// Do a linear search of the ranges to see if this can be joined and/or to
236/// find the insertion point in the list. We keep the ranges sorted for
237/// simplicity here. This is a linear search of a linked list, which is ugly,
238/// however the number of ranges is limited, so this won't get crazy slow.
239void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
240 unsigned Alignment, Instruction *Inst) {
241 int64_t End = Start+Size;
Owen Andersona723d1e2008-04-09 08:23:16 +0000242 range_iterator I = Ranges.begin(), E = Ranges.end();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000243
Owen Andersona723d1e2008-04-09 08:23:16 +0000244 while (I != E && Start > I->End)
245 ++I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000246
Owen Andersona723d1e2008-04-09 08:23:16 +0000247 // We now know that I == E, in which case we didn't find anything to merge
248 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
249 // to insert a new range. Handle this now.
250 if (I == E || End < I->Start) {
251 MemsetRange &R = *Ranges.insert(I, MemsetRange());
252 R.Start = Start;
253 R.End = End;
Chris Lattner06511262011-01-08 20:54:51 +0000254 R.StartPtr = Ptr;
255 R.Alignment = Alignment;
256 R.TheStores.push_back(Inst);
Owen Andersona723d1e2008-04-09 08:23:16 +0000257 return;
258 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000259
Owen Andersona723d1e2008-04-09 08:23:16 +0000260 // This store overlaps with I, add it.
Chris Lattner06511262011-01-08 20:54:51 +0000261 I->TheStores.push_back(Inst);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000262
Owen Andersona723d1e2008-04-09 08:23:16 +0000263 // At this point, we may have an interval that completely contains our store.
264 // If so, just add it to the interval and return.
265 if (I->Start <= Start && I->End >= End)
266 return;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000267
Owen Andersona723d1e2008-04-09 08:23:16 +0000268 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
269 // but is not entirely contained within the range.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000270
Owen Andersona723d1e2008-04-09 08:23:16 +0000271 // See if the range extends the start of the range. In this case, it couldn't
272 // possibly cause it to join the prior range, because otherwise we would have
273 // stopped on *it*.
274 if (Start < I->Start) {
275 I->Start = Start;
Chris Lattner06511262011-01-08 20:54:51 +0000276 I->StartPtr = Ptr;
277 I->Alignment = Alignment;
Owen Andersona723d1e2008-04-09 08:23:16 +0000278 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000279
Owen Andersona723d1e2008-04-09 08:23:16 +0000280 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
281 // is in or right at the end of I), and that End >= I->Start. Extend I out to
282 // End.
283 if (End > I->End) {
284 I->End = End;
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000285 range_iterator NextI = I;
Owen Andersona723d1e2008-04-09 08:23:16 +0000286 while (++NextI != E && End >= NextI->Start) {
287 // Merge the range in.
288 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
289 if (NextI->End > I->End)
290 I->End = NextI->End;
291 Ranges.erase(NextI);
292 NextI = I;
293 }
294 }
295}
296
297//===----------------------------------------------------------------------===//
298// MemCpyOpt Pass
299//===----------------------------------------------------------------------===//
300
301namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000302 class MemCpyOpt : public FunctionPass {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000303 MemoryDependenceAnalysis *MD;
Chris Lattner149f5282011-05-01 18:27:11 +0000304 TargetLibraryInfo *TLI;
Chris Lattner67a716a2011-01-08 20:24:01 +0000305 const TargetData *TD;
Owen Andersona723d1e2008-04-09 08:23:16 +0000306 public:
307 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000308 MemCpyOpt() : FunctionPass(ID) {
309 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000310 MD = 0;
Chris Lattner149f5282011-05-01 18:27:11 +0000311 TLI = 0;
312 TD = 0;
Owen Anderson081c34b2010-10-19 17:21:58 +0000313 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000314
Chris Lattner67a716a2011-01-08 20:24:01 +0000315 bool runOnFunction(Function &F);
316
Owen Andersona723d1e2008-04-09 08:23:16 +0000317 private:
318 // This transformation requires dominator postdominator info
319 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
320 AU.setPreservesCFG();
321 AU.addRequired<DominatorTree>();
322 AU.addRequired<MemoryDependenceAnalysis>();
323 AU.addRequired<AliasAnalysis>();
Chris Lattner149f5282011-05-01 18:27:11 +0000324 AU.addRequired<TargetLibraryInfo>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000325 AU.addPreserved<AliasAnalysis>();
326 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersona723d1e2008-04-09 08:23:16 +0000327 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000328
Owen Andersona723d1e2008-04-09 08:23:16 +0000329 // Helper fuctions
Chris Lattner61c6ba82009-09-01 17:09:55 +0000330 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000331 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000332 bool processMemCpy(MemCpyInst *M);
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000333 bool processMemMove(MemMoveInst *M);
Owen Anderson65491212010-10-15 22:52:12 +0000334 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000335 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Chris Lattner43f8e432010-11-18 07:02:37 +0000336 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
337 uint64_t MSize);
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000338 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattner67a716a2011-01-08 20:24:01 +0000339 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
340 Value *ByteVal);
341
Owen Andersona723d1e2008-04-09 08:23:16 +0000342 bool iterateOnFunction(Function &F);
343 };
Nadav Rotema94d6e82012-07-24 10:51:42 +0000344
Owen Andersona723d1e2008-04-09 08:23:16 +0000345 char MemCpyOpt::ID = 0;
346}
347
348// createMemCpyOptPass - The public interface to this file...
349FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
350
Owen Anderson2ab36d32010-10-12 19:48:12 +0000351INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
352 false, false)
353INITIALIZE_PASS_DEPENDENCY(DominatorTree)
354INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chris Lattner149f5282011-05-01 18:27:11 +0000355INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000356INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
357INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
358 false, false)
Owen Andersona723d1e2008-04-09 08:23:16 +0000359
Chris Lattner67a716a2011-01-08 20:24:01 +0000360/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersona723d1e2008-04-09 08:23:16 +0000361/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sandsab4c3662011-02-15 09:23:02 +0000362/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattner67a716a2011-01-08 20:24:01 +0000363/// attempts to merge them together into a memcpy/memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000364Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattner67a716a2011-01-08 20:24:01 +0000365 Value *StartPtr, Value *ByteVal) {
366 if (TD == 0) return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000367
Chris Lattner67a716a2011-01-08 20:24:01 +0000368 // Okay, so we now have a single store that can be splatable. Scan to find
369 // all subsequent stores of the same value to offset from the same pointer.
370 // Join these together into ranges, so we can decide whether contiguous blocks
371 // are stored.
372 MemsetRanges Ranges(*TD);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000373
Chris Lattner67a716a2011-01-08 20:24:01 +0000374 BasicBlock::iterator BI = StartInst;
375 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner06511262011-01-08 20:54:51 +0000376 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
377 // If the instruction is readnone, ignore it, otherwise bail out. We
378 // don't even allow readonly here because we don't want something like:
Chris Lattner67a716a2011-01-08 20:24:01 +0000379 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner06511262011-01-08 20:54:51 +0000380 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
381 break;
382 continue;
383 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000384
Chris Lattner06511262011-01-08 20:54:51 +0000385 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
386 // If this is a store, see if we can merge it in.
Eli Friedman56efe242011-08-17 22:22:24 +0000387 if (!NextStore->isSimple()) break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000388
Chris Lattner06511262011-01-08 20:54:51 +0000389 // Check to see if this stored value is of the same byte-splattable value.
390 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
391 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000392
Chris Lattner06511262011-01-08 20:54:51 +0000393 // Check to see if this store is to a constant offset from the start ptr.
394 int64_t Offset;
Chris Lattnerf4268502011-01-09 19:26:10 +0000395 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
396 Offset, *TD))
Chris Lattner06511262011-01-08 20:54:51 +0000397 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000398
Chris Lattner06511262011-01-08 20:54:51 +0000399 Ranges.addStore(Offset, NextStore);
400 } else {
401 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000402
Chris Lattner06511262011-01-08 20:54:51 +0000403 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
404 !isa<ConstantInt>(MSI->getLength()))
405 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000406
Chris Lattner06511262011-01-08 20:54:51 +0000407 // Check to see if this store is to a constant offset from the start ptr.
408 int64_t Offset;
409 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD))
410 break;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000411
Chris Lattner06511262011-01-08 20:54:51 +0000412 Ranges.addMemSet(Offset, MSI);
413 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000414 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000415
Chris Lattner67a716a2011-01-08 20:24:01 +0000416 // If we have no ranges, then we just had a single store with nothing that
417 // could be merged in. This is a very common case of course.
418 if (Ranges.empty())
419 return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000420
Chris Lattner67a716a2011-01-08 20:24:01 +0000421 // If we had at least one store that could be merged in, add the starting
422 // store as well. We try to avoid this unless there is at least something
423 // interesting as a small compile-time optimization.
424 Ranges.addInst(0, StartInst);
425
426 // If we create any memsets, we put it right before the first instruction that
427 // isn't part of the memset block. This ensure that the memset is dominated
428 // by any addressing instruction needed by the start of the block.
429 IRBuilder<> Builder(BI);
430
431 // Now that we have full information about ranges, loop over the ranges and
432 // emit memset's for anything big enough to be worthwhile.
433 Instruction *AMemSet = 0;
434 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
435 I != E; ++I) {
436 const MemsetRange &Range = *I;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000437
Chris Lattner67a716a2011-01-08 20:24:01 +0000438 if (Range.TheStores.size() == 1) continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000439
Chris Lattner67a716a2011-01-08 20:24:01 +0000440 // If it is profitable to lower this range to memset, do so now.
441 if (!Range.isProfitableToUseMemset(*TD))
442 continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000443
Chris Lattner67a716a2011-01-08 20:24:01 +0000444 // Otherwise, we do want to transform this! Create a new memset.
445 // Get the starting pointer of the block.
446 StartPtr = Range.StartPtr;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000447
Chris Lattner67a716a2011-01-08 20:24:01 +0000448 // Determine alignment
449 unsigned Alignment = Range.Alignment;
450 if (Alignment == 0) {
Nadav Rotema94d6e82012-07-24 10:51:42 +0000451 Type *EltType =
Chris Lattner67a716a2011-01-08 20:24:01 +0000452 cast<PointerType>(StartPtr->getType())->getElementType();
453 Alignment = TD->getABITypeAlignment(EltType);
454 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000455
456 AMemSet =
Chris Lattner67a716a2011-01-08 20:24:01 +0000457 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000458
Chris Lattner67a716a2011-01-08 20:24:01 +0000459 DEBUG(dbgs() << "Replace stores:\n";
460 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
461 dbgs() << *Range.TheStores[i] << '\n';
462 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelb90584a2011-05-04 21:58:58 +0000463
464 if (!Range.TheStores.empty())
465 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
466
Chris Lattner67a716a2011-01-08 20:24:01 +0000467 // Zap all the stores.
Chris Lattner06511262011-01-08 20:54:51 +0000468 for (SmallVector<Instruction*, 16>::const_iterator
Chris Lattner67a716a2011-01-08 20:24:01 +0000469 SI = Range.TheStores.begin(),
Chris Lattner8a629572011-01-08 22:19:21 +0000470 SE = Range.TheStores.end(); SI != SE; ++SI) {
471 MD->removeInstruction(*SI);
Chris Lattner67a716a2011-01-08 20:24:01 +0000472 (*SI)->eraseFromParent();
Chris Lattner8a629572011-01-08 22:19:21 +0000473 }
Chris Lattner67a716a2011-01-08 20:24:01 +0000474 ++NumMemSetInfer;
475 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000476
Chris Lattner67a716a2011-01-08 20:24:01 +0000477 return AMemSet;
478}
479
480
Chris Lattner61c6ba82009-09-01 17:09:55 +0000481bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman56efe242011-08-17 22:22:24 +0000482 if (!SI->isSimple()) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000483
Chris Lattner67a716a2011-01-08 20:24:01 +0000484 if (TD == 0) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000485
486 // Detect cases where we're performing call slot forwarding, but
487 // happen to be using a load-store pair to implement it, rather than
488 // a memcpy.
489 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman56efe242011-08-17 22:22:24 +0000490 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedman5d40ef22011-06-15 01:25:56 +0000491 LI->getParent() == SI->getParent()) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000492 MemDepResult ldep = MD->getDependency(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000493 CallInst *C = 0;
Eli Friedman70d893e2011-06-02 21:24:42 +0000494 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
495 C = dyn_cast<CallInst>(ldep.getInst());
496
497 if (C) {
498 // Check that nothing touches the dest of the "copy" between
499 // the call and the store.
Eli Friedman5d40ef22011-06-15 01:25:56 +0000500 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
501 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
502 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
503 E = C; I != E; --I) {
504 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
Eli Friedman70d893e2011-06-02 21:24:42 +0000505 C = 0;
Eli Friedman5d40ef22011-06-15 01:25:56 +0000506 break;
507 }
Eli Friedman70d893e2011-06-02 21:24:42 +0000508 }
509 }
510
Owen Anderson65491212010-10-15 22:52:12 +0000511 if (C) {
Duncan Sandsf5874752012-10-04 10:54:40 +0000512 unsigned storeAlign = SI->getAlignment();
513 if (!storeAlign)
514 storeAlign = TD->getABITypeAlignment(SI->getOperand(0)->getType());
515 unsigned loadAlign = LI->getAlignment();
516 if (!loadAlign)
517 loadAlign = TD->getABITypeAlignment(LI->getType());
518
Owen Anderson65491212010-10-15 22:52:12 +0000519 bool changed = performCallSlotOptzn(LI,
Nadav Rotema94d6e82012-07-24 10:51:42 +0000520 SI->getPointerOperand()->stripPointerCasts(),
Owen Anderson65491212010-10-15 22:52:12 +0000521 LI->getPointerOperand()->stripPointerCasts(),
Duncan Sandsf5874752012-10-04 10:54:40 +0000522 TD->getTypeStoreSize(SI->getOperand(0)->getType()),
523 std::min(storeAlign, loadAlign), C);
Owen Anderson65491212010-10-15 22:52:12 +0000524 if (changed) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000525 MD->removeInstruction(SI);
Owen Anderson65491212010-10-15 22:52:12 +0000526 SI->eraseFromParent();
Chris Lattnerf4268502011-01-09 19:26:10 +0000527 MD->removeInstruction(LI);
Owen Anderson65491212010-10-15 22:52:12 +0000528 LI->eraseFromParent();
529 ++NumMemCpyInstr;
530 return true;
531 }
532 }
533 }
534 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000535
Owen Andersona723d1e2008-04-09 08:23:16 +0000536 // There are two cases that are interesting for this code to handle: memcpy
537 // and memset. Right now we only handle memset.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000538
Owen Andersona723d1e2008-04-09 08:23:16 +0000539 // Ensure that the value being stored is something that can be memset'able a
540 // byte at a time like "0" or "-1" or any width, as well as things like
541 // 0xA0A0A0A0 and 0.0.
Chris Lattner67a716a2011-01-08 20:24:01 +0000542 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
543 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
544 ByteVal)) {
545 BBI = I; // Don't invalidate iterator.
546 return true;
Mon P Wang20adc9d2010-04-04 03:10:48 +0000547 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000548
Chris Lattner67a716a2011-01-08 20:24:01 +0000549 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000550}
551
Chris Lattnerd90a1922011-01-08 21:19:19 +0000552bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
553 // See if there is another memset or store neighboring this memset which
554 // allows us to widen out the memset to do a single larger store.
Chris Lattner0468e3e2011-01-08 22:11:56 +0000555 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
556 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
557 MSI->getValue())) {
558 BBI = I; // Don't invalidate iterator.
559 return true;
560 }
Chris Lattnerd90a1922011-01-08 21:19:19 +0000561 return false;
562}
563
Owen Andersona723d1e2008-04-09 08:23:16 +0000564
565/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
566/// and checks for the possibility of a call slot optimization by having
567/// the call write its result directly into the destination of the memcpy.
Owen Anderson65491212010-10-15 22:52:12 +0000568bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
569 Value *cpyDest, Value *cpySrc,
Duncan Sandsf5874752012-10-04 10:54:40 +0000570 uint64_t cpyLen, unsigned cpyAlign,
571 CallInst *C) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000572 // The general transformation to keep in mind is
573 //
574 // call @func(..., src, ...)
575 // memcpy(dest, src, ...)
576 //
577 // ->
578 //
579 // memcpy(dest, src, ...)
580 // call @func(..., dest, ...)
581 //
582 // Since moving the memcpy is technically awkward, we additionally check that
583 // src only holds uninitialized values at the moment of the call, meaning that
584 // the memcpy can be discarded rather than moved.
585
586 // Deliberately get the source and destination with bitcasts stripped away,
587 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000588 CallSite CS(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000589
Owen Andersona723d1e2008-04-09 08:23:16 +0000590 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000591 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersona723d1e2008-04-09 08:23:16 +0000592 if (!srcAlloca)
593 return false;
594
595 // Check that all of src is copied to dest.
Chris Lattner67a716a2011-01-08 20:24:01 +0000596 if (TD == 0) return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000597
Chris Lattner61c6ba82009-09-01 17:09:55 +0000598 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000599 if (!srcArraySize)
600 return false;
601
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000602 uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000603 srcArraySize->getZExtValue();
604
Owen Anderson65491212010-10-15 22:52:12 +0000605 if (cpyLen < srcSize)
Owen Andersona723d1e2008-04-09 08:23:16 +0000606 return false;
607
Duncan Sandsf5874752012-10-04 10:54:40 +0000608 // Check that dest points to memory that is at least as aligned as src.
609 unsigned srcAlign = srcAlloca->getAlignment();
610 if (!srcAlign)
611 srcAlign = TD->getABITypeAlignment(srcAlloca->getAllocatedType());
612 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
613 // If dest is not aligned enough and we can't increase its alignment then
614 // bail out.
615 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
616 return false;
617
Owen Andersona723d1e2008-04-09 08:23:16 +0000618 // Check that accessing the first srcSize bytes of dest will not cause a
619 // trap. Otherwise the transform is invalid since it might cause a trap
620 // to occur earlier than it otherwise would.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000621 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000622 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000623 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersona723d1e2008-04-09 08:23:16 +0000624 if (!destArraySize)
625 return false;
626
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000627 uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersona723d1e2008-04-09 08:23:16 +0000628 destArraySize->getZExtValue();
629
630 if (destSize < srcSize)
631 return false;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000632 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000633 // If the destination is an sret parameter then only accesses that are
634 // outside of the returned struct type can trap.
635 if (!A->hasStructRetAttr())
636 return false;
637
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000638 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Dan Gohman8942f9bb2009-08-18 01:17:52 +0000639 uint64_t destSize = TD->getTypeAllocSize(StructTy);
Owen Andersona723d1e2008-04-09 08:23:16 +0000640
641 if (destSize < srcSize)
642 return false;
643 } else {
644 return false;
645 }
646
647 // Check that src is not accessed except via the call and the memcpy. This
648 // guarantees that it holds only undefined values when passed in (so the final
649 // memcpy can be dropped), that it is not read or written between the call and
650 // the memcpy, and that writing beyond the end of it is undefined.
651 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
652 srcAlloca->use_end());
653 while (!srcUseList.empty()) {
Dan Gohman321a8132010-01-05 16:27:25 +0000654 User *UI = srcUseList.pop_back_val();
Owen Andersona723d1e2008-04-09 08:23:16 +0000655
Owen Anderson009e4f72008-06-01 22:26:26 +0000656 if (isa<BitCastInst>(UI)) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000657 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
658 I != E; ++I)
659 srcUseList.push_back(*I);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000660 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) {
Owen Anderson009e4f72008-06-01 22:26:26 +0000661 if (G->hasAllZeroIndices())
662 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
663 I != E; ++I)
664 srcUseList.push_back(*I);
665 else
666 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000667 } else if (UI != C && UI != cpy) {
668 return false;
669 }
670 }
671
672 // Since we're changing the parameter to the callsite, we need to make sure
673 // that what would be the new parameter dominates the callsite.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000674 DominatorTree &DT = getAnalysis<DominatorTree>();
675 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersona723d1e2008-04-09 08:23:16 +0000676 if (!DT.dominates(cpyDestInst, C))
677 return false;
678
679 // In addition to knowing that the call does not access src in some
680 // unexpected manner, for example via a global, which we deduce from
681 // the use analysis, we also need to know that it does not sneakily
682 // access dest. We rely on AA to figure this out for us.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000683 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chad Rosier3a884f52012-05-14 20:35:04 +0000684 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
685 // If necessary, perform additional analysis.
686 if (MR != AliasAnalysis::NoModRef)
687 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
688 if (MR != AliasAnalysis::NoModRef)
Owen Andersona723d1e2008-04-09 08:23:16 +0000689 return false;
690
691 // All the checks have passed, so do the transformation.
Owen Anderson12cb36c2008-06-01 21:52:16 +0000692 bool changedArgument = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000693 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson009e4f72008-06-01 22:26:26 +0000694 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Owen Andersona723d1e2008-04-09 08:23:16 +0000695 if (cpySrc->getType() != cpyDest->getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000696 cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
Owen Andersona723d1e2008-04-09 08:23:16 +0000697 cpyDest->getName(), C);
Owen Anderson12cb36c2008-06-01 21:52:16 +0000698 changedArgument = true;
Chris Lattner61c6ba82009-09-01 17:09:55 +0000699 if (CS.getArgument(i)->getType() == cpyDest->getType())
Owen Anderson009e4f72008-06-01 22:26:26 +0000700 CS.setArgument(i, cpyDest);
Chris Lattner61c6ba82009-09-01 17:09:55 +0000701 else
Nadav Rotema94d6e82012-07-24 10:51:42 +0000702 CS.setArgument(i, CastInst::CreatePointerCast(cpyDest,
Chris Lattner61c6ba82009-09-01 17:09:55 +0000703 CS.getArgument(i)->getType(), cpyDest->getName(), C));
Owen Andersona723d1e2008-04-09 08:23:16 +0000704 }
705
Owen Anderson12cb36c2008-06-01 21:52:16 +0000706 if (!changedArgument)
707 return false;
708
Duncan Sandsf5874752012-10-04 10:54:40 +0000709 // If the destination wasn't sufficiently aligned then increase its alignment.
710 if (!isDestSufficientlyAligned) {
711 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
712 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
713 }
714
Owen Andersona723d1e2008-04-09 08:23:16 +0000715 // Drop any cached information about the call, because we may have changed
716 // its dependence information by changing its parameter.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000717 MD->removeInstruction(C);
Owen Andersona723d1e2008-04-09 08:23:16 +0000718
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000719 // Remove the memcpy.
720 MD->removeInstruction(cpy);
Dan Gohmanfe601042010-06-22 15:08:57 +0000721 ++NumMemCpyInstr;
Owen Andersona723d1e2008-04-09 08:23:16 +0000722
723 return true;
724}
725
Chris Lattner43f8e432010-11-18 07:02:37 +0000726/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
727/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
728/// copy from MDep's input if we can. MSize is the size of M's copy.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000729///
Chris Lattner43f8e432010-11-18 07:02:37 +0000730bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
731 uint64_t MSize) {
732 // We can only transforms memcpy's where the dest of one is the source of the
733 // other.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000734 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner43f8e432010-11-18 07:02:37 +0000735 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000736
Chris Lattnerf7f35462010-12-09 07:39:50 +0000737 // If dep instruction is reading from our current input, then it is a noop
738 // transfer and substituting the input won't change this instruction. Just
739 // ignore the input and let someone else zap MDep. This handles cases like:
740 // memcpy(a <- a)
741 // memcpy(b <- a)
742 if (M->getSource() == MDep->getSource())
743 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000744
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000745 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner43f8e432010-11-18 07:02:37 +0000746 // must be larger than the following one.
Dan Gohman8fb25c52011-01-21 22:07:57 +0000747 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
748 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
749 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
750 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000751
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000752 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner604f6fe2010-11-21 08:06:10 +0000753
754 // Verify that the copied-from memory doesn't change in between the two
755 // transfers. For example, in:
756 // memcpy(a <- b)
757 // *b = 42;
758 // memcpy(c <- a)
759 // It would be invalid to transform the second memcpy into memcpy(c <- b).
760 //
761 // TODO: If the code between M and MDep is transparent to the destination "c",
762 // then we could still perform the xform by moving M up to the first memcpy.
763 //
764 // NOTE: This is conservative, it will stop on any read from the source loc,
765 // not just the defining memcpy.
766 MemDepResult SourceDep =
767 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
768 false, M, M->getParent());
769 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
770 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000771
Chris Lattner5a7aeaa2010-11-18 08:00:57 +0000772 // If the dest of the second might alias the source of the first, then the
773 // source and dest might overlap. We still want to eliminate the intermediate
774 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner61db1f52010-12-26 22:57:41 +0000775 bool UseMemMove = false;
776 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
777 UseMemMove = true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000778
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000779 // If all checks passed, then we can transform M.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000780
Chris Lattner43f8e432010-11-18 07:02:37 +0000781 // Make sure to use the lesser of the alignment of the source and the dest
782 // since we're changing where we're reading from, but don't want to increase
783 // the alignment past what can be read from or written to.
784 // TODO: Is this worth it if we're creating a less aligned memcpy? For
785 // example we could be moving from movaps -> movq on x86.
Chris Lattnerd528be62010-11-18 08:07:09 +0000786 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000787
Chris Lattner61db1f52010-12-26 22:57:41 +0000788 IRBuilder<> Builder(M);
789 if (UseMemMove)
790 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
791 Align, M->isVolatile());
792 else
793 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
794 Align, M->isVolatile());
Chris Lattnerd528be62010-11-18 08:07:09 +0000795
Chris Lattner604f6fe2010-11-21 08:06:10 +0000796 // Remove the instruction we're replacing.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000797 MD->removeInstruction(M);
Chris Lattnerd528be62010-11-18 08:07:09 +0000798 M->eraseFromParent();
799 ++NumMemCpyInstr;
800 return true;
Chris Lattner43f8e432010-11-18 07:02:37 +0000801}
802
803
Gabor Greif7d3056b2010-07-28 22:50:26 +0000804/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
805/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
806/// B to be a memcpy from X to Z (or potentially a memmove, depending on
807/// circumstances). This allows later passes to remove the first memcpy
808/// altogether.
Chris Lattner61c6ba82009-09-01 17:09:55 +0000809bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000810 // We can only optimize statically-sized memcpy's that are non-volatile.
811 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
812 if (CopySize == 0 || M->isVolatile()) return false;
Owen Anderson65491212010-10-15 22:52:12 +0000813
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000814 // If the source and destination of the memcpy are the same, then zap it.
815 if (M->getSource() == M->getDest()) {
816 MD->removeInstruction(M);
817 M->eraseFromParent();
818 return false;
819 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000820
821 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000822 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer3fed0d92010-12-26 15:23:45 +0000823 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000824 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner61db1f52010-12-26 22:57:41 +0000825 IRBuilder<> Builder(M);
826 Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize,
827 M->getAlignment(), false);
Benjamin Kramer49c7e3e2010-12-24 22:23:59 +0000828 MD->removeInstruction(M);
829 M->eraseFromParent();
830 ++NumCpyToSet;
831 return true;
832 }
Benjamin Kramera1120872010-12-24 21:17:12 +0000833
Owen Andersona8bd6582008-04-21 07:45:10 +0000834 // The are two possible optimizations we can do for memcpy:
Chris Lattner61c6ba82009-09-01 17:09:55 +0000835 // a) memcpy-memcpy xform which exposes redundance for DSE.
836 // b) call-memcpy xform for return slot optimization.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000837 MemDepResult DepInfo = MD->getDependency(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000838 if (DepInfo.isClobber()) {
839 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
840 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsf5874752012-10-04 10:54:40 +0000841 CopySize->getZExtValue(), M->getAlignment(),
842 C)) {
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000843 MD->removeInstruction(M);
844 M->eraseFromParent();
845 return true;
846 }
Chris Lattner8fdca6a2010-12-09 07:45:45 +0000847 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000848 }
Ahmed Charlesb83a67e2012-02-13 06:30:56 +0000849
850 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
Nick Lewycky36c7e6c2011-10-16 20:13:32 +0000851 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
852 M, M->getParent());
853 if (SrcDepInfo.isClobber()) {
854 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
855 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
856 }
857
Owen Anderson02e99882008-04-29 21:51:00 +0000858 return false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000859}
860
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000861/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
862/// are guaranteed not to alias.
863bool MemCpyOpt::processMemMove(MemMoveInst *M) {
864 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
865
Chris Lattner149f5282011-05-01 18:27:11 +0000866 if (!TLI->has(LibFunc::memmove))
867 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000868
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000869 // See if the pointers alias.
Chris Lattner61db1f52010-12-26 22:57:41 +0000870 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000871 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000872
David Greenecb33fd12010-01-05 01:27:47 +0000873 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000874
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000875 // If not, then we know we can transform this.
876 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +0000877 Type *ArgTys[3] = { M->getRawDest()->getType(),
878 M->getRawSource()->getType(),
879 M->getLength()->getType() };
Gabor Greifa3997812010-07-22 10:37:47 +0000880 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000881 ArgTys));
Duncan Sands05cd03b2009-09-03 13:37:16 +0000882
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000883 // MemDep may have over conservative information about this instruction, just
884 // conservatively flush it from the cache.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000885 MD->removeInstruction(M);
Duncan Sands05cd03b2009-09-03 13:37:16 +0000886
887 ++NumMoveToCpy;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000888 return true;
889}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000890
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000891/// processByValArgument - This is called on every byval argument in call sites.
892bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Chris Lattner67a716a2011-01-08 20:24:01 +0000893 if (TD == 0) return false;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000894
Chris Lattner604f6fe2010-11-21 08:06:10 +0000895 // Find out what feeds this byval argument.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000896 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewycky865703e2011-10-12 00:14:31 +0000897 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Chris Lattnerb5a31962010-12-01 01:24:55 +0000898 uint64_t ByValSize = TD->getTypeAllocSize(ByValTy);
Chris Lattner604f6fe2010-11-21 08:06:10 +0000899 MemDepResult DepInfo =
900 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
901 true, CS.getInstruction(),
902 CS.getInstruction()->getParent());
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000903 if (!DepInfo.isClobber())
904 return false;
905
906 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
907 // a memcpy, see if we can byval from the source of the memcpy instead of the
908 // result.
909 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
910 if (MDep == 0 || MDep->isVolatile() ||
911 ByValArg->stripPointerCasts() != MDep->getDest())
912 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000913
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000914 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000915 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner604f6fe2010-11-21 08:06:10 +0000916 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000917 return false;
918
Chris Lattnerb3f06732011-05-23 00:03:39 +0000919 // Get the alignment of the byval. If the call doesn't specify the alignment,
920 // then it is some target specific value that we can't know.
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000921 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattnerb3f06732011-05-23 00:03:39 +0000922 if (ByValAlign == 0) return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000923
Chris Lattnerb3f06732011-05-23 00:03:39 +0000924 // If it is greater than the memcpy, then we check to see if we can force the
925 // source of the memcpy to the alignment we need. If we fail, we bail out.
926 if (MDep->getAlignment() < ByValAlign &&
927 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, TD) < ByValAlign)
928 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000929
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000930 // Verify that the copied-from memory doesn't change in between the memcpy and
931 // the byval call.
932 // memcpy(a <- b)
933 // *b = 42;
934 // foo(*a)
935 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner604f6fe2010-11-21 08:06:10 +0000936 //
937 // NOTE: This is conservative, it will stop on any read from the source loc,
938 // not just the defining memcpy.
939 MemDepResult SourceDep =
940 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
941 false, CS.getInstruction(), MDep->getParent());
942 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
943 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000944
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000945 Value *TmpCast = MDep->getSource();
946 if (MDep->getSource()->getType() != ByValArg->getType())
947 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
948 "tmpcast", CS.getInstruction());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000949
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000950 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
951 << " " << *MDep << "\n"
952 << " " << *CS.getInstruction() << "\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000953
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000954 // Otherwise we're good! Update the byval argument.
955 CS.setArgument(ArgNo, TmpCast);
956 ++NumMemCpyInstr;
957 return true;
958}
959
960/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersona723d1e2008-04-09 08:23:16 +0000961bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000962 bool MadeChange = false;
Owen Andersona723d1e2008-04-09 08:23:16 +0000963
Chris Lattner61c6ba82009-09-01 17:09:55 +0000964 // Walk all instruction in the function.
Owen Andersona8bd6582008-04-21 07:45:10 +0000965 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000966 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattner61c6ba82009-09-01 17:09:55 +0000967 // Avoid invalidating the iterator.
968 Instruction *I = BI++;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000969
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000970 bool RepeatInstruction = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000971
Owen Andersona8bd6582008-04-21 07:45:10 +0000972 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattner61c6ba82009-09-01 17:09:55 +0000973 MadeChange |= processStore(SI, BI);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000974 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
975 RepeatInstruction = processMemSet(M, BI);
976 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000977 RepeatInstruction = processMemCpy(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000978 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000979 RepeatInstruction = processMemMove(M);
Chris Lattnerd90a1922011-01-08 21:19:19 +0000980 else if (CallSite CS = (Value*)I) {
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000981 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky173862e2011-11-20 19:09:04 +0000982 if (CS.isByValArgument(i))
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000983 MadeChange |= processByValArgument(CS, i);
984 }
985
986 // Reprocess the instruction if desired.
987 if (RepeatInstruction) {
Chris Lattner8a629572011-01-08 22:19:21 +0000988 if (BI != BB->begin()) --BI;
Chris Lattner2f5f90a2010-11-21 00:28:59 +0000989 MadeChange = true;
Chris Lattnerf41eaac2009-09-01 17:56:32 +0000990 }
Owen Andersona723d1e2008-04-09 08:23:16 +0000991 }
992 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000993
Chris Lattner61c6ba82009-09-01 17:09:55 +0000994 return MadeChange;
Owen Andersona723d1e2008-04-09 08:23:16 +0000995}
Chris Lattner61c6ba82009-09-01 17:09:55 +0000996
997// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
998// function.
999//
1000bool MemCpyOpt::runOnFunction(Function &F) {
1001 bool MadeChange = false;
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001002 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner67a716a2011-01-08 20:24:01 +00001003 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner149f5282011-05-01 18:27:11 +00001004 TLI = &getAnalysis<TargetLibraryInfo>();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001005
Chris Lattner149f5282011-05-01 18:27:11 +00001006 // If we don't have at least memset and memcpy, there is little point of doing
1007 // anything here. These are required by a freestanding implementation, so if
1008 // even they are disabled, there is no point in trying hard.
1009 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1010 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001011
Chris Lattner61c6ba82009-09-01 17:09:55 +00001012 while (1) {
1013 if (!iterateOnFunction(F))
1014 break;
1015 MadeChange = true;
1016 }
Nadav Rotema94d6e82012-07-24 10:51:42 +00001017
Chris Lattner2f5f90a2010-11-21 00:28:59 +00001018 MD = 0;
Chris Lattner61c6ba82009-09-01 17:09:55 +00001019 return MadeChange;
1020}