blob: 46105dab1d85cc2476c67c2d3cb30c3ca2a62e84 [file] [log] [blame]
Owen Andersonef9a6fd2008-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
Owen Andersonef9a6fd2008-04-09 08:23:16 +000015#include "llvm/Transforms/Scalar.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000016#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Statistic.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000019#include "llvm/Analysis/AssumptionCache.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000020#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000030#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000031#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000032#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyf836c892015-07-21 21:56:26 +000033#include <algorithm>
Owen Andersonef9a6fd2008-04-09 08:23:16 +000034using namespace llvm;
35
Chandler Carruth964daaa2014-04-22 02:55:47 +000036#define DEBUG_TYPE "memcpyopt"
37
Owen Andersonef9a6fd2008-04-09 08:23:16 +000038STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
39STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000040STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000041STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000042
Benjamin Kramer15a257d2012-09-13 16:29:49 +000043static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000044 bool &VariableIdxFound,
45 const DataLayout &DL) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000046 // Skip over the first indices.
47 gep_type_iterator GTI = gep_type_begin(GEP);
48 for (unsigned i = 1; i != Idx; ++i, ++GTI)
49 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000050
Owen Andersonef9a6fd2008-04-09 08:23:16 +000051 // Compute the offset implied by the rest of the indices.
52 int64_t Offset = 0;
53 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
54 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +000055 if (!OpC)
Owen Andersonef9a6fd2008-04-09 08:23:16 +000056 return VariableIdxFound = true;
57 if (OpC->isZero()) continue; // No offset.
58
59 // Handle struct indices, which add their field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +000060 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000061 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000062 continue;
63 }
Nadav Rotem465834c2012-07-24 10:51:42 +000064
Owen Andersonef9a6fd2008-04-09 08:23:16 +000065 // Otherwise, we have a sequential type like an array or vector. Multiply
66 // the index by the ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000067 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000068 Offset += Size*OpC->getSExtValue();
69 }
70
71 return Offset;
72}
73
74/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
75/// constant offset, and return that constant offset. For example, Ptr1 might
76/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
77static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000078 const DataLayout &DL) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +000079 Ptr1 = Ptr1->stripPointerCasts();
80 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer3ef5e462014-03-10 21:05:13 +000081
82 // Handle the trivial case first.
83 if (Ptr1 == Ptr2) {
84 Offset = 0;
85 return true;
86 }
87
Benjamin Kramer15a257d2012-09-13 16:29:49 +000088 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
89 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +000090
Chris Lattner5120ebf2011-01-08 21:07:56 +000091 bool VariableIdxFound = false;
92
93 // If one pointer is a GEP and the other isn't, then see if the GEP is a
94 // constant offset from the base, as in "P" and "gep P, 1".
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000096 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +000097 return !VariableIdxFound;
98 }
99
Craig Topperf40110f2014-04-25 05:29:35 +0000100 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000101 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +0000102 return !VariableIdxFound;
103 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000104
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000105 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
106 // base. After that base, they may have some number of common (and
107 // potentially variable) indices. After that they handle some constant
108 // offset, which determines their offset from each other. At this point, we
109 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000110 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
111 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000112
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000113 // Skip any common indices and track the GEP types.
114 unsigned Idx = 1;
115 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
116 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
117 break;
118
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000119 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
120 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000121 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000122
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000123 Offset = Offset2-Offset1;
124 return true;
125}
126
127
128/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
129/// This allows us to analyze stores like:
130/// store 0 -> P+1
131/// store 0 -> P+0
132/// store 0 -> P+3
133/// store 0 -> P+2
134/// which sometimes happens with stores to arrays of structs etc. When we see
135/// the first store, we make a range [1, 2). The second store extends the range
136/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
137/// two ranges into [0, 3) which is memset'able.
138namespace {
139struct MemsetRange {
140 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000141 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000142 int64_t Start, End;
143
144 /// StartPtr - The getelementptr instruction that points to the start of the
145 /// range.
146 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000147
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000148 /// Alignment - The known alignment of the first store.
149 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000150
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000151 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000152 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000153
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000154 bool isProfitableToUseMemset(const DataLayout &DL) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000155};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000156} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000157
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
Chad Rosier32775572011-12-05 22:53:09 +0000159 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000160 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000161
162 // If there is nothing to merge, don't do anything.
163 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000164
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000165 // If any of the stores are a memset, then it is always good to extend the
166 // memset.
167 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
168 if (!isa<StoreInst>(TheStores[i]))
169 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000170
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000171 // Assume that the code generator is capable of merging pairs of stores
172 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000173 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000174
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000175 // If we have fewer than 8 stores, it can still be worthwhile to do this.
176 // For example, merging 4 i8 stores into an i32 store is useful almost always.
177 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
178 // memset will be split into 2 32-bit stores anyway) and doing so can
179 // pessimize the llvm optimizer.
180 //
181 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000182 // the maximum GPR width is the same size as the largest legal integer
183 // size. If so, check to see whether we will end up actually reducing the
184 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000185 unsigned Bytes = unsigned(End-Start);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000186 unsigned MaxIntSize = DL.getLargestLegalIntTypeSize();
Matt Arsenault899f7d22013-09-16 22:43:16 +0000187 if (MaxIntSize == 0)
188 MaxIntSize = 1;
189 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000190
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000191 // Assume the remaining bytes if any are done a byte at a time.
Matt Arsenault899f7d22013-09-16 22:43:16 +0000192 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000193
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000194 // If we will reduce the # stores (according to this heuristic), do the
195 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
196 // etc.
197 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000198}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000199
200
201namespace {
202class MemsetRanges {
Nick Lewyckyf836c892015-07-21 21:56:26 +0000203 /// Ranges - A sorted list of the memset ranges.
204 SmallVector<MemsetRange, 8> Ranges;
205 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000206 const DataLayout &DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000207public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000208 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000209
Nick Lewyckyf836c892015-07-21 21:56:26 +0000210 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000211 const_iterator begin() const { return Ranges.begin(); }
212 const_iterator end() const { return Ranges.end(); }
213 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000214
Chris Lattnerc6381472011-01-08 20:24:01 +0000215 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
217 addStore(OffsetFromFirst, SI);
218 else
219 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000220 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000221
222 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000223 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000224
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000225 addRange(OffsetFromFirst, StoreSize,
226 SI->getPointerOperand(), SI->getAlignment(), SI);
227 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000228
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000229 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
230 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
231 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
232 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000233
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000234 void addRange(int64_t Start, int64_t Size, Value *Ptr,
235 unsigned Alignment, Instruction *Inst);
236
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000237};
Nadav Rotem465834c2012-07-24 10:51:42 +0000238
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000239} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000240
241
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000242/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000243/// new range for the specified store at the specified offset, merging into
244/// existing ranges as appropriate.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000245void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
246 unsigned Alignment, Instruction *Inst) {
247 int64_t End = Start+Size;
Nadav Rotem465834c2012-07-24 10:51:42 +0000248
Nick Lewyckyf836c892015-07-21 21:56:26 +0000249 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
250 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
Nadav Rotem465834c2012-07-24 10:51:42 +0000251
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000252 // We now know that I == E, in which case we didn't find anything to merge
253 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
254 // to insert a new range. Handle this now.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000255 if (I == Ranges.end() || End < I->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000256 MemsetRange &R = *Ranges.insert(I, MemsetRange());
257 R.Start = Start;
258 R.End = End;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000259 R.StartPtr = Ptr;
260 R.Alignment = Alignment;
261 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000262 return;
263 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000264
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000265 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000266 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000267
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000268 // At this point, we may have an interval that completely contains our store.
269 // If so, just add it to the interval and return.
270 if (I->Start <= Start && I->End >= End)
271 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000272
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000273 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
274 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000275
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000276 // See if the range extends the start of the range. In this case, it couldn't
277 // possibly cause it to join the prior range, because otherwise we would have
278 // stopped on *it*.
279 if (Start < I->Start) {
280 I->Start = Start;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000281 I->StartPtr = Ptr;
282 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000283 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000284
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000285 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
286 // is in or right at the end of I), and that End >= I->Start. Extend I out to
287 // End.
288 if (End > I->End) {
289 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000290 range_iterator NextI = I;
Nick Lewyckyf836c892015-07-21 21:56:26 +0000291 while (++NextI != Ranges.end() && End >= NextI->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000292 // Merge the range in.
293 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
294 if (NextI->End > I->End)
295 I->End = NextI->End;
296 Ranges.erase(NextI);
297 NextI = I;
298 }
299 }
300}
301
302//===----------------------------------------------------------------------===//
303// MemCpyOpt Pass
304//===----------------------------------------------------------------------===//
305
306namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000307 class MemCpyOpt : public FunctionPass {
Chris Lattner58f9f582010-11-21 00:28:59 +0000308 MemoryDependenceAnalysis *MD;
Chris Lattner23f61a02011-05-01 18:27:11 +0000309 TargetLibraryInfo *TLI;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000310 public:
311 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000312 MemCpyOpt() : FunctionPass(ID) {
313 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Craig Topperf40110f2014-04-25 05:29:35 +0000314 MD = nullptr;
315 TLI = nullptr;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000316 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000317
Craig Topper3e4c6972014-03-05 09:10:37 +0000318 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000319
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000320 private:
321 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000322 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000323 AU.setPreservesCFG();
Chandler Carruth66b31302015-01-04 12:03:27 +0000324 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000325 AU.addRequired<DominatorTreeWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000326 AU.addRequired<MemoryDependenceAnalysis>();
327 AU.addRequired<AliasAnalysis>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000328 AU.addRequired<TargetLibraryInfoWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000329 AU.addPreserved<AliasAnalysis>();
330 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000331 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000332
Matt Walaa4afccd2015-06-12 18:16:51 +0000333 // Helper functions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000334 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000335 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000336 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000337 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000338 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000339 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000340 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000341 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000342 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
Chris Lattner58f9f582010-11-21 00:28:59 +0000343 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000344 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
345 Value *ByteVal);
346
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000347 bool iterateOnFunction(Function &F);
348 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000349
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000350 char MemCpyOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000351}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000352
353// createMemCpyOptPass - The public interface to this file...
354FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
355
Owen Anderson8ac477f2010-10-12 19:48:12 +0000356INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
357 false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000358INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000359INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000360INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000361INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000362INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
363INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
364 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000365
Chris Lattnerc6381472011-01-08 20:24:01 +0000366/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000367/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sands75b5d272011-02-15 09:23:02 +0000368/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattnerc6381472011-01-08 20:24:01 +0000369/// attempts to merge them together into a memcpy/memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000370Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattnerc6381472011-01-08 20:24:01 +0000371 Value *StartPtr, Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000372 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000373
Chris Lattnerc6381472011-01-08 20:24:01 +0000374 // Okay, so we now have a single store that can be splatable. Scan to find
375 // all subsequent stores of the same value to offset from the same pointer.
376 // Join these together into ranges, so we can decide whether contiguous blocks
377 // are stored.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000378 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000379
Chris Lattnerc6381472011-01-08 20:24:01 +0000380 BasicBlock::iterator BI = StartInst;
381 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000382 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
383 // If the instruction is readnone, ignore it, otherwise bail out. We
384 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000385 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000386 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
387 break;
388 continue;
389 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000390
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000391 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
392 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000393 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000394
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000395 // Check to see if this stored value is of the same byte-splattable value.
396 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
397 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000398
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000399 // Check to see if this store is to a constant offset from the start ptr.
400 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000401 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
402 DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000403 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000404
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000405 Ranges.addStore(Offset, NextStore);
406 } else {
407 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000408
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000409 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
410 !isa<ConstantInt>(MSI->getLength()))
411 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000412
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000413 // Check to see if this store is to a constant offset from the start ptr.
414 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000415 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000416 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000417
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000418 Ranges.addMemSet(Offset, MSI);
419 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000420 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000421
Chris Lattnerc6381472011-01-08 20:24:01 +0000422 // If we have no ranges, then we just had a single store with nothing that
423 // could be merged in. This is a very common case of course.
424 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000425 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000426
Chris Lattnerc6381472011-01-08 20:24:01 +0000427 // If we had at least one store that could be merged in, add the starting
428 // store as well. We try to avoid this unless there is at least something
429 // interesting as a small compile-time optimization.
430 Ranges.addInst(0, StartInst);
431
432 // If we create any memsets, we put it right before the first instruction that
433 // isn't part of the memset block. This ensure that the memset is dominated
434 // by any addressing instruction needed by the start of the block.
435 IRBuilder<> Builder(BI);
436
437 // Now that we have full information about ranges, loop over the ranges and
438 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000439 Instruction *AMemSet = nullptr;
Chris Lattnerc6381472011-01-08 20:24:01 +0000440 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
441 I != E; ++I) {
442 const MemsetRange &Range = *I;
Nadav Rotem465834c2012-07-24 10:51:42 +0000443
Chris Lattnerc6381472011-01-08 20:24:01 +0000444 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000445
Chris Lattnerc6381472011-01-08 20:24:01 +0000446 // If it is profitable to lower this range to memset, do so now.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000447 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000448 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000449
Chris Lattnerc6381472011-01-08 20:24:01 +0000450 // Otherwise, we do want to transform this! Create a new memset.
451 // Get the starting pointer of the block.
452 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000453
Chris Lattnerc6381472011-01-08 20:24:01 +0000454 // Determine alignment
455 unsigned Alignment = Range.Alignment;
456 if (Alignment == 0) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000457 Type *EltType =
Chris Lattnerc6381472011-01-08 20:24:01 +0000458 cast<PointerType>(StartPtr->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 Alignment = DL.getABITypeAlignment(EltType);
Chris Lattnerc6381472011-01-08 20:24:01 +0000460 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000461
462 AMemSet =
Chris Lattnerc6381472011-01-08 20:24:01 +0000463 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000464
Chris Lattnerc6381472011-01-08 20:24:01 +0000465 DEBUG(dbgs() << "Replace stores:\n";
466 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
467 dbgs() << *Range.TheStores[i] << '\n';
468 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000469
470 if (!Range.TheStores.empty())
471 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
472
Chris Lattnerc6381472011-01-08 20:24:01 +0000473 // Zap all the stores.
Craig Topper31ee5862013-07-03 15:07:05 +0000474 for (SmallVectorImpl<Instruction *>::const_iterator
Chris Lattnerc6381472011-01-08 20:24:01 +0000475 SI = Range.TheStores.begin(),
Chris Lattner7d6433a2011-01-08 22:19:21 +0000476 SE = Range.TheStores.end(); SI != SE; ++SI) {
477 MD->removeInstruction(*SI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000478 (*SI)->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000479 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000480 ++NumMemSetInfer;
481 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000482
Chris Lattnerc6381472011-01-08 20:24:01 +0000483 return AMemSet;
484}
485
486
Chris Lattnerb5557a72009-09-01 17:09:55 +0000487bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000488 if (!SI->isSimple()) return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000490
491 // Detect cases where we're performing call slot forwarding, but
492 // happen to be using a load-store pair to implement it, rather than
493 // a memcpy.
494 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000495 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000496 LI->getParent() == SI->getParent()) {
Eli Friedman5da0ff42011-06-02 21:24:42 +0000497 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000498 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000499 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
500 C = dyn_cast<CallInst>(ldep.getInst());
501
502 if (C) {
503 // Check that nothing touches the dest of the "copy" between
504 // the call and the store.
Eli Friedmane8bbc102011-06-15 01:25:56 +0000505 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000506 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Eli Friedmane8bbc102011-06-15 01:25:56 +0000507 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
508 E = C; I != E; --I) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000509 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000510 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000511 break;
512 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000513 }
514 }
515
Owen Anderson18e4fed2010-10-15 22:52:12 +0000516 if (C) {
Duncan Sandsc6ada692012-10-04 10:54:40 +0000517 unsigned storeAlign = SI->getAlignment();
518 if (!storeAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000519 storeAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
Duncan Sandsc6ada692012-10-04 10:54:40 +0000520 unsigned loadAlign = LI->getAlignment();
521 if (!loadAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000522 loadAlign = DL.getABITypeAlignment(LI->getType());
Duncan Sandsc6ada692012-10-04 10:54:40 +0000523
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000524 bool changed = performCallSlotOptzn(
525 LI, SI->getPointerOperand()->stripPointerCasts(),
526 LI->getPointerOperand()->stripPointerCasts(),
527 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
528 std::min(storeAlign, loadAlign), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000529 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000530 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000531 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000532 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000533 LI->eraseFromParent();
534 ++NumMemCpyInstr;
535 return true;
536 }
537 }
538 }
539 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000540
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000541 // There are two cases that are interesting for this code to handle: memcpy
542 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000543
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000544 // Ensure that the value being stored is something that can be memset'able a
545 // byte at a time like "0" or "-1" or any width, as well as things like
546 // 0xA0A0A0A0 and 0.0.
Chris Lattnerc6381472011-01-08 20:24:01 +0000547 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
548 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
549 ByteVal)) {
550 BBI = I; // Don't invalidate iterator.
551 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000552 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000553
Chris Lattnerc6381472011-01-08 20:24:01 +0000554 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000555}
556
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000557bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
558 // See if there is another memset or store neighboring this memset which
559 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000560 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
561 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
562 MSI->getValue())) {
563 BBI = I; // Don't invalidate iterator.
564 return true;
565 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000566 return false;
567}
568
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000569
570/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
571/// and checks for the possibility of a call slot optimization by having
572/// the call write its result directly into the destination of the memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000573bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
574 Value *cpyDest, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000575 uint64_t cpyLen, unsigned cpyAlign,
576 CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000577 // The general transformation to keep in mind is
578 //
579 // call @func(..., src, ...)
580 // memcpy(dest, src, ...)
581 //
582 // ->
583 //
584 // memcpy(dest, src, ...)
585 // call @func(..., dest, ...)
586 //
587 // Since moving the memcpy is technically awkward, we additionally check that
588 // src only holds uninitialized values at the moment of the call, meaning that
589 // the memcpy can be discarded rather than moved.
590
591 // Deliberately get the source and destination with bitcasts stripped away,
592 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000593 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000594
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000595 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000596 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000597 if (!srcAlloca)
598 return false;
599
Chris Lattnerb5557a72009-09-01 17:09:55 +0000600 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000601 if (!srcArraySize)
602 return false;
603
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 const DataLayout &DL = cpy->getModule()->getDataLayout();
605 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
606 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000607
Owen Anderson18e4fed2010-10-15 22:52:12 +0000608 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000609 return false;
610
611 // Check that accessing the first srcSize bytes of dest will not cause a
612 // trap. Otherwise the transform is invalid since it might cause a trap
613 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000614 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000615 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000616 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000617 if (!destArraySize)
618 return false;
619
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000620 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
621 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000622
623 if (destSize < srcSize)
624 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000625 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000626 if (A->getDereferenceableBytes() < srcSize) {
627 // If the destination is an sret parameter then only accesses that are
628 // outside of the returned struct type can trap.
629 if (!A->hasStructRetAttr())
630 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000631
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000632 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
633 if (!StructTy->isSized()) {
634 // The call may never return and hence the copy-instruction may never
635 // be executed, and therefore it's not safe to say "the destination
636 // has at least <cpyLen> bytes, as implied by the copy-instruction",
637 return false;
638 }
639
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000640 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000641 if (destSize < srcSize)
642 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000643 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000644 } else {
645 return false;
646 }
647
Duncan Sands933db772012-10-05 07:29:46 +0000648 // Check that dest points to memory that is at least as aligned as src.
649 unsigned srcAlign = srcAlloca->getAlignment();
650 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000651 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000652 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
653 // If dest is not aligned enough and we can't increase its alignment then
654 // bail out.
655 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
656 return false;
657
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000658 // Check that src is not accessed except via the call and the memcpy. This
659 // guarantees that it holds only undefined values when passed in (so the final
660 // memcpy can be dropped), that it is not read or written between the call and
661 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000662 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
663 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000664 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000665 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000666
Chandler Carruthcdf47882014-03-09 03:16:01 +0000667 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
668 for (User *UU : U->users())
669 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000670 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000671 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000672 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
673 if (!G->hasAllZeroIndices())
674 return false;
675
676 for (User *UU : U->users())
677 srcUseList.push_back(UU);
678 continue;
679 }
680 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
681 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
682 IT->getIntrinsicID() == Intrinsic::lifetime_end)
683 continue;
684
685 if (U != C && U != cpy)
686 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000687 }
688
Nick Lewycky703e4882014-07-14 18:52:02 +0000689 // Check that src isn't captured by the called function since the
690 // transformation can cause aliasing issues in that case.
691 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
692 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
693 return false;
694
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000695 // Since we're changing the parameter to the callsite, we need to make sure
696 // that what would be the new parameter dominates the callsite.
Chandler Carruth73523022014-01-13 13:07:17 +0000697 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000698 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000699 if (!DT.dominates(cpyDestInst, C))
700 return false;
701
702 // In addition to knowing that the call does not access src in some
703 // unexpected manner, for example via a global, which we deduce from
704 // the use analysis, we also need to know that it does not sneakily
705 // access dest. We rely on AA to figure this out for us.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000706 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chandler Carruth194f59c2015-07-22 23:15:57 +0000707 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
Chad Rosiera968caf2012-05-14 20:35:04 +0000708 // If necessary, perform additional analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000709 if (MR != MRI_NoModRef)
Chad Rosiera968caf2012-05-14 20:35:04 +0000710 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000711 if (MR != MRI_NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000712 return false;
713
714 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000715 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000716 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000717 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000718 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
719 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
720 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000721 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000722 if (CS.getArgument(i)->getType() == Dest->getType())
723 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000724 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000725 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
726 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000727 }
728
Owen Andersond071a872008-06-01 21:52:16 +0000729 if (!changedArgument)
730 return false;
731
Duncan Sandsc6ada692012-10-04 10:54:40 +0000732 // If the destination wasn't sufficiently aligned then increase its alignment.
733 if (!isDestSufficientlyAligned) {
734 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
735 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
736 }
737
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000738 // Drop any cached information about the call, because we may have changed
739 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000740 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000741
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000742 // Update AA metadata
743 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
744 // handled here, but combineMetadata doesn't support them yet
745 unsigned KnownIDs[] = {
746 LLVMContext::MD_tbaa,
747 LLVMContext::MD_alias_scope,
748 LLVMContext::MD_noalias,
749 };
750 combineMetadata(C, cpy, KnownIDs);
751
Chris Lattner58f9f582010-11-21 00:28:59 +0000752 // Remove the memcpy.
753 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000754 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000755
756 return true;
757}
758
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000759/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
760/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000761/// copy from MDep's input if we can.
Nadav Rotem465834c2012-07-24 10:51:42 +0000762///
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000763bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000764 // We can only transforms memcpy's where the dest of one is the source of the
765 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000766 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000767 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000768
Chris Lattnerfd51c522010-12-09 07:39:50 +0000769 // If dep instruction is reading from our current input, then it is a noop
770 // transfer and substituting the input won't change this instruction. Just
771 // ignore the input and let someone else zap MDep. This handles cases like:
772 // memcpy(a <- a)
773 // memcpy(b <- a)
774 if (M->getSource() == MDep->getSource())
775 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000776
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000777 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000778 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000779 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
780 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
781 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
782 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000783
Chris Lattner58f9f582010-11-21 00:28:59 +0000784 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner59572292010-11-21 08:06:10 +0000785
786 // Verify that the copied-from memory doesn't change in between the two
787 // transfers. For example, in:
788 // memcpy(a <- b)
789 // *b = 42;
790 // memcpy(c <- a)
791 // It would be invalid to transform the second memcpy into memcpy(c <- b).
792 //
793 // TODO: If the code between M and MDep is transparent to the destination "c",
794 // then we could still perform the xform by moving M up to the first memcpy.
795 //
796 // NOTE: This is conservative, it will stop on any read from the source loc,
797 // not just the defining memcpy.
Chandler Carruth70c61c12015-06-04 02:03:15 +0000798 MemDepResult SourceDep = MD->getPointerDependencyFrom(
799 MemoryLocation::getForSource(MDep), false, M, M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +0000800 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
801 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000802
Chris Lattner731caac2010-11-18 08:00:57 +0000803 // If the dest of the second might alias the source of the first, then the
804 // source and dest might overlap. We still want to eliminate the intermediate
805 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000806 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +0000807 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
808 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000809 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000810
Chris Lattner58f9f582010-11-21 00:28:59 +0000811 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +0000812
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000813 // Make sure to use the lesser of the alignment of the source and the dest
814 // since we're changing where we're reading from, but don't want to increase
815 // the alignment past what can be read from or written to.
816 // TODO: Is this worth it if we're creating a less aligned memcpy? For
817 // example we could be moving from movaps -> movq on x86.
Chris Lattner1385dff2010-11-18 08:07:09 +0000818 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotem465834c2012-07-24 10:51:42 +0000819
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000820 IRBuilder<> Builder(M);
821 if (UseMemMove)
822 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
823 Align, M->isVolatile());
824 else
825 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
826 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +0000827
Chris Lattner59572292010-11-21 08:06:10 +0000828 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +0000829 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +0000830 M->eraseFromParent();
831 ++NumMemCpyInstr;
832 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000833}
834
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000835/// We've found that the (upward scanning) memory dependence of \p MemCpy is
836/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
837/// weren't copied over by \p MemCpy.
838///
839/// In other words, transform:
840/// \code
841/// memset(dst, c, dst_size);
842/// memcpy(dst, src, src_size);
843/// \endcode
844/// into:
845/// \code
846/// memcpy(dst, src, src_size);
847/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
848/// \endcode
849bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
850 MemSetInst *MemSet) {
851 // We can only transform memset/memcpy with the same destination.
852 if (MemSet->getDest() != MemCpy->getDest())
853 return false;
854
Ahmed Bougacha97876fa2015-05-21 01:43:39 +0000855 // Check that there are no other dependencies on the memset destination.
Chandler Carruth70c61c12015-06-04 02:03:15 +0000856 MemDepResult DstDepInfo = MD->getPointerDependencyFrom(
857 MemoryLocation::getForDest(MemSet), false, MemCpy, MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +0000858 if (DstDepInfo.getInst() != MemSet)
859 return false;
860
Ahmed Bougacha9692e302015-04-21 21:28:33 +0000861 // Use the same i8* dest as the memcpy, killing the memset dest if different.
862 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000863 Value *DestSize = MemSet->getLength();
864 Value *SrcSize = MemCpy->getLength();
865
866 // By default, create an unaligned memset.
867 unsigned Align = 1;
868 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
869 // of the sum.
870 const unsigned DestAlign =
871 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
872 if (DestAlign > 1)
873 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
874 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
875
Ahmed Bougacha97876fa2015-05-21 01:43:39 +0000876 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000877
Ahmed Bougacha05b72c12015-04-18 23:06:04 +0000878 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +0000879 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +0000880 if (DestSize->getType()->getIntegerBitWidth() >
881 SrcSize->getType()->getIntegerBitWidth())
882 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
883 else
884 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +0000885 }
886
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000887 Value *MemsetLen =
888 Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
889 ConstantInt::getNullValue(DestSize->getType()),
890 Builder.CreateSub(DestSize, SrcSize));
891 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
892 MemsetLen, Align);
893
894 MD->removeInstruction(MemSet);
895 MemSet->eraseFromParent();
896 return true;
897}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000898
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000899/// Transform memcpy to memset when its source was just memset.
900/// In other words, turn:
901/// \code
902/// memset(dst1, c, dst1_size);
903/// memcpy(dst2, dst1, dst2_size);
904/// \endcode
905/// into:
906/// \code
907/// memset(dst1, c, dst1_size);
908/// memset(dst2, c, dst2_size);
909/// \endcode
910/// When dst2_size <= dst1_size.
911///
912/// The \p MemCpy must have a Constant length.
913bool MemCpyOpt::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
914 MemSetInst *MemSet) {
915 // This only makes sense on memcpy(..., memset(...), ...).
916 if (MemSet->getRawDest() != MemCpy->getRawSource())
917 return false;
918
919 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
920 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
921 // Make sure the memcpy doesn't read any more than what the memset wrote.
922 // Don't worry about sizes larger than i64.
923 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
924 return false;
925
Ahmed Bougacha0541c672015-05-21 00:08:35 +0000926 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000927 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
928 CopySize, MemCpy->getAlignment());
929 return true;
930}
931
Gabor Greif62f0aac2010-07-28 22:50:26 +0000932/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
933/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
934/// B to be a memcpy from X to Z (or potentially a memmove, depending on
935/// circumstances). This allows later passes to remove the first memcpy
936/// altogether.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000937bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +0000938 // We can only optimize non-volatile memcpy's.
939 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +0000940
Chris Lattnerbc4457e2010-12-09 07:45:45 +0000941 // If the source and destination of the memcpy are the same, then zap it.
942 if (M->getSource() == M->getDest()) {
943 MD->removeInstruction(M);
944 M->eraseFromParent();
945 return false;
946 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +0000947
948 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000949 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +0000950 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000951 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000952 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +0000953 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000954 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000955 MD->removeInstruction(M);
956 M->eraseFromParent();
957 ++NumCpyToSet;
958 return true;
959 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +0000960
Ahmed Bougachab6169662015-05-11 23:09:46 +0000961 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000962
963 // Try to turn a partially redundant memset + memcpy into
964 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +0000965 if (DepInfo.isClobber())
966 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000967 if (processMemSetMemCpyDependence(M, MDep))
968 return true;
969
Nick Lewycky00703e72014-02-04 00:18:54 +0000970 // The optimizations after this point require the memcpy size.
971 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000972 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +0000973
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000974 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +0000975 // a) memcpy-memcpy xform which exposes redundance for DSE.
976 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +0000977 // c) memcpy from freshly alloca'd space or space that has just started its
978 // lifetime copies undefined data, and we can therefore eliminate the
979 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000980 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000981 if (DepInfo.isClobber()) {
982 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
983 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsc6ada692012-10-04 10:54:40 +0000984 CopySize->getZExtValue(), M->getAlignment(),
985 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000986 MD->removeInstruction(M);
987 M->eraseFromParent();
988 return true;
989 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +0000990 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000991 }
Ahmed Charles32e983e2012-02-13 06:30:56 +0000992
Chandler Carruthac80dc72015-06-17 07:18:54 +0000993 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Ahmed Bougachab6169662015-05-11 23:09:46 +0000994 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
995 M, M->getParent());
996
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000997 if (SrcDepInfo.isClobber()) {
998 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000999 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001000 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001001 Instruction *I = SrcDepInfo.getInst();
1002 bool hasUndefContents = false;
1003
1004 if (isa<AllocaInst>(I)) {
1005 hasUndefContents = true;
1006 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1007 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1008 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1009 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1010 hasUndefContents = true;
1011 }
1012
1013 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +00001014 MD->removeInstruction(M);
1015 M->eraseFromParent();
1016 ++NumMemCpyInstr;
1017 return true;
1018 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001019 }
1020
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001021 if (SrcDepInfo.isClobber())
1022 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1023 if (performMemCpyToMemSetOptzn(M, MDep)) {
1024 MD->removeInstruction(M);
1025 M->eraseFromParent();
1026 ++NumCpyToSet;
1027 return true;
1028 }
1029
Owen Andersonad5367f2008-04-29 21:51:00 +00001030 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001031}
1032
Chris Lattner1145e332009-09-01 17:56:32 +00001033/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
1034/// are guaranteed not to alias.
1035bool MemCpyOpt::processMemMove(MemMoveInst *M) {
1036 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1037
Chris Lattner23f61a02011-05-01 18:27:11 +00001038 if (!TLI->has(LibFunc::memmove))
1039 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001040
Chris Lattner1145e332009-09-01 17:56:32 +00001041 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001042 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1043 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001044 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001045
David Greene24199232010-01-05 01:27:47 +00001046 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001047
Chris Lattner1145e332009-09-01 17:56:32 +00001048 // If not, then we know we can transform this.
1049 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +00001050 Type *ArgTys[3] = { M->getRawDest()->getType(),
1051 M->getRawSource()->getType(),
1052 M->getLength()->getType() };
Gabor Greif3e44ea12010-07-22 10:37:47 +00001053 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramere6e19332011-07-14 17:45:39 +00001054 ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001055
Chris Lattner1145e332009-09-01 17:56:32 +00001056 // MemDep may have over conservative information about this instruction, just
1057 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001058 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001059
1060 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001061 return true;
1062}
Nadav Rotem465834c2012-07-24 10:51:42 +00001063
Chris Lattner58f9f582010-11-21 00:28:59 +00001064/// processByValArgument - This is called on every byval argument in call sites.
1065bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001066 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001067 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001068 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001069 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001070 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001071 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1072 MemoryLocation(ByValArg, ByValSize), true, CS.getInstruction(),
1073 CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001074 if (!DepInfo.isClobber())
1075 return false;
1076
1077 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1078 // a memcpy, see if we can byval from the source of the memcpy instead of the
1079 // result.
1080 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001081 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001082 ByValArg->stripPointerCasts() != MDep->getDest())
1083 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001084
Chris Lattner58f9f582010-11-21 00:28:59 +00001085 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001086 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001087 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001088 return false;
1089
Chris Lattner83791ce2011-05-23 00:03:39 +00001090 // Get the alignment of the byval. If the call doesn't specify the alignment,
1091 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +00001092 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +00001093 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001094
Chris Lattner83791ce2011-05-23 00:03:39 +00001095 // If it is greater than the memcpy, then we check to see if we can force the
1096 // source of the memcpy to the alignment we need. If we fail, we bail out.
Chandler Carruth66b31302015-01-04 12:03:27 +00001097 AssumptionCache &AC =
1098 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
1099 *CS->getParent()->getParent());
Hal Finkel60db0582014-09-07 18:57:58 +00001100 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattner83791ce2011-05-23 00:03:39 +00001101 if (MDep->getAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001102 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1103 CS.getInstruction(), &AC, &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001104 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001105
Chris Lattner58f9f582010-11-21 00:28:59 +00001106 // Verify that the copied-from memory doesn't change in between the memcpy and
1107 // the byval call.
1108 // memcpy(a <- b)
1109 // *b = 42;
1110 // foo(*a)
1111 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001112 //
1113 // NOTE: This is conservative, it will stop on any read from the source loc,
1114 // not just the defining memcpy.
1115 MemDepResult SourceDep =
Chandler Carruth70c61c12015-06-04 02:03:15 +00001116 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1117 CS.getInstruction(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001118 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1119 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001120
Chris Lattner58f9f582010-11-21 00:28:59 +00001121 Value *TmpCast = MDep->getSource();
1122 if (MDep->getSource()->getType() != ByValArg->getType())
1123 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1124 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001125
Chris Lattner58f9f582010-11-21 00:28:59 +00001126 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
1127 << " " << *MDep << "\n"
1128 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001129
Chris Lattner58f9f582010-11-21 00:28:59 +00001130 // Otherwise we're good! Update the byval argument.
1131 CS.setArgument(ArgNo, TmpCast);
1132 ++NumMemCpyInstr;
1133 return true;
1134}
1135
1136/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001137bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001138 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001139
Chris Lattnerb5557a72009-09-01 17:09:55 +00001140 // Walk all instruction in the function.
Owen Anderson6a7355c2008-04-21 07:45:10 +00001141 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001142 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001143 // Avoid invalidating the iterator.
1144 Instruction *I = BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001145
Chris Lattner58f9f582010-11-21 00:28:59 +00001146 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001147
Owen Anderson6a7355c2008-04-21 07:45:10 +00001148 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001149 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001150 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1151 RepeatInstruction = processMemSet(M, BI);
1152 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001153 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001154 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001155 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001156 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001157 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001158 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001159 MadeChange |= processByValArgument(CS, i);
1160 }
1161
1162 // Reprocess the instruction if desired.
1163 if (RepeatInstruction) {
Chris Lattner7d6433a2011-01-08 22:19:21 +00001164 if (BI != BB->begin()) --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001165 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001166 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001167 }
1168 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001169
Chris Lattnerb5557a72009-09-01 17:09:55 +00001170 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001171}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001172
1173// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1174// function.
1175//
1176bool MemCpyOpt::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001177 if (skipOptnoneFunction(F))
1178 return false;
1179
Chris Lattnerb5557a72009-09-01 17:09:55 +00001180 bool MadeChange = false;
Chris Lattner58f9f582010-11-21 00:28:59 +00001181 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001182 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nadav Rotem465834c2012-07-24 10:51:42 +00001183
Chris Lattner23f61a02011-05-01 18:27:11 +00001184 // If we don't have at least memset and memcpy, there is little point of doing
1185 // anything here. These are required by a freestanding implementation, so if
1186 // even they are disabled, there is no point in trying hard.
1187 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1188 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001189
Chris Lattnerb5557a72009-09-01 17:09:55 +00001190 while (1) {
1191 if (!iterateOnFunction(F))
1192 break;
1193 MadeChange = true;
1194 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001195
Craig Topperf40110f2014-04-25 05:29:35 +00001196 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001197 return MadeChange;
1198}