blob: 3ab892f752938db05d6c816f96bdbc9e8f33f341 [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"
Amaury Sechetbdb261b2016-03-14 22:52:27 +000016#include "llvm/ADT/DenseSet.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000020#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000021#include "llvm/Analysis/GlobalsModRef.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000022#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000027#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000032#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000034#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyf836c892015-07-21 21:56:26 +000035#include <algorithm>
Owen Andersonef9a6fd2008-04-09 08:23:16 +000036using namespace llvm;
37
Chandler Carruth964daaa2014-04-22 02:55:47 +000038#define DEBUG_TYPE "memcpyopt"
39
Owen Andersonef9a6fd2008-04-09 08:23:16 +000040STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
41STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000042STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000043STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000044
Benjamin Kramer15a257d2012-09-13 16:29:49 +000045static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000046 bool &VariableIdxFound,
47 const DataLayout &DL) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000048 // Skip over the first indices.
49 gep_type_iterator GTI = gep_type_begin(GEP);
50 for (unsigned i = 1; i != Idx; ++i, ++GTI)
51 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000052
Owen Andersonef9a6fd2008-04-09 08:23:16 +000053 // Compute the offset implied by the rest of the indices.
54 int64_t Offset = 0;
55 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
56 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +000057 if (!OpC)
Owen Andersonef9a6fd2008-04-09 08:23:16 +000058 return VariableIdxFound = true;
59 if (OpC->isZero()) continue; // No offset.
60
61 // Handle struct indices, which add their field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +000062 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000063 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000064 continue;
65 }
Nadav Rotem465834c2012-07-24 10:51:42 +000066
Owen Andersonef9a6fd2008-04-09 08:23:16 +000067 // Otherwise, we have a sequential type like an array or vector. Multiply
68 // the index by the ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000069 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000070 Offset += Size*OpC->getSExtValue();
71 }
72
73 return Offset;
74}
75
Sanjay Patela75c41e2015-08-13 22:53:20 +000076/// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
77/// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
78/// might be &A[40]. In this case offset would be -8.
Owen Andersonef9a6fd2008-04-09 08:23:16 +000079static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000080 const DataLayout &DL) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +000081 Ptr1 = Ptr1->stripPointerCasts();
82 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer3ef5e462014-03-10 21:05:13 +000083
84 // Handle the trivial case first.
85 if (Ptr1 == Ptr2) {
86 Offset = 0;
87 return true;
88 }
89
Benjamin Kramer15a257d2012-09-13 16:29:49 +000090 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
91 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +000092
Chris Lattner5120ebf2011-01-08 21:07:56 +000093 bool VariableIdxFound = false;
94
95 // If one pointer is a GEP and the other isn't, then see if the GEP is a
96 // constant offset from the base, as in "P" and "gep P, 1".
Craig Topperf40110f2014-04-25 05:29:35 +000097 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000098 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +000099 return !VariableIdxFound;
100 }
101
Craig Topperf40110f2014-04-25 05:29:35 +0000102 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000103 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +0000104 return !VariableIdxFound;
105 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000106
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000107 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
108 // base. After that base, they may have some number of common (and
109 // potentially variable) indices. After that they handle some constant
110 // offset, which determines their offset from each other. At this point, we
111 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000112 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
113 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000114
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000115 // Skip any common indices and track the GEP types.
116 unsigned Idx = 1;
117 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
118 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
119 break;
120
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000121 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
122 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000123 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000124
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000125 Offset = Offset2-Offset1;
126 return true;
127}
128
129
Sanjay Patela75c41e2015-08-13 22:53:20 +0000130/// Represents a range of memset'd bytes with the ByteVal value.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000131/// This allows us to analyze stores like:
132/// store 0 -> P+1
133/// store 0 -> P+0
134/// store 0 -> P+3
135/// store 0 -> P+2
136/// which sometimes happens with stores to arrays of structs etc. When we see
137/// the first store, we make a range [1, 2). The second store extends the range
138/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
139/// two ranges into [0, 3) which is memset'able.
140namespace {
Tim Northover39617352016-05-10 21:49:40 +0000141struct MemsetRange {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000142 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000143 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000144 int64_t Start, End;
145
146 /// StartPtr - The getelementptr instruction that points to the start of the
147 /// range.
Tim Northover39617352016-05-10 21:49:40 +0000148 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000149
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000150 /// Alignment - The known alignment of the first store.
151 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000152
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000153 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000154 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000155
Tim Northover39617352016-05-10 21:49:40 +0000156 bool isProfitableToUseMemset(const DataLayout &DL) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000157};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000158} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000159
Tim Northover39617352016-05-10 21:49:40 +0000160bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
161 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000162 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000163
164 // If there is nothing to merge, don't do anything.
165 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000166
Tim Northover39617352016-05-10 21:49:40 +0000167 // If any of the stores are a memset, then it is always good to extend the
168 // memset.
Craig Toppere325e382015-11-20 07:18:48 +0000169 for (Instruction *SI : TheStores)
Tim Northover39617352016-05-10 21:49:40 +0000170 if (!isa<StoreInst>(SI))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000171 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000172
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000173 // Assume that the code generator is capable of merging pairs of stores
174 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000175 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000176
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000177 // If we have fewer than 8 stores, it can still be worthwhile to do this.
178 // For example, merging 4 i8 stores into an i32 store is useful almost always.
179 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
180 // memset will be split into 2 32-bit stores anyway) and doing so can
181 // pessimize the llvm optimizer.
182 //
183 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000184 // the maximum GPR width is the same size as the largest legal integer
185 // size. If so, check to see whether we will end up actually reducing the
186 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000187 unsigned Bytes = unsigned(End-Start);
Jun Bum Limbe11bdc2016-05-13 18:38:35 +0000188 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
Matt Arsenault899f7d22013-09-16 22:43:16 +0000189 if (MaxIntSize == 0)
190 MaxIntSize = 1;
191 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000192
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000193 // Assume the remaining bytes if any are done a byte at a time.
Craig Toppera5ea5282015-11-21 17:44:42 +0000194 unsigned NumByteStores = Bytes % MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000195
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000196 // If we will reduce the # stores (according to this heuristic), do the
197 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
198 // etc.
199 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000200}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000201
202
203namespace {
Tim Northover39617352016-05-10 21:49:40 +0000204class MemsetRanges {
Sanjay Patela75c41e2015-08-13 22:53:20 +0000205 /// A sorted list of the memset ranges.
Tim Northover39617352016-05-10 21:49:40 +0000206 SmallVector<MemsetRange, 8> Ranges;
207 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000208 const DataLayout &DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000209public:
Tim Northover39617352016-05-10 21:49:40 +0000210 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000211
Tim Northover39617352016-05-10 21:49:40 +0000212 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000213 const_iterator begin() const { return Ranges.begin(); }
214 const_iterator end() const { return Ranges.end(); }
215 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000216
Chris Lattnerc6381472011-01-08 20:24:01 +0000217 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000218 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
219 addStore(OffsetFromFirst, SI);
220 else
221 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000222 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000223
224 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000225 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000226
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000227 addRange(OffsetFromFirst, StoreSize,
Tim Northover39617352016-05-10 21:49:40 +0000228 SI->getPointerOperand(), SI->getAlignment(), SI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000229 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000230
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000231 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
232 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Tim Northover39617352016-05-10 21:49:40 +0000233 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000234 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000235
Tim Northover39617352016-05-10 21:49:40 +0000236 void addRange(int64_t Start, int64_t Size, Value *Ptr,
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000237 unsigned Alignment, Instruction *Inst);
238
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000239};
Nadav Rotem465834c2012-07-24 10:51:42 +0000240
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000241} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000242
243
Tim Northover39617352016-05-10 21:49:40 +0000244/// Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000245/// new range for the specified store at the specified offset, merging into
246/// existing ranges as appropriate.
Tim Northover39617352016-05-10 21:49:40 +0000247void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
248 unsigned Alignment, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000249 int64_t End = Start+Size;
Nadav Rotem465834c2012-07-24 10:51:42 +0000250
Nick Lewyckyf836c892015-07-21 21:56:26 +0000251 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
Tim Northover39617352016-05-10 21:49:40 +0000252 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
Nadav Rotem465834c2012-07-24 10:51:42 +0000253
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000254 // We now know that I == E, in which case we didn't find anything to merge
255 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
256 // to insert a new range. Handle this now.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000257 if (I == Ranges.end() || End < I->Start) {
Tim Northover39617352016-05-10 21:49:40 +0000258 MemsetRange &R = *Ranges.insert(I, MemsetRange());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000259 R.Start = Start;
260 R.End = End;
Tim Northover39617352016-05-10 21:49:40 +0000261 R.StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000262 R.Alignment = Alignment;
263 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000264 return;
265 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000266
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000267 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000268 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000269
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000270 // At this point, we may have an interval that completely contains our store.
271 // If so, just add it to the interval and return.
272 if (I->Start <= Start && I->End >= End)
273 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000274
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000275 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
276 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000277
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000278 // See if the range extends the start of the range. In this case, it couldn't
279 // possibly cause it to join the prior range, because otherwise we would have
280 // stopped on *it*.
281 if (Start < I->Start) {
282 I->Start = Start;
Tim Northover39617352016-05-10 21:49:40 +0000283 I->StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000284 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000285 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000286
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000287 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
288 // is in or right at the end of I), and that End >= I->Start. Extend I out to
289 // End.
290 if (End > I->End) {
291 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000292 range_iterator NextI = I;
Nick Lewyckyf836c892015-07-21 21:56:26 +0000293 while (++NextI != Ranges.end() && End >= NextI->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000294 // Merge the range in.
295 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
296 if (NextI->End > I->End)
297 I->End = NextI->End;
298 Ranges.erase(NextI);
299 NextI = I;
300 }
301 }
302}
303
304//===----------------------------------------------------------------------===//
305// MemCpyOpt Pass
306//===----------------------------------------------------------------------===//
307
308namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000309 class MemCpyOpt : public FunctionPass {
Chandler Carruth61440d22016-03-10 00:55:30 +0000310 MemoryDependenceResults *MD;
Chris Lattner23f61a02011-05-01 18:27:11 +0000311 TargetLibraryInfo *TLI;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000312 public:
313 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000314 MemCpyOpt() : FunctionPass(ID) {
315 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Craig Topperf40110f2014-04-25 05:29:35 +0000316 MD = nullptr;
317 TLI = nullptr;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000318 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000319
Craig Topper3e4c6972014-03-05 09:10:37 +0000320 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000321
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000322 private:
323 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000324 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000325 AU.setPreservesCFG();
Chandler Carruth66b31302015-01-04 12:03:27 +0000326 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000327 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000328 AU.addRequired<MemoryDependenceWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000329 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000330 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000331 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000332 AU.addPreserved<MemoryDependenceWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000333 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000334
Matt Walaa4afccd2015-06-12 18:16:51 +0000335 // Helper functions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000336 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000337 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Tim Northover39617352016-05-10 21:49:40 +0000338 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000339 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000340 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000341 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000342 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000343 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000344 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
Chris Lattner58f9f582010-11-21 00:28:59 +0000345 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000346 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
347 Value *ByteVal);
348
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000349 bool iterateOnFunction(Function &F);
350 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000351
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000352 char MemCpyOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000353}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000354
Sanjay Patela75c41e2015-08-13 22:53:20 +0000355/// The public interface to this file...
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000356FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
357
Owen Anderson8ac477f2010-10-12 19:48:12 +0000358INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
359 false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000360INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000361INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth61440d22016-03-10 00:55:30 +0000362INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000363INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000364INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
365INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000366INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
367 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000368
Sanjay Patela75c41e2015-08-13 22:53:20 +0000369/// When scanning forward over instructions, we look for some other patterns to
370/// fold away. In particular, this looks for stores to neighboring locations of
371/// memory. If it sees enough consecutive ones, it attempts to merge them
372/// together into a memcpy/memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000373Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattnerc6381472011-01-08 20:24:01 +0000374 Value *StartPtr, Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000375 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000376
Chris Lattnerc6381472011-01-08 20:24:01 +0000377 // Okay, so we now have a single store that can be splatable. Scan to find
378 // all subsequent stores of the same value to offset from the same pointer.
379 // Join these together into ranges, so we can decide whether contiguous blocks
380 // are stored.
Tim Northover39617352016-05-10 21:49:40 +0000381 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000382
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000383 BasicBlock::iterator BI(StartInst);
Chris Lattnerc6381472011-01-08 20:24:01 +0000384 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000385 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
386 // If the instruction is readnone, ignore it, otherwise bail out. We
387 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000388 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000389 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
390 break;
391 continue;
392 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000393
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000394 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
395 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000396 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000397
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000398 // Check to see if this stored value is of the same byte-splattable value.
399 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
400 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000401
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000402 // Check to see if this store is to a constant offset from the start ptr.
403 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000404 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
405 DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000406 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000407
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000408 Ranges.addStore(Offset, NextStore);
409 } else {
410 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000411
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000412 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
413 !isa<ConstantInt>(MSI->getLength()))
414 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000415
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000416 // Check to see if this store is to a constant offset from the start ptr.
417 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000418 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000419 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000420
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000421 Ranges.addMemSet(Offset, MSI);
422 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000423 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000424
Chris Lattnerc6381472011-01-08 20:24:01 +0000425 // If we have no ranges, then we just had a single store with nothing that
426 // could be merged in. This is a very common case of course.
427 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000428 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000429
Chris Lattnerc6381472011-01-08 20:24:01 +0000430 // If we had at least one store that could be merged in, add the starting
431 // store as well. We try to avoid this unless there is at least something
432 // interesting as a small compile-time optimization.
433 Ranges.addInst(0, StartInst);
434
435 // If we create any memsets, we put it right before the first instruction that
436 // isn't part of the memset block. This ensure that the memset is dominated
437 // by any addressing instruction needed by the start of the block.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000438 IRBuilder<> Builder(&*BI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000439
440 // Now that we have full information about ranges, loop over the ranges and
441 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000442 Instruction *AMemSet = nullptr;
Tim Northover39617352016-05-10 21:49:40 +0000443 for (const MemsetRange &Range : Ranges) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000444
Chris Lattnerc6381472011-01-08 20:24:01 +0000445 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000446
Chris Lattnerc6381472011-01-08 20:24:01 +0000447 // If it is profitable to lower this range to memset, do so now.
Tim Northover39617352016-05-10 21:49:40 +0000448 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000449 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000450
Chris Lattnerc6381472011-01-08 20:24:01 +0000451 // Otherwise, we do want to transform this! Create a new memset.
452 // Get the starting pointer of the block.
Tim Northover39617352016-05-10 21:49:40 +0000453 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000454
Tim Northover39617352016-05-10 21:49:40 +0000455 // Determine alignment
456 unsigned Alignment = Range.Alignment;
457 if (Alignment == 0) {
458 Type *EltType =
459 cast<PointerType>(StartPtr->getType())->getElementType();
460 Alignment = DL.getABITypeAlignment(EltType);
461 }
462
463 AMemSet =
464 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000465
Chris Lattnerc6381472011-01-08 20:24:01 +0000466 DEBUG(dbgs() << "Replace stores:\n";
Craig Toppere325e382015-11-20 07:18:48 +0000467 for (Instruction *SI : Range.TheStores)
468 dbgs() << *SI << '\n';
Chris Lattnerc6381472011-01-08 20:24:01 +0000469 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000470
471 if (!Range.TheStores.empty())
472 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
473
Chris Lattnerc6381472011-01-08 20:24:01 +0000474 // Zap all the stores.
Craig Toppere325e382015-11-20 07:18:48 +0000475 for (Instruction *SI : Range.TheStores) {
476 MD->removeInstruction(SI);
477 SI->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000478 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000479 ++NumMemSetInfer;
480 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000481
Chris Lattnerc6381472011-01-08 20:24:01 +0000482 return AMemSet;
483}
484
Tim Northover39617352016-05-10 21:49:40 +0000485static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
486 const LoadInst *LI) {
487 unsigned StoreAlign = SI->getAlignment();
488 if (!StoreAlign)
489 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
490 unsigned LoadAlign = LI->getAlignment();
491 if (!LoadAlign)
492 LoadAlign = DL.getABITypeAlignment(LI->getType());
Amaury Secheta0c242c2016-01-05 20:17:48 +0000493
Tim Northover39617352016-05-10 21:49:40 +0000494 return std::min(StoreAlign, LoadAlign);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000495}
Chris Lattnerc6381472011-01-08 20:24:01 +0000496
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000497// This method try to lift a store instruction before position P.
498// It will lift the store and its argument + that anything that
David Majnemerd99068d2016-05-26 19:24:24 +0000499// may alias with these.
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000500// The method returns true if it was successful.
501static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P) {
502 // If the store alias this position, early bail out.
503 MemoryLocation StoreLoc = MemoryLocation::get(SI);
504 if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef)
505 return false;
506
507 // Keep track of the arguments of all instruction we plan to lift
508 // so we can make sure to lift them as well if apropriate.
509 DenseSet<Instruction*> Args;
510 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
511 if (Ptr->getParent() == SI->getParent())
512 Args.insert(Ptr);
513
514 // Instruction to lift before P.
515 SmallVector<Instruction*, 8> ToLift;
516
517 // Memory locations of lifted instructions.
518 SmallVector<MemoryLocation, 8> MemLocs;
519 MemLocs.push_back(StoreLoc);
520
521 // Lifted callsites.
522 SmallVector<ImmutableCallSite, 8> CallSites;
523
524 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
525 auto *C = &*I;
526
527 bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef;
528
529 bool NeedLift = false;
530 if (Args.erase(C))
531 NeedLift = true;
532 else if (MayAlias) {
533 NeedLift = std::any_of(MemLocs.begin(), MemLocs.end(),
534 [C, &AA](const MemoryLocation &ML) {
535 return AA.getModRefInfo(C, ML);
536 });
537
538 if (!NeedLift)
539 NeedLift = std::any_of(CallSites.begin(), CallSites.end(),
540 [C, &AA](const ImmutableCallSite &CS) {
541 return AA.getModRefInfo(C, CS);
542 });
543 }
544
545 if (!NeedLift)
546 continue;
547
548 if (MayAlias) {
549 if (auto CS = ImmutableCallSite(C)) {
550 // If we can't lift this before P, it's game over.
551 if (AA.getModRefInfo(P, CS) != MRI_NoModRef)
552 return false;
553
554 CallSites.push_back(CS);
555 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
556 // If we can't lift this before P, it's game over.
557 auto ML = MemoryLocation::get(C);
558 if (AA.getModRefInfo(P, ML) != MRI_NoModRef)
559 return false;
560
561 MemLocs.push_back(ML);
562 } else
563 // We don't know how to lift this instruction.
564 return false;
565 }
566
567 ToLift.push_back(C);
568 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
569 if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
570 if (A->getParent() == SI->getParent())
571 Args.insert(A);
572 }
573
574 // We made it, we need to lift
575 for (auto *I : reverse(ToLift)) {
576 DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
577 I->moveBefore(P);
578 }
579
580 return true;
581}
582
Chris Lattnerb5557a72009-09-01 17:09:55 +0000583bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000584 if (!SI->isSimple()) return false;
Andrea Di Biagio99493df2015-10-09 10:53:41 +0000585
586 // Avoid merging nontemporal stores since the resulting
587 // memcpy/memset would not be able to preserve the nontemporal hint.
588 // In theory we could teach how to propagate the !nontemporal metadata to
589 // memset calls. However, that change would force the backend to
590 // conservatively expand !nontemporal memset calls back to sequences of
591 // store instructions (effectively undoing the merging).
592 if (SI->getMetadata(LLVMContext::MD_nontemporal))
593 return false;
594
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000596
Amaury Secheta0c242c2016-01-05 20:17:48 +0000597 // Load to store forwarding can be interpreted as memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000598 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000599 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000600 LI->getParent() == SI->getParent()) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000601
602 auto *T = LI->getType();
603 if (T->isAggregateType()) {
604 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
605 MemoryLocation LoadLoc = MemoryLocation::get(LI);
606
607 // We use alias analysis to check if an instruction may store to
608 // the memory we load from in between the load and the store. If
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000609 // such an instruction is found, we try to promote there instead
610 // of at the store position.
611 Instruction *P = SI;
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000612 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
613 if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) {
614 P = &I;
615 break;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000616 }
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000617 }
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000618
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000619 // We found an instruction that may write to the loaded memory.
620 // We can try to promote at this position instead of the store
621 // position if nothing alias the store memory after this and the store
622 // destination is not in the range.
623 if (P && P != SI) {
624 if (!moveUp(AA, SI, P))
625 P = nullptr;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000626 }
627
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000628 // If a valid insertion position is found, then we can promote
629 // the load/store pair to a memcpy.
630 if (P) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000631 // If we load from memory that may alias the memory we store to,
632 // memmove must be used to preserve semantic. If not, memcpy can
633 // be used.
634 bool UseMemMove = false;
635 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
636 UseMemMove = true;
637
638 unsigned Align = findCommonAlignment(DL, SI, LI);
639 uint64_t Size = DL.getTypeStoreSize(T);
640
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000641 IRBuilder<> Builder(P);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000642 Instruction *M;
643 if (UseMemMove)
644 M = Builder.CreateMemMove(SI->getPointerOperand(),
645 LI->getPointerOperand(), Size,
646 Align, SI->isVolatile());
647 else
648 M = Builder.CreateMemCpy(SI->getPointerOperand(),
649 LI->getPointerOperand(), Size,
650 Align, SI->isVolatile());
651
652 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
653 << " => " << *M << "\n");
654
655 MD->removeInstruction(SI);
656 SI->eraseFromParent();
657 MD->removeInstruction(LI);
658 LI->eraseFromParent();
659 ++NumMemCpyInstr;
660
661 // Make sure we do not invalidate the iterator.
662 BBI = M->getIterator();
663 return true;
664 }
665 }
666
667 // Detect cases where we're performing call slot forwarding, but
668 // happen to be using a load-store pair to implement it, rather than
669 // a memcpy.
Eli Friedman5da0ff42011-06-02 21:24:42 +0000670 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000671 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000672 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
673 C = dyn_cast<CallInst>(ldep.getInst());
674
675 if (C) {
676 // Check that nothing touches the dest of the "copy" between
677 // the call and the store.
David Majnemerd99068d2016-05-26 19:24:24 +0000678 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
679 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000680 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000681 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000682 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
683 I != E; --I) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000684 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000685 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000686 break;
687 }
David Majnemerd99068d2016-05-26 19:24:24 +0000688 // The store to dest may never happen if an exception can be thrown
689 // between the load and the store.
690 if (I->mayThrow() && !CpyDestIsLocal) {
691 C = nullptr;
692 break;
693 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000694 }
695 }
696
Owen Anderson18e4fed2010-10-15 22:52:12 +0000697 if (C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000698 bool changed = performCallSlotOptzn(
699 LI, SI->getPointerOperand()->stripPointerCasts(),
700 LI->getPointerOperand()->stripPointerCasts(),
701 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
Amaury Secheta0c242c2016-01-05 20:17:48 +0000702 findCommonAlignment(DL, SI, LI), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000703 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000704 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000705 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000706 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000707 LI->eraseFromParent();
708 ++NumMemCpyInstr;
709 return true;
710 }
711 }
712 }
713 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000714
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000715 // There are two cases that are interesting for this code to handle: memcpy
716 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000717
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000718 // Ensure that the value being stored is something that can be memset'able a
719 // byte at a time like "0" or "-1" or any width, as well as things like
720 // 0xA0A0A0A0 and 0.0.
Amaury Sechet3235c082016-01-06 19:47:24 +0000721 auto *V = SI->getOperand(0);
722 if (Value *ByteVal = isBytewiseValue(V)) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000723 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
724 ByteVal)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000725 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerc6381472011-01-08 20:24:01 +0000726 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000727 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000728
Amaury Sechet3235c082016-01-06 19:47:24 +0000729 // If we have an aggregate, we try to promote it to memset regardless
730 // of opportunity for merging as it can expose optimization opportunities
731 // in subsequent passes.
732 auto *T = V->getType();
733 if (T->isAggregateType()) {
734 uint64_t Size = DL.getTypeStoreSize(T);
735 unsigned Align = SI->getAlignment();
736 if (!Align)
737 Align = DL.getABITypeAlignment(T);
738 IRBuilder<> Builder(SI);
739 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
740 Size, Align, SI->isVolatile());
741
742 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
743
744 MD->removeInstruction(SI);
745 SI->eraseFromParent();
746 NumMemSetInfer++;
747
748 // Make sure we do not invalidate the iterator.
749 BBI = M->getIterator();
750 return true;
751 }
752 }
753
Chris Lattnerc6381472011-01-08 20:24:01 +0000754 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000755}
756
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000757bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
758 // See if there is another memset or store neighboring this memset which
759 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000760 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
761 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
762 MSI->getValue())) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000763 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000764 return true;
765 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000766 return false;
767}
768
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000769
Sanjay Patela75c41e2015-08-13 22:53:20 +0000770/// Takes a memcpy and a call that it depends on,
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000771/// and checks for the possibility of a call slot optimization by having
772/// the call write its result directly into the destination of the memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000773bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
774 Value *cpyDest, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000775 uint64_t cpyLen, unsigned cpyAlign,
776 CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000777 // The general transformation to keep in mind is
778 //
779 // call @func(..., src, ...)
780 // memcpy(dest, src, ...)
781 //
782 // ->
783 //
784 // memcpy(dest, src, ...)
785 // call @func(..., dest, ...)
786 //
787 // Since moving the memcpy is technically awkward, we additionally check that
788 // src only holds uninitialized values at the moment of the call, meaning that
789 // the memcpy can be discarded rather than moved.
790
Tim Shen7aa0ad62016-06-08 19:42:32 +0000791 // Lifetime marks shouldn't be operated on.
792 if (Function *F = C->getCalledFunction())
793 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
794 return false;
795
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000796 // Deliberately get the source and destination with bitcasts stripped away,
797 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000798 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000799
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000800 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000801 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000802 if (!srcAlloca)
803 return false;
804
Chris Lattnerb5557a72009-09-01 17:09:55 +0000805 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000806 if (!srcArraySize)
807 return false;
808
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000809 const DataLayout &DL = cpy->getModule()->getDataLayout();
810 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
811 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000812
Owen Anderson18e4fed2010-10-15 22:52:12 +0000813 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000814 return false;
815
816 // Check that accessing the first srcSize bytes of dest will not cause a
817 // trap. Otherwise the transform is invalid since it might cause a trap
818 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000819 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000820 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000821 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000822 if (!destArraySize)
823 return false;
824
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
826 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000827
828 if (destSize < srcSize)
829 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000830 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
David Majnemerd99068d2016-05-26 19:24:24 +0000831 // The store to dest may never happen if the call can throw.
832 if (C->mayThrow())
833 return false;
834
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000835 if (A->getDereferenceableBytes() < srcSize) {
836 // If the destination is an sret parameter then only accesses that are
837 // outside of the returned struct type can trap.
838 if (!A->hasStructRetAttr())
839 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000840
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000841 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
842 if (!StructTy->isSized()) {
843 // The call may never return and hence the copy-instruction may never
844 // be executed, and therefore it's not safe to say "the destination
845 // has at least <cpyLen> bytes, as implied by the copy-instruction",
846 return false;
847 }
848
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000849 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000850 if (destSize < srcSize)
851 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000852 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000853 } else {
854 return false;
855 }
856
Duncan Sands933db772012-10-05 07:29:46 +0000857 // Check that dest points to memory that is at least as aligned as src.
858 unsigned srcAlign = srcAlloca->getAlignment();
859 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000860 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000861 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
862 // If dest is not aligned enough and we can't increase its alignment then
863 // bail out.
864 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
865 return false;
866
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000867 // Check that src is not accessed except via the call and the memcpy. This
868 // guarantees that it holds only undefined values when passed in (so the final
869 // memcpy can be dropped), that it is not read or written between the call and
870 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000871 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
872 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000873 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000874 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000875
Chandler Carruthcdf47882014-03-09 03:16:01 +0000876 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
877 for (User *UU : U->users())
878 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000879 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000880 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000881 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
882 if (!G->hasAllZeroIndices())
883 return false;
884
885 for (User *UU : U->users())
886 srcUseList.push_back(UU);
887 continue;
888 }
889 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
890 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
891 IT->getIntrinsicID() == Intrinsic::lifetime_end)
892 continue;
893
894 if (U != C && U != cpy)
895 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000896 }
897
Nick Lewycky703e4882014-07-14 18:52:02 +0000898 // Check that src isn't captured by the called function since the
899 // transformation can cause aliasing issues in that case.
900 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
901 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
902 return false;
903
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000904 // Since we're changing the parameter to the callsite, we need to make sure
905 // that what would be the new parameter dominates the callsite.
Chandler Carruth73523022014-01-13 13:07:17 +0000906 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000907 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000908 if (!DT.dominates(cpyDestInst, C))
909 return false;
910
911 // In addition to knowing that the call does not access src in some
912 // unexpected manner, for example via a global, which we deduce from
913 // the use analysis, we also need to know that it does not sneakily
914 // access dest. We rely on AA to figure this out for us.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000915 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth194f59c2015-07-22 23:15:57 +0000916 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
Chad Rosiera968caf2012-05-14 20:35:04 +0000917 // If necessary, perform additional analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000918 if (MR != MRI_NoModRef)
Chad Rosiera968caf2012-05-14 20:35:04 +0000919 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000920 if (MR != MRI_NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000921 return false;
922
923 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000924 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000925 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000926 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000927 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
928 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
929 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000930 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000931 if (CS.getArgument(i)->getType() == Dest->getType())
932 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000933 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000934 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
935 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000936 }
937
Owen Andersond071a872008-06-01 21:52:16 +0000938 if (!changedArgument)
939 return false;
940
Duncan Sandsc6ada692012-10-04 10:54:40 +0000941 // If the destination wasn't sufficiently aligned then increase its alignment.
942 if (!isDestSufficientlyAligned) {
943 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
944 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
945 }
946
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000947 // Drop any cached information about the call, because we may have changed
948 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000949 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000950
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000951 // Update AA metadata
952 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
953 // handled here, but combineMetadata doesn't support them yet
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +0000954 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
955 LLVMContext::MD_noalias,
956 LLVMContext::MD_invariant_group};
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000957 combineMetadata(C, cpy, KnownIDs);
958
Chris Lattner58f9f582010-11-21 00:28:59 +0000959 // Remove the memcpy.
960 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000961 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000962
963 return true;
964}
965
Sanjay Patela75c41e2015-08-13 22:53:20 +0000966/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
967/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000968bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000969 // We can only transforms memcpy's where the dest of one is the source of the
970 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000971 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000972 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000973
Chris Lattnerfd51c522010-12-09 07:39:50 +0000974 // If dep instruction is reading from our current input, then it is a noop
975 // transfer and substituting the input won't change this instruction. Just
976 // ignore the input and let someone else zap MDep. This handles cases like:
977 // memcpy(a <- a)
978 // memcpy(b <- a)
979 if (M->getSource() == MDep->getSource())
980 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000981
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000982 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000983 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000984 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
985 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
986 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
987 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000988
Chandler Carruth7b560d42015-09-09 17:55:00 +0000989 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chris Lattner59572292010-11-21 08:06:10 +0000990
991 // Verify that the copied-from memory doesn't change in between the two
992 // transfers. For example, in:
993 // memcpy(a <- b)
994 // *b = 42;
995 // memcpy(c <- a)
996 // It would be invalid to transform the second memcpy into memcpy(c <- b).
997 //
998 // TODO: If the code between M and MDep is transparent to the destination "c",
999 // then we could still perform the xform by moving M up to the first memcpy.
1000 //
1001 // NOTE: This is conservative, it will stop on any read from the source loc,
1002 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001003 MemDepResult SourceDep =
1004 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1005 M->getIterator(), M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001006 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1007 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001008
Chris Lattner731caac2010-11-18 08:00:57 +00001009 // If the dest of the second might alias the source of the first, then the
1010 // source and dest might overlap. We still want to eliminate the intermediate
1011 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001012 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +00001013 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1014 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001015 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001016
Chris Lattner58f9f582010-11-21 00:28:59 +00001017 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +00001018
Pete Cooper67cf9a72015-11-19 05:56:52 +00001019 // Make sure to use the lesser of the alignment of the source and the dest
1020 // since we're changing where we're reading from, but don't want to increase
1021 // the alignment past what can be read from or written to.
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001022 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1023 // example we could be moving from movaps -> movq on x86.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001024 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
1025
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001026 IRBuilder<> Builder(M);
1027 if (UseMemMove)
1028 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001029 Align, M->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001030 else
1031 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001032 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +00001033
Chris Lattner59572292010-11-21 08:06:10 +00001034 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +00001035 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +00001036 M->eraseFromParent();
1037 ++NumMemCpyInstr;
1038 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001039}
1040
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001041/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1042/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1043/// weren't copied over by \p MemCpy.
1044///
1045/// In other words, transform:
1046/// \code
1047/// memset(dst, c, dst_size);
1048/// memcpy(dst, src, src_size);
1049/// \endcode
1050/// into:
1051/// \code
1052/// memcpy(dst, src, src_size);
1053/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1054/// \endcode
1055bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1056 MemSetInst *MemSet) {
1057 // We can only transform memset/memcpy with the same destination.
1058 if (MemSet->getDest() != MemCpy->getDest())
1059 return false;
1060
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001061 // Check that there are no other dependencies on the memset destination.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001062 MemDepResult DstDepInfo =
1063 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1064 MemCpy->getIterator(), MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001065 if (DstDepInfo.getInst() != MemSet)
1066 return false;
1067
Ahmed Bougacha9692e302015-04-21 21:28:33 +00001068 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1069 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001070 Value *DestSize = MemSet->getLength();
1071 Value *SrcSize = MemCpy->getLength();
1072
1073 // By default, create an unaligned memset.
1074 unsigned Align = 1;
1075 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1076 // of the sum.
1077 const unsigned DestAlign =
Pete Cooper67cf9a72015-11-19 05:56:52 +00001078 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001079 if (DestAlign > 1)
1080 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1081 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1082
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001083 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001084
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001085 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001086 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001087 if (DestSize->getType()->getIntegerBitWidth() >
1088 SrcSize->getType()->getIntegerBitWidth())
1089 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1090 else
1091 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001092 }
1093
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001094 Value *MemsetLen =
1095 Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
1096 ConstantInt::getNullValue(DestSize->getType()),
1097 Builder.CreateSub(DestSize, SrcSize));
1098 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1099 MemsetLen, Align);
1100
1101 MD->removeInstruction(MemSet);
1102 MemSet->eraseFromParent();
1103 return true;
1104}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001105
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001106/// Transform memcpy to memset when its source was just memset.
1107/// In other words, turn:
1108/// \code
1109/// memset(dst1, c, dst1_size);
1110/// memcpy(dst2, dst1, dst2_size);
1111/// \endcode
1112/// into:
1113/// \code
1114/// memset(dst1, c, dst1_size);
1115/// memset(dst2, c, dst2_size);
1116/// \endcode
1117/// When dst2_size <= dst1_size.
1118///
1119/// The \p MemCpy must have a Constant length.
1120bool MemCpyOpt::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1121 MemSetInst *MemSet) {
1122 // This only makes sense on memcpy(..., memset(...), ...).
1123 if (MemSet->getRawDest() != MemCpy->getRawSource())
1124 return false;
1125
1126 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1127 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1128 // Make sure the memcpy doesn't read any more than what the memset wrote.
1129 // Don't worry about sizes larger than i64.
1130 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1131 return false;
1132
Ahmed Bougacha0541c672015-05-21 00:08:35 +00001133 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001134 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001135 CopySize, MemCpy->getAlignment());
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001136 return true;
1137}
1138
Sanjay Patela75c41e2015-08-13 22:53:20 +00001139/// Perform simplification of memcpy's. If we have memcpy A
Gabor Greif62f0aac2010-07-28 22:50:26 +00001140/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1141/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1142/// circumstances). This allows later passes to remove the first memcpy
1143/// altogether.
Tim Northover39617352016-05-10 21:49:40 +00001144bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +00001145 // We can only optimize non-volatile memcpy's.
1146 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +00001147
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001148 // If the source and destination of the memcpy are the same, then zap it.
1149 if (M->getSource() == M->getDest()) {
1150 MD->removeInstruction(M);
1151 M->eraseFromParent();
1152 return false;
1153 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001154
1155 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001156 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +00001157 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001158 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001159 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +00001160 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001161 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001162 MD->removeInstruction(M);
1163 M->eraseFromParent();
1164 ++NumCpyToSet;
1165 return true;
1166 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001167
Ahmed Bougachab6169662015-05-11 23:09:46 +00001168 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001169
1170 // Try to turn a partially redundant memset + memcpy into
1171 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +00001172 if (DepInfo.isClobber())
1173 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001174 if (processMemSetMemCpyDependence(M, MDep))
1175 return true;
1176
Nick Lewycky00703e72014-02-04 00:18:54 +00001177 // The optimizations after this point require the memcpy size.
1178 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001179 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +00001180
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001181 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +00001182 // a) memcpy-memcpy xform which exposes redundance for DSE.
1183 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001184 // c) memcpy from freshly alloca'd space or space that has just started its
1185 // lifetime copies undefined data, and we can therefore eliminate the
1186 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001187 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001188 if (DepInfo.isClobber()) {
1189 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1190 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001191 CopySize->getZExtValue(), M->getAlignment(),
Duncan Sandsc6ada692012-10-04 10:54:40 +00001192 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001193 MD->removeInstruction(M);
1194 M->eraseFromParent();
1195 return true;
1196 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001197 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001198 }
Ahmed Charles32e983e2012-02-13 06:30:56 +00001199
Chandler Carruthac80dc72015-06-17 07:18:54 +00001200 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001201 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1202 SrcLoc, true, M->getIterator(), M->getParent());
Ahmed Bougachab6169662015-05-11 23:09:46 +00001203
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001204 if (SrcDepInfo.isClobber()) {
1205 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +00001206 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001207 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001208 Instruction *I = SrcDepInfo.getInst();
1209 bool hasUndefContents = false;
1210
1211 if (isa<AllocaInst>(I)) {
1212 hasUndefContents = true;
1213 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1214 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1215 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1216 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1217 hasUndefContents = true;
1218 }
1219
1220 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +00001221 MD->removeInstruction(M);
1222 M->eraseFromParent();
1223 ++NumMemCpyInstr;
1224 return true;
1225 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001226 }
1227
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001228 if (SrcDepInfo.isClobber())
1229 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1230 if (performMemCpyToMemSetOptzn(M, MDep)) {
1231 MD->removeInstruction(M);
1232 M->eraseFromParent();
1233 ++NumCpyToSet;
1234 return true;
1235 }
1236
Owen Andersonad5367f2008-04-29 21:51:00 +00001237 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001238}
1239
Sanjay Patela75c41e2015-08-13 22:53:20 +00001240/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1241/// not to alias.
Chris Lattner1145e332009-09-01 17:56:32 +00001242bool MemCpyOpt::processMemMove(MemMoveInst *M) {
Chandler Carruth7b560d42015-09-09 17:55:00 +00001243 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chris Lattner1145e332009-09-01 17:56:32 +00001244
Chris Lattner23f61a02011-05-01 18:27:11 +00001245 if (!TLI->has(LibFunc::memmove))
1246 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001247
Chris Lattner1145e332009-09-01 17:56:32 +00001248 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001249 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1250 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001251 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001252
David Greene24199232010-01-05 01:27:47 +00001253 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001254
Chris Lattner1145e332009-09-01 17:56:32 +00001255 // If not, then we know we can transform this.
Jay Foadb804a2b2011-07-12 14:06:48 +00001256 Type *ArgTys[3] = { M->getRawDest()->getType(),
1257 M->getRawSource()->getType(),
1258 M->getLength()->getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001259 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1260 Intrinsic::memcpy, ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001261
Chris Lattner1145e332009-09-01 17:56:32 +00001262 // MemDep may have over conservative information about this instruction, just
1263 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001264 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001265
1266 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001267 return true;
1268}
Nadav Rotem465834c2012-07-24 10:51:42 +00001269
Sanjay Patela75c41e2015-08-13 22:53:20 +00001270/// This is called on every byval argument in call sites.
Chris Lattner58f9f582010-11-21 00:28:59 +00001271bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001272 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001273 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001274 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001275 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001276 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001277 MemDepResult DepInfo = MD->getPointerDependencyFrom(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001278 MemoryLocation(ByValArg, ByValSize), true,
1279 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001280 if (!DepInfo.isClobber())
1281 return false;
1282
1283 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1284 // a memcpy, see if we can byval from the source of the memcpy instead of the
1285 // result.
1286 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001287 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001288 ByValArg->stripPointerCasts() != MDep->getDest())
1289 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001290
Chris Lattner58f9f582010-11-21 00:28:59 +00001291 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001292 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001293 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001294 return false;
1295
Chris Lattner83791ce2011-05-23 00:03:39 +00001296 // Get the alignment of the byval. If the call doesn't specify the alignment,
1297 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +00001298 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +00001299 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001300
Chris Lattner83791ce2011-05-23 00:03:39 +00001301 // If it is greater than the memcpy, then we check to see if we can force the
1302 // source of the memcpy to the alignment we need. If we fail, we bail out.
Chandler Carruth66b31302015-01-04 12:03:27 +00001303 AssumptionCache &AC =
1304 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
1305 *CS->getParent()->getParent());
Hal Finkel60db0582014-09-07 18:57:58 +00001306 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Pete Cooper67cf9a72015-11-19 05:56:52 +00001307 if (MDep->getAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001308 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1309 CS.getInstruction(), &AC, &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001310 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001311
Chris Lattner58f9f582010-11-21 00:28:59 +00001312 // Verify that the copied-from memory doesn't change in between the memcpy and
1313 // the byval call.
1314 // memcpy(a <- b)
1315 // *b = 42;
1316 // foo(*a)
1317 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001318 //
1319 // NOTE: This is conservative, it will stop on any read from the source loc,
1320 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001321 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1322 MemoryLocation::getForSource(MDep), false,
1323 CS.getInstruction()->getIterator(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001324 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1325 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001326
Chris Lattner58f9f582010-11-21 00:28:59 +00001327 Value *TmpCast = MDep->getSource();
1328 if (MDep->getSource()->getType() != ByValArg->getType())
1329 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1330 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001331
Chris Lattner58f9f582010-11-21 00:28:59 +00001332 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
1333 << " " << *MDep << "\n"
1334 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001335
Chris Lattner58f9f582010-11-21 00:28:59 +00001336 // Otherwise we're good! Update the byval argument.
1337 CS.setArgument(ArgNo, TmpCast);
1338 ++NumMemCpyInstr;
1339 return true;
1340}
1341
Sanjay Patela75c41e2015-08-13 22:53:20 +00001342/// Executes one iteration of MemCpyOpt.
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001343bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001344 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001345
Chris Lattnerb5557a72009-09-01 17:09:55 +00001346 // Walk all instruction in the function.
Owen Anderson6a7355c2008-04-21 07:45:10 +00001347 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001348 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001349 // Avoid invalidating the iterator.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001350 Instruction *I = &*BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001351
Chris Lattner58f9f582010-11-21 00:28:59 +00001352 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001353
Owen Anderson6a7355c2008-04-21 07:45:10 +00001354 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001355 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001356 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1357 RepeatInstruction = processMemSet(M, BI);
1358 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Tim Northover39617352016-05-10 21:49:40 +00001359 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001360 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001361 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001362 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001363 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001364 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001365 MadeChange |= processByValArgument(CS, i);
1366 }
1367
1368 // Reprocess the instruction if desired.
1369 if (RepeatInstruction) {
Chris Lattner7d6433a2011-01-08 22:19:21 +00001370 if (BI != BB->begin()) --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001371 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001372 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001373 }
1374 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001375
Chris Lattnerb5557a72009-09-01 17:09:55 +00001376 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001377}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001378
Sanjay Patela75c41e2015-08-13 22:53:20 +00001379/// This is the main transformation entry point for a function.
Chris Lattnerb5557a72009-09-01 17:09:55 +00001380bool MemCpyOpt::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001381 if (skipFunction(F))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001382 return false;
1383
Chris Lattnerb5557a72009-09-01 17:09:55 +00001384 bool MadeChange = false;
Chandler Carruth61440d22016-03-10 00:55:30 +00001385 MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001386 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nadav Rotem465834c2012-07-24 10:51:42 +00001387
Chris Lattner23f61a02011-05-01 18:27:11 +00001388 // If we don't have at least memset and memcpy, there is little point of doing
1389 // anything here. These are required by a freestanding implementation, so if
1390 // even they are disabled, there is no point in trying hard.
1391 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1392 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001393
Chris Lattnerb5557a72009-09-01 17:09:55 +00001394 while (1) {
1395 if (!iterateOnFunction(F))
1396 break;
1397 MadeChange = true;
1398 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001399
Craig Topperf40110f2014-04-25 05:29:35 +00001400 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001401 return MadeChange;
1402}