blob: 1d8ab1be04b151a81eb2b3a0b90cb8ccc919798a [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
Sean Silva6347df02016-06-14 02:44:55 +000015#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000016#include "llvm/Transforms/Scalar.h"
Amaury Sechetbdb261b2016-03-14 22:52:27 +000017#include "llvm/ADT/DenseSet.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000022#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/GlobalVariable.h"
24#include "llvm/IR/IRBuilder.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000025#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000026#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000027#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyf836c892015-07-21 21:56:26 +000028#include <algorithm>
Owen Andersonef9a6fd2008-04-09 08:23:16 +000029using namespace llvm;
30
Chandler Carruth964daaa2014-04-22 02:55:47 +000031#define DEBUG_TYPE "memcpyopt"
32
Owen Andersonef9a6fd2008-04-09 08:23:16 +000033STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
34STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000035STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000036STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000037
Benjamin Kramer15a257d2012-09-13 16:29:49 +000038static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000039 bool &VariableIdxFound,
40 const DataLayout &DL) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000041 // Skip over the first indices.
42 gep_type_iterator GTI = gep_type_begin(GEP);
43 for (unsigned i = 1; i != Idx; ++i, ++GTI)
44 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000045
Owen Andersonef9a6fd2008-04-09 08:23:16 +000046 // Compute the offset implied by the rest of the indices.
47 int64_t Offset = 0;
48 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
49 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +000050 if (!OpC)
Owen Andersonef9a6fd2008-04-09 08:23:16 +000051 return VariableIdxFound = true;
52 if (OpC->isZero()) continue; // No offset.
53
54 // Handle struct indices, which add their field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +000055 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000056 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000057 continue;
58 }
Nadav Rotem465834c2012-07-24 10:51:42 +000059
Owen Andersonef9a6fd2008-04-09 08:23:16 +000060 // Otherwise, we have a sequential type like an array or vector. Multiply
61 // the index by the ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000062 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000063 Offset += Size*OpC->getSExtValue();
64 }
65
66 return Offset;
67}
68
Sanjay Patela75c41e2015-08-13 22:53:20 +000069/// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
70/// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
71/// might be &A[40]. In this case offset would be -8.
Owen Andersonef9a6fd2008-04-09 08:23:16 +000072static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000073 const DataLayout &DL) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +000074 Ptr1 = Ptr1->stripPointerCasts();
75 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer3ef5e462014-03-10 21:05:13 +000076
77 // Handle the trivial case first.
78 if (Ptr1 == Ptr2) {
79 Offset = 0;
80 return true;
81 }
82
Benjamin Kramer15a257d2012-09-13 16:29:49 +000083 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
84 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +000085
Chris Lattner5120ebf2011-01-08 21:07:56 +000086 bool VariableIdxFound = false;
87
88 // If one pointer is a GEP and the other isn't, then see if the GEP is a
89 // constant offset from the base, as in "P" and "gep P, 1".
Craig Topperf40110f2014-04-25 05:29:35 +000090 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000091 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +000092 return !VariableIdxFound;
93 }
94
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000096 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +000097 return !VariableIdxFound;
98 }
Nadav Rotem465834c2012-07-24 10:51:42 +000099
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000100 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
101 // base. After that base, they may have some number of common (and
102 // potentially variable) indices. After that they handle some constant
103 // offset, which determines their offset from each other. At this point, we
104 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000105 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
106 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000107
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000108 // Skip any common indices and track the GEP types.
109 unsigned Idx = 1;
110 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
111 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
112 break;
113
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000114 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
115 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000116 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000117
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000118 Offset = Offset2-Offset1;
119 return true;
120}
121
122
Sanjay Patela75c41e2015-08-13 22:53:20 +0000123/// Represents a range of memset'd bytes with the ByteVal value.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000124/// This allows us to analyze stores like:
125/// store 0 -> P+1
126/// store 0 -> P+0
127/// store 0 -> P+3
128/// store 0 -> P+2
129/// which sometimes happens with stores to arrays of structs etc. When we see
130/// the first store, we make a range [1, 2). The second store extends the range
131/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
132/// two ranges into [0, 3) which is memset'able.
133namespace {
Tim Northover39617352016-05-10 21:49:40 +0000134struct MemsetRange {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000135 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000136 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000137 int64_t Start, End;
138
139 /// StartPtr - The getelementptr instruction that points to the start of the
140 /// range.
Tim Northover39617352016-05-10 21:49:40 +0000141 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000142
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000143 /// Alignment - The known alignment of the first store.
144 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000145
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000146 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000147 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Tim Northover39617352016-05-10 21:49:40 +0000149 bool isProfitableToUseMemset(const DataLayout &DL) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000150};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000151} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000152
Tim Northover39617352016-05-10 21:49:40 +0000153bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
154 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000155 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000156
157 // If there is nothing to merge, don't do anything.
158 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000159
Tim Northover39617352016-05-10 21:49:40 +0000160 // If any of the stores are a memset, then it is always good to extend the
161 // memset.
Craig Toppere325e382015-11-20 07:18:48 +0000162 for (Instruction *SI : TheStores)
Tim Northover39617352016-05-10 21:49:40 +0000163 if (!isa<StoreInst>(SI))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000164 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000165
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000166 // Assume that the code generator is capable of merging pairs of stores
167 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000168 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000169
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000170 // If we have fewer than 8 stores, it can still be worthwhile to do this.
171 // For example, merging 4 i8 stores into an i32 store is useful almost always.
172 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
173 // memset will be split into 2 32-bit stores anyway) and doing so can
174 // pessimize the llvm optimizer.
175 //
176 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000177 // the maximum GPR width is the same size as the largest legal integer
178 // size. If so, check to see whether we will end up actually reducing the
179 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000180 unsigned Bytes = unsigned(End-Start);
Jun Bum Limbe11bdc2016-05-13 18:38:35 +0000181 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
Matt Arsenault899f7d22013-09-16 22:43:16 +0000182 if (MaxIntSize == 0)
183 MaxIntSize = 1;
184 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000185
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000186 // Assume the remaining bytes if any are done a byte at a time.
Craig Toppera5ea5282015-11-21 17:44:42 +0000187 unsigned NumByteStores = Bytes % MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000188
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000189 // If we will reduce the # stores (according to this heuristic), do the
190 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
191 // etc.
192 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000193}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000194
195
196namespace {
Tim Northover39617352016-05-10 21:49:40 +0000197class MemsetRanges {
Sanjay Patela75c41e2015-08-13 22:53:20 +0000198 /// A sorted list of the memset ranges.
Tim Northover39617352016-05-10 21:49:40 +0000199 SmallVector<MemsetRange, 8> Ranges;
200 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000201 const DataLayout &DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000202public:
Tim Northover39617352016-05-10 21:49:40 +0000203 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000204
Tim Northover39617352016-05-10 21:49:40 +0000205 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000206 const_iterator begin() const { return Ranges.begin(); }
207 const_iterator end() const { return Ranges.end(); }
208 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000209
Chris Lattnerc6381472011-01-08 20:24:01 +0000210 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000211 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
212 addStore(OffsetFromFirst, SI);
213 else
214 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000215 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000216
217 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000218 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000219
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000220 addRange(OffsetFromFirst, StoreSize,
Tim Northover39617352016-05-10 21:49:40 +0000221 SI->getPointerOperand(), SI->getAlignment(), SI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000222 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000223
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000224 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
225 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Tim Northover39617352016-05-10 21:49:40 +0000226 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000227 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000228
Tim Northover39617352016-05-10 21:49:40 +0000229 void addRange(int64_t Start, int64_t Size, Value *Ptr,
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000230 unsigned Alignment, Instruction *Inst);
231
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000232};
Nadav Rotem465834c2012-07-24 10:51:42 +0000233
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000234} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000235
236
Tim Northover39617352016-05-10 21:49:40 +0000237/// Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000238/// new range for the specified store at the specified offset, merging into
239/// existing ranges as appropriate.
Tim Northover39617352016-05-10 21:49:40 +0000240void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
241 unsigned Alignment, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000242 int64_t End = Start+Size;
Nadav Rotem465834c2012-07-24 10:51:42 +0000243
Nick Lewyckyf836c892015-07-21 21:56:26 +0000244 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
Tim Northover39617352016-05-10 21:49:40 +0000245 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
Nadav Rotem465834c2012-07-24 10:51:42 +0000246
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000247 // We now know that I == E, in which case we didn't find anything to merge
248 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
249 // to insert a new range. Handle this now.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000250 if (I == Ranges.end() || End < I->Start) {
Tim Northover39617352016-05-10 21:49:40 +0000251 MemsetRange &R = *Ranges.insert(I, MemsetRange());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000252 R.Start = Start;
253 R.End = End;
Tim Northover39617352016-05-10 21:49:40 +0000254 R.StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000255 R.Alignment = Alignment;
256 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000257 return;
258 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000259
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000260 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000261 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000262
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000263 // At this point, we may have an interval that completely contains our store.
264 // If so, just add it to the interval and return.
265 if (I->Start <= Start && I->End >= End)
266 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000267
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000268 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
269 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000270
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000271 // See if the range extends the start of the range. In this case, it couldn't
272 // possibly cause it to join the prior range, because otherwise we would have
273 // stopped on *it*.
274 if (Start < I->Start) {
275 I->Start = Start;
Tim Northover39617352016-05-10 21:49:40 +0000276 I->StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000277 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000278 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000279
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000280 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
281 // is in or right at the end of I), and that End >= I->Start. Extend I out to
282 // End.
283 if (End > I->End) {
284 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000285 range_iterator NextI = I;
Nick Lewyckyf836c892015-07-21 21:56:26 +0000286 while (++NextI != Ranges.end() && End >= NextI->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000287 // Merge the range in.
288 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
289 if (NextI->End > I->End)
290 I->End = NextI->End;
291 Ranges.erase(NextI);
292 NextI = I;
293 }
294 }
295}
296
297//===----------------------------------------------------------------------===//
Sean Silva6347df02016-06-14 02:44:55 +0000298// MemCpyOptLegacyPass Pass
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000299//===----------------------------------------------------------------------===//
300
301namespace {
Sean Silva6347df02016-06-14 02:44:55 +0000302 class MemCpyOptLegacyPass : public FunctionPass {
303 MemCpyOptPass Impl;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000304 public:
305 static char ID; // Pass identification, replacement for typeid
Sean Silva6347df02016-06-14 02:44:55 +0000306 MemCpyOptLegacyPass() : FunctionPass(ID) {
307 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000308 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000309
Craig Topper3e4c6972014-03-05 09:10:37 +0000310 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000311
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000312 private:
313 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000314 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000315 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000316 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000317 AU.addRequired<MemoryDependenceWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000318 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000319 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000320 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000321 AU.addPreserved<MemoryDependenceWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000322 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000323
Matt Walaa4afccd2015-06-12 18:16:51 +0000324 // Helper functions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000325 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000326 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Tim Northover39617352016-05-10 21:49:40 +0000327 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000328 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000329 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000330 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000331 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000332 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000333 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
Chris Lattner58f9f582010-11-21 00:28:59 +0000334 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000335 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
336 Value *ByteVal);
337
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000338 bool iterateOnFunction(Function &F);
339 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000340
Sean Silva6347df02016-06-14 02:44:55 +0000341 char MemCpyOptLegacyPass::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000342}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000343
Sanjay Patela75c41e2015-08-13 22:53:20 +0000344/// The public interface to this file...
Sean Silva6347df02016-06-14 02:44:55 +0000345FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000346
Sean Silva6347df02016-06-14 02:44:55 +0000347INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000348 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000349INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth61440d22016-03-10 00:55:30 +0000350INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000351INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000352INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
353INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Sean Silva6347df02016-06-14 02:44:55 +0000354INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000355 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000356
Sanjay Patela75c41e2015-08-13 22:53:20 +0000357/// When scanning forward over instructions, we look for some other patterns to
358/// fold away. In particular, this looks for stores to neighboring locations of
359/// memory. If it sees enough consecutive ones, it attempts to merge them
360/// together into a memcpy/memset.
Sean Silva6347df02016-06-14 02:44:55 +0000361Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
362 Value *StartPtr,
363 Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000364 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000365
Chris Lattnerc6381472011-01-08 20:24:01 +0000366 // Okay, so we now have a single store that can be splatable. Scan to find
367 // all subsequent stores of the same value to offset from the same pointer.
368 // Join these together into ranges, so we can decide whether contiguous blocks
369 // are stored.
Tim Northover39617352016-05-10 21:49:40 +0000370 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000371
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000372 BasicBlock::iterator BI(StartInst);
Chris Lattnerc6381472011-01-08 20:24:01 +0000373 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000374 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
375 // If the instruction is readnone, ignore it, otherwise bail out. We
376 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000377 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000378 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
379 break;
380 continue;
381 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000382
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000383 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
384 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000385 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000386
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000387 // Check to see if this stored value is of the same byte-splattable value.
388 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
389 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000390
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000391 // Check to see if this store is to a constant offset from the start ptr.
392 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000393 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
394 DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000395 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000396
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000397 Ranges.addStore(Offset, NextStore);
398 } else {
399 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000400
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000401 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
402 !isa<ConstantInt>(MSI->getLength()))
403 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000404
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000405 // Check to see if this store is to a constant offset from the start ptr.
406 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000407 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000408 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000409
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000410 Ranges.addMemSet(Offset, MSI);
411 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000412 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000413
Chris Lattnerc6381472011-01-08 20:24:01 +0000414 // If we have no ranges, then we just had a single store with nothing that
415 // could be merged in. This is a very common case of course.
416 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000417 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000418
Chris Lattnerc6381472011-01-08 20:24:01 +0000419 // If we had at least one store that could be merged in, add the starting
420 // store as well. We try to avoid this unless there is at least something
421 // interesting as a small compile-time optimization.
422 Ranges.addInst(0, StartInst);
423
424 // If we create any memsets, we put it right before the first instruction that
425 // isn't part of the memset block. This ensure that the memset is dominated
426 // by any addressing instruction needed by the start of the block.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000427 IRBuilder<> Builder(&*BI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000428
429 // Now that we have full information about ranges, loop over the ranges and
430 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000431 Instruction *AMemSet = nullptr;
Tim Northover39617352016-05-10 21:49:40 +0000432 for (const MemsetRange &Range : Ranges) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000433
Chris Lattnerc6381472011-01-08 20:24:01 +0000434 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000435
Chris Lattnerc6381472011-01-08 20:24:01 +0000436 // If it is profitable to lower this range to memset, do so now.
Tim Northover39617352016-05-10 21:49:40 +0000437 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000438 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000439
Chris Lattnerc6381472011-01-08 20:24:01 +0000440 // Otherwise, we do want to transform this! Create a new memset.
441 // Get the starting pointer of the block.
Tim Northover39617352016-05-10 21:49:40 +0000442 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000443
Tim Northover39617352016-05-10 21:49:40 +0000444 // Determine alignment
445 unsigned Alignment = Range.Alignment;
446 if (Alignment == 0) {
447 Type *EltType =
448 cast<PointerType>(StartPtr->getType())->getElementType();
449 Alignment = DL.getABITypeAlignment(EltType);
450 }
451
452 AMemSet =
453 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000454
Chris Lattnerc6381472011-01-08 20:24:01 +0000455 DEBUG(dbgs() << "Replace stores:\n";
Craig Toppere325e382015-11-20 07:18:48 +0000456 for (Instruction *SI : Range.TheStores)
457 dbgs() << *SI << '\n';
Chris Lattnerc6381472011-01-08 20:24:01 +0000458 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000459
460 if (!Range.TheStores.empty())
461 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
462
Chris Lattnerc6381472011-01-08 20:24:01 +0000463 // Zap all the stores.
Craig Toppere325e382015-11-20 07:18:48 +0000464 for (Instruction *SI : Range.TheStores) {
465 MD->removeInstruction(SI);
466 SI->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000467 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000468 ++NumMemSetInfer;
469 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000470
Chris Lattnerc6381472011-01-08 20:24:01 +0000471 return AMemSet;
472}
473
Tim Northover39617352016-05-10 21:49:40 +0000474static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
475 const LoadInst *LI) {
476 unsigned StoreAlign = SI->getAlignment();
477 if (!StoreAlign)
478 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
479 unsigned LoadAlign = LI->getAlignment();
480 if (!LoadAlign)
481 LoadAlign = DL.getABITypeAlignment(LI->getType());
Amaury Secheta0c242c2016-01-05 20:17:48 +0000482
Tim Northover39617352016-05-10 21:49:40 +0000483 return std::min(StoreAlign, LoadAlign);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000484}
Chris Lattnerc6381472011-01-08 20:24:01 +0000485
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000486// This method try to lift a store instruction before position P.
487// It will lift the store and its argument + that anything that
David Majnemerd99068d2016-05-26 19:24:24 +0000488// may alias with these.
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000489// The method returns true if it was successful.
490static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P) {
491 // If the store alias this position, early bail out.
492 MemoryLocation StoreLoc = MemoryLocation::get(SI);
493 if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef)
494 return false;
495
496 // Keep track of the arguments of all instruction we plan to lift
497 // so we can make sure to lift them as well if apropriate.
498 DenseSet<Instruction*> Args;
499 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
500 if (Ptr->getParent() == SI->getParent())
501 Args.insert(Ptr);
502
503 // Instruction to lift before P.
504 SmallVector<Instruction*, 8> ToLift;
505
506 // Memory locations of lifted instructions.
507 SmallVector<MemoryLocation, 8> MemLocs;
508 MemLocs.push_back(StoreLoc);
509
510 // Lifted callsites.
511 SmallVector<ImmutableCallSite, 8> CallSites;
512
513 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
514 auto *C = &*I;
515
516 bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef;
517
518 bool NeedLift = false;
519 if (Args.erase(C))
520 NeedLift = true;
521 else if (MayAlias) {
David Majnemer0a16c222016-08-11 21:15:00 +0000522 NeedLift = any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
523 return AA.getModRefInfo(C, ML);
524 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000525
526 if (!NeedLift)
David Majnemer0a16c222016-08-11 21:15:00 +0000527 NeedLift = any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) {
528 return AA.getModRefInfo(C, CS);
529 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000530 }
531
532 if (!NeedLift)
533 continue;
534
535 if (MayAlias) {
536 if (auto CS = ImmutableCallSite(C)) {
537 // If we can't lift this before P, it's game over.
538 if (AA.getModRefInfo(P, CS) != MRI_NoModRef)
539 return false;
540
541 CallSites.push_back(CS);
542 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
543 // If we can't lift this before P, it's game over.
544 auto ML = MemoryLocation::get(C);
545 if (AA.getModRefInfo(P, ML) != MRI_NoModRef)
546 return false;
547
548 MemLocs.push_back(ML);
549 } else
550 // We don't know how to lift this instruction.
551 return false;
552 }
553
554 ToLift.push_back(C);
555 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
556 if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
557 if (A->getParent() == SI->getParent())
558 Args.insert(A);
559 }
560
561 // We made it, we need to lift
562 for (auto *I : reverse(ToLift)) {
563 DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
564 I->moveBefore(P);
565 }
566
567 return true;
568}
569
Sean Silva6347df02016-06-14 02:44:55 +0000570bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000571 if (!SI->isSimple()) return false;
Andrea Di Biagio99493df2015-10-09 10:53:41 +0000572
573 // Avoid merging nontemporal stores since the resulting
574 // memcpy/memset would not be able to preserve the nontemporal hint.
575 // In theory we could teach how to propagate the !nontemporal metadata to
576 // memset calls. However, that change would force the backend to
577 // conservatively expand !nontemporal memset calls back to sequences of
578 // store instructions (effectively undoing the merging).
579 if (SI->getMetadata(LLVMContext::MD_nontemporal))
580 return false;
581
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000582 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000583
Amaury Secheta0c242c2016-01-05 20:17:48 +0000584 // Load to store forwarding can be interpreted as memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000585 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000586 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000587 LI->getParent() == SI->getParent()) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000588
589 auto *T = LI->getType();
590 if (T->isAggregateType()) {
Sean Silva6347df02016-06-14 02:44:55 +0000591 AliasAnalysis &AA = LookupAliasAnalysis();
Amaury Secheta0c242c2016-01-05 20:17:48 +0000592 MemoryLocation LoadLoc = MemoryLocation::get(LI);
593
594 // We use alias analysis to check if an instruction may store to
595 // the memory we load from in between the load and the store. If
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000596 // such an instruction is found, we try to promote there instead
597 // of at the store position.
598 Instruction *P = SI;
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000599 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
600 if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) {
601 P = &I;
602 break;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000603 }
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000604 }
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000605
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000606 // We found an instruction that may write to the loaded memory.
607 // We can try to promote at this position instead of the store
608 // position if nothing alias the store memory after this and the store
609 // destination is not in the range.
610 if (P && P != SI) {
611 if (!moveUp(AA, SI, P))
612 P = nullptr;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000613 }
614
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000615 // If a valid insertion position is found, then we can promote
616 // the load/store pair to a memcpy.
617 if (P) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000618 // If we load from memory that may alias the memory we store to,
619 // memmove must be used to preserve semantic. If not, memcpy can
620 // be used.
621 bool UseMemMove = false;
622 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
623 UseMemMove = true;
624
625 unsigned Align = findCommonAlignment(DL, SI, LI);
626 uint64_t Size = DL.getTypeStoreSize(T);
627
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000628 IRBuilder<> Builder(P);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000629 Instruction *M;
630 if (UseMemMove)
631 M = Builder.CreateMemMove(SI->getPointerOperand(),
632 LI->getPointerOperand(), Size,
633 Align, SI->isVolatile());
634 else
635 M = Builder.CreateMemCpy(SI->getPointerOperand(),
636 LI->getPointerOperand(), Size,
637 Align, SI->isVolatile());
638
639 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
640 << " => " << *M << "\n");
641
642 MD->removeInstruction(SI);
643 SI->eraseFromParent();
644 MD->removeInstruction(LI);
645 LI->eraseFromParent();
646 ++NumMemCpyInstr;
647
648 // Make sure we do not invalidate the iterator.
649 BBI = M->getIterator();
650 return true;
651 }
652 }
653
654 // Detect cases where we're performing call slot forwarding, but
655 // happen to be using a load-store pair to implement it, rather than
656 // a memcpy.
Eli Friedman5da0ff42011-06-02 21:24:42 +0000657 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000658 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000659 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
660 C = dyn_cast<CallInst>(ldep.getInst());
661
662 if (C) {
663 // Check that nothing touches the dest of the "copy" between
664 // the call and the store.
David Majnemerd99068d2016-05-26 19:24:24 +0000665 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
666 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
Sean Silva6347df02016-06-14 02:44:55 +0000667 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000668 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000669 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
670 I != E; --I) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000671 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000672 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000673 break;
674 }
David Majnemerd99068d2016-05-26 19:24:24 +0000675 // The store to dest may never happen if an exception can be thrown
676 // between the load and the store.
677 if (I->mayThrow() && !CpyDestIsLocal) {
678 C = nullptr;
679 break;
680 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000681 }
682 }
683
Owen Anderson18e4fed2010-10-15 22:52:12 +0000684 if (C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000685 bool changed = performCallSlotOptzn(
686 LI, SI->getPointerOperand()->stripPointerCasts(),
687 LI->getPointerOperand()->stripPointerCasts(),
688 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
Amaury Secheta0c242c2016-01-05 20:17:48 +0000689 findCommonAlignment(DL, SI, LI), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000690 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000691 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000692 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000693 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000694 LI->eraseFromParent();
695 ++NumMemCpyInstr;
696 return true;
697 }
698 }
699 }
700 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000701
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000702 // There are two cases that are interesting for this code to handle: memcpy
703 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000704
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000705 // Ensure that the value being stored is something that can be memset'able a
706 // byte at a time like "0" or "-1" or any width, as well as things like
707 // 0xA0A0A0A0 and 0.0.
Amaury Sechet3235c082016-01-06 19:47:24 +0000708 auto *V = SI->getOperand(0);
709 if (Value *ByteVal = isBytewiseValue(V)) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000710 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
711 ByteVal)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000712 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerc6381472011-01-08 20:24:01 +0000713 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000714 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000715
Amaury Sechet3235c082016-01-06 19:47:24 +0000716 // If we have an aggregate, we try to promote it to memset regardless
717 // of opportunity for merging as it can expose optimization opportunities
718 // in subsequent passes.
719 auto *T = V->getType();
720 if (T->isAggregateType()) {
721 uint64_t Size = DL.getTypeStoreSize(T);
722 unsigned Align = SI->getAlignment();
723 if (!Align)
724 Align = DL.getABITypeAlignment(T);
725 IRBuilder<> Builder(SI);
726 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
727 Size, Align, SI->isVolatile());
728
729 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
730
731 MD->removeInstruction(SI);
732 SI->eraseFromParent();
733 NumMemSetInfer++;
734
735 // Make sure we do not invalidate the iterator.
736 BBI = M->getIterator();
737 return true;
738 }
739 }
740
Chris Lattnerc6381472011-01-08 20:24:01 +0000741 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000742}
743
Sean Silva6347df02016-06-14 02:44:55 +0000744bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000745 // See if there is another memset or store neighboring this memset which
746 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000747 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
748 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
749 MSI->getValue())) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000750 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000751 return true;
752 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000753 return false;
754}
755
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000756
Sanjay Patela75c41e2015-08-13 22:53:20 +0000757/// Takes a memcpy and a call that it depends on,
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000758/// and checks for the possibility of a call slot optimization by having
759/// the call write its result directly into the destination of the memcpy.
Sean Silva6347df02016-06-14 02:44:55 +0000760bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
761 Value *cpySrc, uint64_t cpyLen,
762 unsigned cpyAlign, CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000763 // The general transformation to keep in mind is
764 //
765 // call @func(..., src, ...)
766 // memcpy(dest, src, ...)
767 //
768 // ->
769 //
770 // memcpy(dest, src, ...)
771 // call @func(..., dest, ...)
772 //
773 // Since moving the memcpy is technically awkward, we additionally check that
774 // src only holds uninitialized values at the moment of the call, meaning that
775 // the memcpy can be discarded rather than moved.
776
Tim Shen7aa0ad62016-06-08 19:42:32 +0000777 // Lifetime marks shouldn't be operated on.
778 if (Function *F = C->getCalledFunction())
779 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
780 return false;
781
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000782 // Deliberately get the source and destination with bitcasts stripped away,
783 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000784 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000785
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000786 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000787 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000788 if (!srcAlloca)
789 return false;
790
Chris Lattnerb5557a72009-09-01 17:09:55 +0000791 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000792 if (!srcArraySize)
793 return false;
794
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000795 const DataLayout &DL = cpy->getModule()->getDataLayout();
796 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
797 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000798
Owen Anderson18e4fed2010-10-15 22:52:12 +0000799 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000800 return false;
801
802 // Check that accessing the first srcSize bytes of dest will not cause a
803 // trap. Otherwise the transform is invalid since it might cause a trap
804 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000805 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000806 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000807 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000808 if (!destArraySize)
809 return false;
810
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000811 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
812 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000813
814 if (destSize < srcSize)
815 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000816 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
David Majnemerd99068d2016-05-26 19:24:24 +0000817 // The store to dest may never happen if the call can throw.
818 if (C->mayThrow())
819 return false;
820
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000821 if (A->getDereferenceableBytes() < srcSize) {
822 // If the destination is an sret parameter then only accesses that are
823 // outside of the returned struct type can trap.
824 if (!A->hasStructRetAttr())
825 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000826
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000827 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
828 if (!StructTy->isSized()) {
829 // The call may never return and hence the copy-instruction may never
830 // be executed, and therefore it's not safe to say "the destination
831 // has at least <cpyLen> bytes, as implied by the copy-instruction",
832 return false;
833 }
834
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000835 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000836 if (destSize < srcSize)
837 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000838 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000839 } else {
840 return false;
841 }
842
Duncan Sands933db772012-10-05 07:29:46 +0000843 // Check that dest points to memory that is at least as aligned as src.
844 unsigned srcAlign = srcAlloca->getAlignment();
845 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000846 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000847 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
848 // If dest is not aligned enough and we can't increase its alignment then
849 // bail out.
850 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
851 return false;
852
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000853 // Check that src is not accessed except via the call and the memcpy. This
854 // guarantees that it holds only undefined values when passed in (so the final
855 // memcpy can be dropped), that it is not read or written between the call and
856 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000857 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
858 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000859 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000860 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000861
Chandler Carruthcdf47882014-03-09 03:16:01 +0000862 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
863 for (User *UU : U->users())
864 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000865 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000866 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000867 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
868 if (!G->hasAllZeroIndices())
869 return false;
870
871 for (User *UU : U->users())
872 srcUseList.push_back(UU);
873 continue;
874 }
875 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
876 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
877 IT->getIntrinsicID() == Intrinsic::lifetime_end)
878 continue;
879
880 if (U != C && U != cpy)
881 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000882 }
883
Nick Lewycky703e4882014-07-14 18:52:02 +0000884 // Check that src isn't captured by the called function since the
885 // transformation can cause aliasing issues in that case.
886 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
887 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
888 return false;
889
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000890 // Since we're changing the parameter to the callsite, we need to make sure
891 // that what would be the new parameter dominates the callsite.
Sean Silva6347df02016-06-14 02:44:55 +0000892 DominatorTree &DT = LookupDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000893 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000894 if (!DT.dominates(cpyDestInst, C))
895 return false;
896
897 // In addition to knowing that the call does not access src in some
898 // unexpected manner, for example via a global, which we deduce from
899 // the use analysis, we also need to know that it does not sneakily
900 // access dest. We rely on AA to figure this out for us.
Sean Silva6347df02016-06-14 02:44:55 +0000901 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruth194f59c2015-07-22 23:15:57 +0000902 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
Chad Rosiera968caf2012-05-14 20:35:04 +0000903 // If necessary, perform additional analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000904 if (MR != MRI_NoModRef)
Chad Rosiera968caf2012-05-14 20:35:04 +0000905 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000906 if (MR != MRI_NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000907 return false;
908
909 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000910 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000911 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000912 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000913 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
914 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
915 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000916 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000917 if (CS.getArgument(i)->getType() == Dest->getType())
918 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000919 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000920 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
921 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000922 }
923
Owen Andersond071a872008-06-01 21:52:16 +0000924 if (!changedArgument)
925 return false;
926
Duncan Sandsc6ada692012-10-04 10:54:40 +0000927 // If the destination wasn't sufficiently aligned then increase its alignment.
928 if (!isDestSufficientlyAligned) {
929 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
930 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
931 }
932
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000933 // Drop any cached information about the call, because we may have changed
934 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000935 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000936
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000937 // Update AA metadata
938 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
939 // handled here, but combineMetadata doesn't support them yet
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +0000940 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
941 LLVMContext::MD_noalias,
942 LLVMContext::MD_invariant_group};
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000943 combineMetadata(C, cpy, KnownIDs);
944
Chris Lattner58f9f582010-11-21 00:28:59 +0000945 // Remove the memcpy.
946 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000947 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000948
949 return true;
950}
951
Sanjay Patela75c41e2015-08-13 22:53:20 +0000952/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
953/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
Sean Silva6347df02016-06-14 02:44:55 +0000954bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
955 MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000956 // We can only transforms memcpy's where the dest of one is the source of the
957 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000958 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000959 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000960
Chris Lattnerfd51c522010-12-09 07:39:50 +0000961 // If dep instruction is reading from our current input, then it is a noop
962 // transfer and substituting the input won't change this instruction. Just
963 // ignore the input and let someone else zap MDep. This handles cases like:
964 // memcpy(a <- a)
965 // memcpy(b <- a)
966 if (M->getSource() == MDep->getSource())
967 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000968
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000969 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000970 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000971 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
972 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
973 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
974 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000975
Sean Silva6347df02016-06-14 02:44:55 +0000976 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner59572292010-11-21 08:06:10 +0000977
978 // Verify that the copied-from memory doesn't change in between the two
979 // transfers. For example, in:
980 // memcpy(a <- b)
981 // *b = 42;
982 // memcpy(c <- a)
983 // It would be invalid to transform the second memcpy into memcpy(c <- b).
984 //
985 // TODO: If the code between M and MDep is transparent to the destination "c",
986 // then we could still perform the xform by moving M up to the first memcpy.
987 //
988 // NOTE: This is conservative, it will stop on any read from the source loc,
989 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000990 MemDepResult SourceDep =
991 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
992 M->getIterator(), M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +0000993 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
994 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000995
Chris Lattner731caac2010-11-18 08:00:57 +0000996 // If the dest of the second might alias the source of the first, then the
997 // source and dest might overlap. We still want to eliminate the intermediate
998 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000999 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +00001000 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1001 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001002 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001003
Chris Lattner58f9f582010-11-21 00:28:59 +00001004 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +00001005
Pete Cooper67cf9a72015-11-19 05:56:52 +00001006 // Make sure to use the lesser of the alignment of the source and the dest
1007 // since we're changing where we're reading from, but don't want to increase
1008 // the alignment past what can be read from or written to.
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001009 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1010 // example we could be moving from movaps -> movq on x86.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001011 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
1012
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001013 IRBuilder<> Builder(M);
1014 if (UseMemMove)
1015 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001016 Align, M->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001017 else
1018 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001019 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +00001020
Chris Lattner59572292010-11-21 08:06:10 +00001021 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +00001022 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +00001023 M->eraseFromParent();
1024 ++NumMemCpyInstr;
1025 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001026}
1027
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001028/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1029/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1030/// weren't copied over by \p MemCpy.
1031///
1032/// In other words, transform:
1033/// \code
1034/// memset(dst, c, dst_size);
1035/// memcpy(dst, src, src_size);
1036/// \endcode
1037/// into:
1038/// \code
1039/// memcpy(dst, src, src_size);
1040/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1041/// \endcode
Sean Silva6347df02016-06-14 02:44:55 +00001042bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1043 MemSetInst *MemSet) {
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001044 // We can only transform memset/memcpy with the same destination.
1045 if (MemSet->getDest() != MemCpy->getDest())
1046 return false;
1047
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001048 // Check that there are no other dependencies on the memset destination.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001049 MemDepResult DstDepInfo =
1050 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1051 MemCpy->getIterator(), MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001052 if (DstDepInfo.getInst() != MemSet)
1053 return false;
1054
Ahmed Bougacha9692e302015-04-21 21:28:33 +00001055 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1056 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001057 Value *DestSize = MemSet->getLength();
1058 Value *SrcSize = MemCpy->getLength();
1059
1060 // By default, create an unaligned memset.
1061 unsigned Align = 1;
1062 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1063 // of the sum.
1064 const unsigned DestAlign =
Pete Cooper67cf9a72015-11-19 05:56:52 +00001065 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001066 if (DestAlign > 1)
1067 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1068 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1069
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001070 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001071
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001072 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001073 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001074 if (DestSize->getType()->getIntegerBitWidth() >
1075 SrcSize->getType()->getIntegerBitWidth())
1076 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1077 else
1078 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001079 }
1080
Benjamin Kramer1697d392016-11-07 17:47:28 +00001081 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1082 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1083 Value *MemsetLen = Builder.CreateSelect(
1084 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001085 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1086 MemsetLen, Align);
1087
1088 MD->removeInstruction(MemSet);
1089 MemSet->eraseFromParent();
1090 return true;
1091}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001092
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001093/// Transform memcpy to memset when its source was just memset.
1094/// In other words, turn:
1095/// \code
1096/// memset(dst1, c, dst1_size);
1097/// memcpy(dst2, dst1, dst2_size);
1098/// \endcode
1099/// into:
1100/// \code
1101/// memset(dst1, c, dst1_size);
1102/// memset(dst2, c, dst2_size);
1103/// \endcode
1104/// When dst2_size <= dst1_size.
1105///
1106/// The \p MemCpy must have a Constant length.
Sean Silva6347df02016-06-14 02:44:55 +00001107bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1108 MemSetInst *MemSet) {
Tim Shena3dbead2016-08-25 19:27:26 +00001109 AliasAnalysis &AA = LookupAliasAnalysis();
1110
Tim Shen3ad8b432016-08-25 21:03:46 +00001111 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1112 // memcpying from the same address. Otherwise it is hard to reason about.
Tim Shena3dbead2016-08-25 19:27:26 +00001113 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001114 return false;
1115
1116 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1117 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1118 // Make sure the memcpy doesn't read any more than what the memset wrote.
1119 // Don't worry about sizes larger than i64.
1120 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1121 return false;
1122
Ahmed Bougacha0541c672015-05-21 00:08:35 +00001123 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001124 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001125 CopySize, MemCpy->getAlignment());
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001126 return true;
1127}
1128
Sanjay Patela75c41e2015-08-13 22:53:20 +00001129/// Perform simplification of memcpy's. If we have memcpy A
Gabor Greif62f0aac2010-07-28 22:50:26 +00001130/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1131/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1132/// circumstances). This allows later passes to remove the first memcpy
1133/// altogether.
Sean Silva6347df02016-06-14 02:44:55 +00001134bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +00001135 // We can only optimize non-volatile memcpy's.
1136 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +00001137
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001138 // If the source and destination of the memcpy are the same, then zap it.
1139 if (M->getSource() == M->getDest()) {
1140 MD->removeInstruction(M);
1141 M->eraseFromParent();
1142 return false;
1143 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001144
1145 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +00001147 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001148 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001149 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +00001150 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001151 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001152 MD->removeInstruction(M);
1153 M->eraseFromParent();
1154 ++NumCpyToSet;
1155 return true;
1156 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001157
Ahmed Bougachab6169662015-05-11 23:09:46 +00001158 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001159
1160 // Try to turn a partially redundant memset + memcpy into
1161 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +00001162 if (DepInfo.isClobber())
1163 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001164 if (processMemSetMemCpyDependence(M, MDep))
1165 return true;
1166
Nick Lewycky00703e72014-02-04 00:18:54 +00001167 // The optimizations after this point require the memcpy size.
1168 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001169 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +00001170
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001171 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +00001172 // a) memcpy-memcpy xform which exposes redundance for DSE.
1173 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001174 // c) memcpy from freshly alloca'd space or space that has just started its
1175 // lifetime copies undefined data, and we can therefore eliminate the
1176 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001177 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001178 if (DepInfo.isClobber()) {
1179 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1180 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001181 CopySize->getZExtValue(), M->getAlignment(),
Duncan Sandsc6ada692012-10-04 10:54:40 +00001182 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001183 MD->removeInstruction(M);
1184 M->eraseFromParent();
1185 return true;
1186 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001187 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001188 }
Ahmed Charles32e983e2012-02-13 06:30:56 +00001189
Chandler Carruthac80dc72015-06-17 07:18:54 +00001190 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001191 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1192 SrcLoc, true, M->getIterator(), M->getParent());
Ahmed Bougachab6169662015-05-11 23:09:46 +00001193
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001194 if (SrcDepInfo.isClobber()) {
1195 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +00001196 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001197 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001198 Instruction *I = SrcDepInfo.getInst();
1199 bool hasUndefContents = false;
1200
1201 if (isa<AllocaInst>(I)) {
1202 hasUndefContents = true;
1203 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1204 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1205 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1206 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1207 hasUndefContents = true;
1208 }
1209
1210 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +00001211 MD->removeInstruction(M);
1212 M->eraseFromParent();
1213 ++NumMemCpyInstr;
1214 return true;
1215 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001216 }
1217
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001218 if (SrcDepInfo.isClobber())
1219 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1220 if (performMemCpyToMemSetOptzn(M, MDep)) {
1221 MD->removeInstruction(M);
1222 M->eraseFromParent();
1223 ++NumCpyToSet;
1224 return true;
1225 }
1226
Owen Andersonad5367f2008-04-29 21:51:00 +00001227 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001228}
1229
Sanjay Patela75c41e2015-08-13 22:53:20 +00001230/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1231/// not to alias.
Sean Silva6347df02016-06-14 02:44:55 +00001232bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1233 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner1145e332009-09-01 17:56:32 +00001234
Chris Lattner23f61a02011-05-01 18:27:11 +00001235 if (!TLI->has(LibFunc::memmove))
1236 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001237
Chris Lattner1145e332009-09-01 17:56:32 +00001238 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001239 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1240 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001241 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001242
Sean Silva6347df02016-06-14 02:44:55 +00001243 DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1244 << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001245
Chris Lattner1145e332009-09-01 17:56:32 +00001246 // If not, then we know we can transform this.
Jay Foadb804a2b2011-07-12 14:06:48 +00001247 Type *ArgTys[3] = { M->getRawDest()->getType(),
1248 M->getRawSource()->getType(),
1249 M->getLength()->getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001250 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1251 Intrinsic::memcpy, ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001252
Chris Lattner1145e332009-09-01 17:56:32 +00001253 // MemDep may have over conservative information about this instruction, just
1254 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001255 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001256
1257 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001258 return true;
1259}
Nadav Rotem465834c2012-07-24 10:51:42 +00001260
Sanjay Patela75c41e2015-08-13 22:53:20 +00001261/// This is called on every byval argument in call sites.
Sean Silva6347df02016-06-14 02:44:55 +00001262bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001263 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001264 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001265 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001266 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001267 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001268 MemDepResult DepInfo = MD->getPointerDependencyFrom(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001269 MemoryLocation(ByValArg, ByValSize), true,
1270 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001271 if (!DepInfo.isClobber())
1272 return false;
1273
1274 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1275 // a memcpy, see if we can byval from the source of the memcpy instead of the
1276 // result.
1277 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001278 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001279 ByValArg->stripPointerCasts() != MDep->getDest())
1280 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001281
Chris Lattner58f9f582010-11-21 00:28:59 +00001282 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001283 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001284 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001285 return false;
1286
Chris Lattner83791ce2011-05-23 00:03:39 +00001287 // Get the alignment of the byval. If the call doesn't specify the alignment,
1288 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +00001289 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +00001290 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001291
Chris Lattner83791ce2011-05-23 00:03:39 +00001292 // If it is greater than the memcpy, then we check to see if we can force the
1293 // source of the memcpy to the alignment we need. If we fail, we bail out.
Sean Silva6347df02016-06-14 02:44:55 +00001294 DominatorTree &DT = LookupDomTree();
Pete Cooper67cf9a72015-11-19 05:56:52 +00001295 if (MDep->getAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001296 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001297 CS.getInstruction(), &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001298 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001299
Chris Lattner58f9f582010-11-21 00:28:59 +00001300 // Verify that the copied-from memory doesn't change in between the memcpy and
1301 // the byval call.
1302 // memcpy(a <- b)
1303 // *b = 42;
1304 // foo(*a)
1305 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001306 //
1307 // NOTE: This is conservative, it will stop on any read from the source loc,
1308 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001309 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1310 MemoryLocation::getForSource(MDep), false,
1311 CS.getInstruction()->getIterator(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001312 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1313 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001314
Chris Lattner58f9f582010-11-21 00:28:59 +00001315 Value *TmpCast = MDep->getSource();
1316 if (MDep->getSource()->getType() != ByValArg->getType())
1317 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1318 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001319
Sean Silva6347df02016-06-14 02:44:55 +00001320 DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
Chris Lattner58f9f582010-11-21 00:28:59 +00001321 << " " << *MDep << "\n"
1322 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001323
Chris Lattner58f9f582010-11-21 00:28:59 +00001324 // Otherwise we're good! Update the byval argument.
1325 CS.setArgument(ArgNo, TmpCast);
1326 ++NumMemCpyInstr;
1327 return true;
1328}
1329
Sean Silva6347df02016-06-14 02:44:55 +00001330/// Executes one iteration of MemCpyOptPass.
1331bool MemCpyOptPass::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001332 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001333
Chris Lattnerb5557a72009-09-01 17:09:55 +00001334 // Walk all instruction in the function.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001335 for (BasicBlock &BB : F) {
1336 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001337 // Avoid invalidating the iterator.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001338 Instruction *I = &*BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001339
Chris Lattner58f9f582010-11-21 00:28:59 +00001340 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001341
Owen Anderson6a7355c2008-04-21 07:45:10 +00001342 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001343 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001344 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1345 RepeatInstruction = processMemSet(M, BI);
1346 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Tim Northover39617352016-05-10 21:49:40 +00001347 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001348 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001349 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001350 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001351 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001352 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001353 MadeChange |= processByValArgument(CS, i);
1354 }
1355
1356 // Reprocess the instruction if desired.
1357 if (RepeatInstruction) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001358 if (BI != BB.begin())
1359 --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001360 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001361 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001362 }
1363 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001364
Chris Lattnerb5557a72009-09-01 17:09:55 +00001365 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001366}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001367
Sean Silva6347df02016-06-14 02:44:55 +00001368PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001369
Sean Silva6347df02016-06-14 02:44:55 +00001370 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1371 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1372
1373 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1374 return AM.getResult<AAManager>(F);
1375 };
Sean Silva6347df02016-06-14 02:44:55 +00001376 auto LookupDomTree = [&]() -> DominatorTree & {
1377 return AM.getResult<DominatorTreeAnalysis>(F);
1378 };
1379
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001380 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis, LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001381 if (!MadeChange)
1382 return PreservedAnalyses::all();
1383 PreservedAnalyses PA;
1384 PA.preserve<GlobalsAA>();
1385 PA.preserve<MemoryDependenceAnalysis>();
1386 return PA;
1387}
1388
1389bool MemCpyOptPass::runImpl(
1390 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
1391 std::function<AliasAnalysis &()> LookupAliasAnalysis_,
Sean Silva6347df02016-06-14 02:44:55 +00001392 std::function<DominatorTree &()> LookupDomTree_) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001393 bool MadeChange = false;
Sean Silva6347df02016-06-14 02:44:55 +00001394 MD = MD_;
1395 TLI = TLI_;
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001396 LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001397 LookupDomTree = std::move(LookupDomTree_);
Nadav Rotem465834c2012-07-24 10:51:42 +00001398
Chris Lattner23f61a02011-05-01 18:27:11 +00001399 // If we don't have at least memset and memcpy, there is little point of doing
1400 // anything here. These are required by a freestanding implementation, so if
1401 // even they are disabled, there is no point in trying hard.
1402 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1403 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001404
Chris Lattnerb5557a72009-09-01 17:09:55 +00001405 while (1) {
1406 if (!iterateOnFunction(F))
1407 break;
1408 MadeChange = true;
1409 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001410
Craig Topperf40110f2014-04-25 05:29:35 +00001411 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001412 return MadeChange;
1413}
Sean Silva6347df02016-06-14 02:44:55 +00001414
1415/// This is the main transformation entry point for a function.
1416bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1417 if (skipFunction(F))
1418 return false;
1419
1420 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1421 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1422
1423 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1424 return getAnalysis<AAResultsWrapperPass>().getAAResults();
1425 };
Sean Silva6347df02016-06-14 02:44:55 +00001426 auto LookupDomTree = [this]() -> DominatorTree & {
1427 return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1428 };
1429
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001430 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001431}