blob: 3d84c3c9b1d2b76abff8fcf404d051a43fac29ab [file] [log] [blame]
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs various transformations related to eliminating memcpy
11// calls, or transforming sets of stores into memset's.
12//
13//===----------------------------------------------------------------------===//
14
Owen Andersonef9a6fd2008-04-09 08:23:16 +000015#include "llvm/Transforms/Scalar.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000016#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Statistic.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000019#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000020#include "llvm/Analysis/GlobalsModRef.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000021#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000026#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000031#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000033#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyf836c892015-07-21 21:56:26 +000034#include <algorithm>
Owen Andersonef9a6fd2008-04-09 08:23:16 +000035using namespace llvm;
36
Chandler Carruth964daaa2014-04-22 02:55:47 +000037#define DEBUG_TYPE "memcpyopt"
38
Owen Andersonef9a6fd2008-04-09 08:23:16 +000039STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
40STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000041STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000042STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000043
Benjamin Kramer15a257d2012-09-13 16:29:49 +000044static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000045 bool &VariableIdxFound,
46 const DataLayout &DL) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000047 // Skip over the first indices.
48 gep_type_iterator GTI = gep_type_begin(GEP);
49 for (unsigned i = 1; i != Idx; ++i, ++GTI)
50 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000051
Owen Andersonef9a6fd2008-04-09 08:23:16 +000052 // Compute the offset implied by the rest of the indices.
53 int64_t Offset = 0;
54 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
55 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +000056 if (!OpC)
Owen Andersonef9a6fd2008-04-09 08:23:16 +000057 return VariableIdxFound = true;
58 if (OpC->isZero()) continue; // No offset.
59
60 // Handle struct indices, which add their field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +000061 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000062 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000063 continue;
64 }
Nadav Rotem465834c2012-07-24 10:51:42 +000065
Owen Andersonef9a6fd2008-04-09 08:23:16 +000066 // Otherwise, we have a sequential type like an array or vector. Multiply
67 // the index by the ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000068 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000069 Offset += Size*OpC->getSExtValue();
70 }
71
72 return Offset;
73}
74
Sanjay Patela75c41e2015-08-13 22:53:20 +000075/// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
76/// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
77/// might be &A[40]. In this case offset would be -8.
Owen Andersonef9a6fd2008-04-09 08:23:16 +000078static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000079 const DataLayout &DL) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +000080 Ptr1 = Ptr1->stripPointerCasts();
81 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer3ef5e462014-03-10 21:05:13 +000082
83 // Handle the trivial case first.
84 if (Ptr1 == Ptr2) {
85 Offset = 0;
86 return true;
87 }
88
Benjamin Kramer15a257d2012-09-13 16:29:49 +000089 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
90 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +000091
Chris Lattner5120ebf2011-01-08 21:07:56 +000092 bool VariableIdxFound = false;
93
94 // If one pointer is a GEP and the other isn't, then see if the GEP is a
95 // constant offset from the base, as in "P" and "gep P, 1".
Craig Topperf40110f2014-04-25 05:29:35 +000096 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000097 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +000098 return !VariableIdxFound;
99 }
100
Craig Topperf40110f2014-04-25 05:29:35 +0000101 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000102 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +0000103 return !VariableIdxFound;
104 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000105
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000106 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
107 // base. After that base, they may have some number of common (and
108 // potentially variable) indices. After that they handle some constant
109 // offset, which determines their offset from each other. At this point, we
110 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000111 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
112 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000113
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000114 // Skip any common indices and track the GEP types.
115 unsigned Idx = 1;
116 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
117 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
118 break;
119
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000120 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
121 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000122 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000123
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000124 Offset = Offset2-Offset1;
125 return true;
126}
127
128
Sanjay Patela75c41e2015-08-13 22:53:20 +0000129/// Represents a range of memset'd bytes with the ByteVal value.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000130/// This allows us to analyze stores like:
131/// store 0 -> P+1
132/// store 0 -> P+0
133/// store 0 -> P+3
134/// store 0 -> P+2
135/// which sometimes happens with stores to arrays of structs etc. When we see
136/// the first store, we make a range [1, 2). The second store extends the range
137/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
138/// two ranges into [0, 3) which is memset'able.
139namespace {
140struct MemsetRange {
141 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000142 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000143 int64_t Start, End;
144
145 /// StartPtr - The getelementptr instruction that points to the start of the
146 /// range.
147 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000149 /// Alignment - The known alignment of the first store.
150 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000151
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000152 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000153 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000154
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000155 bool isProfitableToUseMemset(const DataLayout &DL) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000156};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000157} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000158
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
Chad Rosier32775572011-12-05 22:53:09 +0000160 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000161 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000162
163 // If there is nothing to merge, don't do anything.
164 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000165
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000166 // If any of the stores are a memset, then it is always good to extend the
167 // memset.
Craig Toppere325e382015-11-20 07:18:48 +0000168 for (Instruction *SI : TheStores)
169 if (!isa<StoreInst>(SI))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000170 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000171
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000172 // Assume that the code generator is capable of merging pairs of stores
173 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000174 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000175
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000176 // If we have fewer than 8 stores, it can still be worthwhile to do this.
177 // For example, merging 4 i8 stores into an i32 store is useful almost always.
178 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
179 // memset will be split into 2 32-bit stores anyway) and doing so can
180 // pessimize the llvm optimizer.
181 //
182 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000183 // the maximum GPR width is the same size as the largest legal integer
184 // size. If so, check to see whether we will end up actually reducing the
185 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000186 unsigned Bytes = unsigned(End-Start);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000187 unsigned MaxIntSize = DL.getLargestLegalIntTypeSize();
Matt Arsenault899f7d22013-09-16 22:43:16 +0000188 if (MaxIntSize == 0)
189 MaxIntSize = 1;
190 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000191
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000192 // Assume the remaining bytes if any are done a byte at a time.
Craig Toppera5ea5282015-11-21 17:44:42 +0000193 unsigned NumByteStores = Bytes % MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000194
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000195 // If we will reduce the # stores (according to this heuristic), do the
196 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
197 // etc.
198 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000199}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000200
201
202namespace {
203class MemsetRanges {
Sanjay Patela75c41e2015-08-13 22:53:20 +0000204 /// A sorted list of the memset ranges.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000205 SmallVector<MemsetRange, 8> Ranges;
206 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000207 const DataLayout &DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000208public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000209 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000210
Nick Lewyckyf836c892015-07-21 21:56:26 +0000211 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000212 const_iterator begin() const { return Ranges.begin(); }
213 const_iterator end() const { return Ranges.end(); }
214 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000215
Chris Lattnerc6381472011-01-08 20:24:01 +0000216 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000217 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
218 addStore(OffsetFromFirst, SI);
219 else
220 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000221 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000222
223 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000224 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000225
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000226 addRange(OffsetFromFirst, StoreSize,
227 SI->getPointerOperand(), SI->getAlignment(), SI);
228 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000229
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000230 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
231 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000232 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000233 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000234
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000235 void addRange(int64_t Start, int64_t Size, Value *Ptr,
236 unsigned Alignment, Instruction *Inst);
237
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000238};
Nadav Rotem465834c2012-07-24 10:51:42 +0000239
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000240} // end anon namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000241
242
Sanjay Patela75c41e2015-08-13 22:53:20 +0000243/// Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000244/// new range for the specified store at the specified offset, merging into
245/// existing ranges as appropriate.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000246void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
247 unsigned Alignment, Instruction *Inst) {
248 int64_t End = Start+Size;
Nadav Rotem465834c2012-07-24 10:51:42 +0000249
Nick Lewyckyf836c892015-07-21 21:56:26 +0000250 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
251 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
Nadav Rotem465834c2012-07-24 10:51:42 +0000252
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000253 // We now know that I == E, in which case we didn't find anything to merge
254 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
255 // to insert a new range. Handle this now.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000256 if (I == Ranges.end() || End < I->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000257 MemsetRange &R = *Ranges.insert(I, MemsetRange());
258 R.Start = Start;
259 R.End = End;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000260 R.StartPtr = Ptr;
261 R.Alignment = Alignment;
262 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000263 return;
264 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000265
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000266 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000267 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000268
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000269 // At this point, we may have an interval that completely contains our store.
270 // If so, just add it to the interval and return.
271 if (I->Start <= Start && I->End >= End)
272 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000273
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000274 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
275 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000276
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000277 // See if the range extends the start of the range. In this case, it couldn't
278 // possibly cause it to join the prior range, because otherwise we would have
279 // stopped on *it*.
280 if (Start < I->Start) {
281 I->Start = Start;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000282 I->StartPtr = Ptr;
283 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000284 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000285
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000286 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
287 // is in or right at the end of I), and that End >= I->Start. Extend I out to
288 // End.
289 if (End > I->End) {
290 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000291 range_iterator NextI = I;
Nick Lewyckyf836c892015-07-21 21:56:26 +0000292 while (++NextI != Ranges.end() && End >= NextI->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000293 // Merge the range in.
294 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
295 if (NextI->End > I->End)
296 I->End = NextI->End;
297 Ranges.erase(NextI);
298 NextI = I;
299 }
300 }
301}
302
303//===----------------------------------------------------------------------===//
304// MemCpyOpt Pass
305//===----------------------------------------------------------------------===//
306
307namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000308 class MemCpyOpt : public FunctionPass {
Chandler Carruth61440d22016-03-10 00:55:30 +0000309 MemoryDependenceResults *MD;
Chris Lattner23f61a02011-05-01 18:27:11 +0000310 TargetLibraryInfo *TLI;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000311 public:
312 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000313 MemCpyOpt() : FunctionPass(ID) {
314 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Craig Topperf40110f2014-04-25 05:29:35 +0000315 MD = nullptr;
316 TLI = nullptr;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000317 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000318
Craig Topper3e4c6972014-03-05 09:10:37 +0000319 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000320
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000321 private:
322 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000323 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000324 AU.setPreservesCFG();
Chandler Carruth66b31302015-01-04 12:03:27 +0000325 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000326 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000327 AU.addRequired<MemoryDependenceWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000328 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000329 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000330 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000331 AU.addPreserved<MemoryDependenceWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000332 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000333
Matt Walaa4afccd2015-06-12 18:16:51 +0000334 // Helper functions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000335 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000336 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000337 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000338 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000339 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000340 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000341 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000342 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000343 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
Chris Lattner58f9f582010-11-21 00:28:59 +0000344 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000345 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
346 Value *ByteVal);
347
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000348 bool iterateOnFunction(Function &F);
349 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000350
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000351 char MemCpyOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000352}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000353
Sanjay Patela75c41e2015-08-13 22:53:20 +0000354/// The public interface to this file...
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000355FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
356
Owen Anderson8ac477f2010-10-12 19:48:12 +0000357INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
358 false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000359INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000360INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth61440d22016-03-10 00:55:30 +0000361INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000362INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000363INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
364INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000365INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
366 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000367
Sanjay Patela75c41e2015-08-13 22:53:20 +0000368/// When scanning forward over instructions, we look for some other patterns to
369/// fold away. In particular, this looks for stores to neighboring locations of
370/// memory. If it sees enough consecutive ones, it attempts to merge them
371/// together into a memcpy/memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000372Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattnerc6381472011-01-08 20:24:01 +0000373 Value *StartPtr, Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000374 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000375
Chris Lattnerc6381472011-01-08 20:24:01 +0000376 // Okay, so we now have a single store that can be splatable. Scan to find
377 // all subsequent stores of the same value to offset from the same pointer.
378 // Join these together into ranges, so we can decide whether contiguous blocks
379 // are stored.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000381
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000382 BasicBlock::iterator BI(StartInst);
Chris Lattnerc6381472011-01-08 20:24:01 +0000383 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000384 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
385 // If the instruction is readnone, ignore it, otherwise bail out. We
386 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000387 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000388 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
389 break;
390 continue;
391 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000392
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000393 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
394 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000395 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000396
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000397 // Check to see if this stored value is of the same byte-splattable value.
398 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
399 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000400
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000401 // Check to see if this store is to a constant offset from the start ptr.
402 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000403 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
404 DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000405 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000406
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000407 Ranges.addStore(Offset, NextStore);
408 } else {
409 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000410
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000411 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
412 !isa<ConstantInt>(MSI->getLength()))
413 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000414
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000415 // Check to see if this store is to a constant offset from the start ptr.
416 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000417 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000418 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000419
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000420 Ranges.addMemSet(Offset, MSI);
421 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000422 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000423
Chris Lattnerc6381472011-01-08 20:24:01 +0000424 // If we have no ranges, then we just had a single store with nothing that
425 // could be merged in. This is a very common case of course.
426 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000427 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000428
Chris Lattnerc6381472011-01-08 20:24:01 +0000429 // If we had at least one store that could be merged in, add the starting
430 // store as well. We try to avoid this unless there is at least something
431 // interesting as a small compile-time optimization.
432 Ranges.addInst(0, StartInst);
433
434 // If we create any memsets, we put it right before the first instruction that
435 // isn't part of the memset block. This ensure that the memset is dominated
436 // by any addressing instruction needed by the start of the block.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000437 IRBuilder<> Builder(&*BI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000438
439 // Now that we have full information about ranges, loop over the ranges and
440 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000441 Instruction *AMemSet = nullptr;
Craig Toppere325e382015-11-20 07:18:48 +0000442 for (const MemsetRange &Range : Ranges) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000443
Chris Lattnerc6381472011-01-08 20:24:01 +0000444 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000445
Chris Lattnerc6381472011-01-08 20:24:01 +0000446 // If it is profitable to lower this range to memset, do so now.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000447 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000448 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000449
Chris Lattnerc6381472011-01-08 20:24:01 +0000450 // Otherwise, we do want to transform this! Create a new memset.
451 // Get the starting pointer of the block.
452 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000453
Chris Lattnerc6381472011-01-08 20:24:01 +0000454 // Determine alignment
455 unsigned Alignment = Range.Alignment;
456 if (Alignment == 0) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000457 Type *EltType =
Chris Lattnerc6381472011-01-08 20:24:01 +0000458 cast<PointerType>(StartPtr->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 Alignment = DL.getABITypeAlignment(EltType);
Chris Lattnerc6381472011-01-08 20:24:01 +0000460 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000461
462 AMemSet =
Chris Lattnerc6381472011-01-08 20:24:01 +0000463 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000464
Chris Lattnerc6381472011-01-08 20:24:01 +0000465 DEBUG(dbgs() << "Replace stores:\n";
Craig Toppere325e382015-11-20 07:18:48 +0000466 for (Instruction *SI : Range.TheStores)
467 dbgs() << *SI << '\n';
Chris Lattnerc6381472011-01-08 20:24:01 +0000468 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000469
470 if (!Range.TheStores.empty())
471 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
472
Chris Lattnerc6381472011-01-08 20:24:01 +0000473 // Zap all the stores.
Craig Toppere325e382015-11-20 07:18:48 +0000474 for (Instruction *SI : Range.TheStores) {
475 MD->removeInstruction(SI);
476 SI->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000477 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000478 ++NumMemSetInfer;
479 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000480
Chris Lattnerc6381472011-01-08 20:24:01 +0000481 return AMemSet;
482}
483
Amaury Secheta0c242c2016-01-05 20:17:48 +0000484static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
485 const LoadInst *LI) {
486 unsigned StoreAlign = SI->getAlignment();
487 if (!StoreAlign)
488 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
489 unsigned LoadAlign = LI->getAlignment();
490 if (!LoadAlign)
491 LoadAlign = DL.getABITypeAlignment(LI->getType());
492
493 return std::min(StoreAlign, LoadAlign);
494}
Chris Lattnerc6381472011-01-08 20:24:01 +0000495
Chris Lattnerb5557a72009-09-01 17:09:55 +0000496bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000497 if (!SI->isSimple()) return false;
Andrea Di Biagio99493df2015-10-09 10:53:41 +0000498
499 // Avoid merging nontemporal stores since the resulting
500 // memcpy/memset would not be able to preserve the nontemporal hint.
501 // In theory we could teach how to propagate the !nontemporal metadata to
502 // memset calls. However, that change would force the backend to
503 // conservatively expand !nontemporal memset calls back to sequences of
504 // store instructions (effectively undoing the merging).
505 if (SI->getMetadata(LLVMContext::MD_nontemporal))
506 return false;
507
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000508 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000509
Amaury Secheta0c242c2016-01-05 20:17:48 +0000510 // Load to store forwarding can be interpreted as memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000511 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000512 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000513 LI->getParent() == SI->getParent()) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000514
515 auto *T = LI->getType();
516 if (T->isAggregateType()) {
517 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
518 MemoryLocation LoadLoc = MemoryLocation::get(LI);
519
520 // We use alias analysis to check if an instruction may store to
521 // the memory we load from in between the load and the store. If
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000522 // such an instruction is found, we try to promote there instead
523 // of at the store position.
524 Instruction *P = SI;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000525 for (BasicBlock::iterator I = ++LI->getIterator(), E = SI->getIterator();
526 I != E; ++I) {
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000527 if (!(AA.getModRefInfo(&*I, LoadLoc) & MRI_Mod))
528 continue;
529
530 // We found an instruction that may write to the loaded memory.
531 // We can try to promote at this position instead of the store
Mehdi Amini05350032016-01-06 23:50:22 +0000532 // position if nothing alias the store memory after this and the store
533 // destination is not in the range.
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000534 P = &*I;
535 for (; I != E; ++I) {
536 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Mehdi Amini05350032016-01-06 23:50:22 +0000537 if (&*I == SI->getOperand(1) ||
538 AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000539 P = nullptr;
540 break;
541 }
Amaury Secheta0c242c2016-01-05 20:17:48 +0000542 }
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000543
544 break;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000545 }
546
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000547 // If a valid insertion position is found, then we can promote
548 // the load/store pair to a memcpy.
549 if (P) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000550 // If we load from memory that may alias the memory we store to,
551 // memmove must be used to preserve semantic. If not, memcpy can
552 // be used.
553 bool UseMemMove = false;
554 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
555 UseMemMove = true;
556
557 unsigned Align = findCommonAlignment(DL, SI, LI);
558 uint64_t Size = DL.getTypeStoreSize(T);
559
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000560 IRBuilder<> Builder(P);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000561 Instruction *M;
562 if (UseMemMove)
563 M = Builder.CreateMemMove(SI->getPointerOperand(),
564 LI->getPointerOperand(), Size,
565 Align, SI->isVolatile());
566 else
567 M = Builder.CreateMemCpy(SI->getPointerOperand(),
568 LI->getPointerOperand(), Size,
569 Align, SI->isVolatile());
570
571 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
572 << " => " << *M << "\n");
573
574 MD->removeInstruction(SI);
575 SI->eraseFromParent();
576 MD->removeInstruction(LI);
577 LI->eraseFromParent();
578 ++NumMemCpyInstr;
579
580 // Make sure we do not invalidate the iterator.
581 BBI = M->getIterator();
582 return true;
583 }
584 }
585
586 // Detect cases where we're performing call slot forwarding, but
587 // happen to be using a load-store pair to implement it, rather than
588 // a memcpy.
Eli Friedman5da0ff42011-06-02 21:24:42 +0000589 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000590 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000591 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
592 C = dyn_cast<CallInst>(ldep.getInst());
593
594 if (C) {
595 // Check that nothing touches the dest of the "copy" between
596 // the call and the store.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000597 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000598 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000599 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
600 I != E; --I) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000601 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000602 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000603 break;
604 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000605 }
606 }
607
Owen Anderson18e4fed2010-10-15 22:52:12 +0000608 if (C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000609 bool changed = performCallSlotOptzn(
610 LI, SI->getPointerOperand()->stripPointerCasts(),
611 LI->getPointerOperand()->stripPointerCasts(),
612 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
Amaury Secheta0c242c2016-01-05 20:17:48 +0000613 findCommonAlignment(DL, SI, LI), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000614 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000615 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000616 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000617 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000618 LI->eraseFromParent();
619 ++NumMemCpyInstr;
620 return true;
621 }
622 }
623 }
624 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000625
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000626 // There are two cases that are interesting for this code to handle: memcpy
627 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000628
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000629 // Ensure that the value being stored is something that can be memset'able a
630 // byte at a time like "0" or "-1" or any width, as well as things like
631 // 0xA0A0A0A0 and 0.0.
Amaury Sechet3235c082016-01-06 19:47:24 +0000632 auto *V = SI->getOperand(0);
633 if (Value *ByteVal = isBytewiseValue(V)) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000634 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
635 ByteVal)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000636 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerc6381472011-01-08 20:24:01 +0000637 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000638 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000639
Amaury Sechet3235c082016-01-06 19:47:24 +0000640 // If we have an aggregate, we try to promote it to memset regardless
641 // of opportunity for merging as it can expose optimization opportunities
642 // in subsequent passes.
643 auto *T = V->getType();
644 if (T->isAggregateType()) {
645 uint64_t Size = DL.getTypeStoreSize(T);
646 unsigned Align = SI->getAlignment();
647 if (!Align)
648 Align = DL.getABITypeAlignment(T);
649 IRBuilder<> Builder(SI);
650 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
651 Size, Align, SI->isVolatile());
652
653 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
654
655 MD->removeInstruction(SI);
656 SI->eraseFromParent();
657 NumMemSetInfer++;
658
659 // Make sure we do not invalidate the iterator.
660 BBI = M->getIterator();
661 return true;
662 }
663 }
664
Chris Lattnerc6381472011-01-08 20:24:01 +0000665 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000666}
667
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000668bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
669 // See if there is another memset or store neighboring this memset which
670 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000671 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
672 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
673 MSI->getValue())) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000674 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000675 return true;
676 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000677 return false;
678}
679
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000680
Sanjay Patela75c41e2015-08-13 22:53:20 +0000681/// Takes a memcpy and a call that it depends on,
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000682/// and checks for the possibility of a call slot optimization by having
683/// the call write its result directly into the destination of the memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000684bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
685 Value *cpyDest, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000686 uint64_t cpyLen, unsigned cpyAlign,
687 CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000688 // The general transformation to keep in mind is
689 //
690 // call @func(..., src, ...)
691 // memcpy(dest, src, ...)
692 //
693 // ->
694 //
695 // memcpy(dest, src, ...)
696 // call @func(..., dest, ...)
697 //
698 // Since moving the memcpy is technically awkward, we additionally check that
699 // src only holds uninitialized values at the moment of the call, meaning that
700 // the memcpy can be discarded rather than moved.
701
702 // Deliberately get the source and destination with bitcasts stripped away,
703 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000704 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000705
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000706 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000707 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000708 if (!srcAlloca)
709 return false;
710
Chris Lattnerb5557a72009-09-01 17:09:55 +0000711 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000712 if (!srcArraySize)
713 return false;
714
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000715 const DataLayout &DL = cpy->getModule()->getDataLayout();
716 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
717 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000718
Owen Anderson18e4fed2010-10-15 22:52:12 +0000719 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000720 return false;
721
722 // Check that accessing the first srcSize bytes of dest will not cause a
723 // trap. Otherwise the transform is invalid since it might cause a trap
724 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000725 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000726 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000727 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000728 if (!destArraySize)
729 return false;
730
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000731 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
732 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000733
734 if (destSize < srcSize)
735 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000736 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000737 if (A->getDereferenceableBytes() < srcSize) {
738 // If the destination is an sret parameter then only accesses that are
739 // outside of the returned struct type can trap.
740 if (!A->hasStructRetAttr())
741 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000742
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000743 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
744 if (!StructTy->isSized()) {
745 // The call may never return and hence the copy-instruction may never
746 // be executed, and therefore it's not safe to say "the destination
747 // has at least <cpyLen> bytes, as implied by the copy-instruction",
748 return false;
749 }
750
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000751 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000752 if (destSize < srcSize)
753 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000754 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000755 } else {
756 return false;
757 }
758
Duncan Sands933db772012-10-05 07:29:46 +0000759 // Check that dest points to memory that is at least as aligned as src.
760 unsigned srcAlign = srcAlloca->getAlignment();
761 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000762 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000763 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
764 // If dest is not aligned enough and we can't increase its alignment then
765 // bail out.
766 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
767 return false;
768
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000769 // Check that src is not accessed except via the call and the memcpy. This
770 // guarantees that it holds only undefined values when passed in (so the final
771 // memcpy can be dropped), that it is not read or written between the call and
772 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000773 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
774 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000775 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000776 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000777
Chandler Carruthcdf47882014-03-09 03:16:01 +0000778 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
779 for (User *UU : U->users())
780 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000781 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000782 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000783 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
784 if (!G->hasAllZeroIndices())
785 return false;
786
787 for (User *UU : U->users())
788 srcUseList.push_back(UU);
789 continue;
790 }
791 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
792 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
793 IT->getIntrinsicID() == Intrinsic::lifetime_end)
794 continue;
795
796 if (U != C && U != cpy)
797 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000798 }
799
Nick Lewycky703e4882014-07-14 18:52:02 +0000800 // Check that src isn't captured by the called function since the
801 // transformation can cause aliasing issues in that case.
802 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
803 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
804 return false;
805
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000806 // Since we're changing the parameter to the callsite, we need to make sure
807 // that what would be the new parameter dominates the callsite.
Chandler Carruth73523022014-01-13 13:07:17 +0000808 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000809 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000810 if (!DT.dominates(cpyDestInst, C))
811 return false;
812
813 // In addition to knowing that the call does not access src in some
814 // unexpected manner, for example via a global, which we deduce from
815 // the use analysis, we also need to know that it does not sneakily
816 // access dest. We rely on AA to figure this out for us.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000817 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth194f59c2015-07-22 23:15:57 +0000818 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
Chad Rosiera968caf2012-05-14 20:35:04 +0000819 // If necessary, perform additional analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000820 if (MR != MRI_NoModRef)
Chad Rosiera968caf2012-05-14 20:35:04 +0000821 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000822 if (MR != MRI_NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000823 return false;
824
825 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000826 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000827 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000828 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000829 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
830 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
831 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000832 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000833 if (CS.getArgument(i)->getType() == Dest->getType())
834 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000835 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000836 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
837 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000838 }
839
Owen Andersond071a872008-06-01 21:52:16 +0000840 if (!changedArgument)
841 return false;
842
Duncan Sandsc6ada692012-10-04 10:54:40 +0000843 // If the destination wasn't sufficiently aligned then increase its alignment.
844 if (!isDestSufficientlyAligned) {
845 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
846 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
847 }
848
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000849 // Drop any cached information about the call, because we may have changed
850 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000851 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000852
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000853 // Update AA metadata
854 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
855 // handled here, but combineMetadata doesn't support them yet
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +0000856 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
857 LLVMContext::MD_noalias,
858 LLVMContext::MD_invariant_group};
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000859 combineMetadata(C, cpy, KnownIDs);
860
Chris Lattner58f9f582010-11-21 00:28:59 +0000861 // Remove the memcpy.
862 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000863 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000864
865 return true;
866}
867
Sanjay Patela75c41e2015-08-13 22:53:20 +0000868/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
869/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000870bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000871 // We can only transforms memcpy's where the dest of one is the source of the
872 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000873 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000874 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000875
Chris Lattnerfd51c522010-12-09 07:39:50 +0000876 // If dep instruction is reading from our current input, then it is a noop
877 // transfer and substituting the input won't change this instruction. Just
878 // ignore the input and let someone else zap MDep. This handles cases like:
879 // memcpy(a <- a)
880 // memcpy(b <- a)
881 if (M->getSource() == MDep->getSource())
882 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000883
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000884 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000885 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000886 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
887 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
888 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
889 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000890
Chandler Carruth7b560d42015-09-09 17:55:00 +0000891 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chris Lattner59572292010-11-21 08:06:10 +0000892
893 // Verify that the copied-from memory doesn't change in between the two
894 // transfers. For example, in:
895 // memcpy(a <- b)
896 // *b = 42;
897 // memcpy(c <- a)
898 // It would be invalid to transform the second memcpy into memcpy(c <- b).
899 //
900 // TODO: If the code between M and MDep is transparent to the destination "c",
901 // then we could still perform the xform by moving M up to the first memcpy.
902 //
903 // NOTE: This is conservative, it will stop on any read from the source loc,
904 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000905 MemDepResult SourceDep =
906 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
907 M->getIterator(), M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +0000908 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
909 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000910
Chris Lattner731caac2010-11-18 08:00:57 +0000911 // If the dest of the second might alias the source of the first, then the
912 // source and dest might overlap. We still want to eliminate the intermediate
913 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000914 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +0000915 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
916 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000917 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000918
Chris Lattner58f9f582010-11-21 00:28:59 +0000919 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +0000920
Pete Cooper67cf9a72015-11-19 05:56:52 +0000921 // Make sure to use the lesser of the alignment of the source and the dest
922 // since we're changing where we're reading from, but don't want to increase
923 // the alignment past what can be read from or written to.
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000924 // TODO: Is this worth it if we're creating a less aligned memcpy? For
925 // example we could be moving from movaps -> movq on x86.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000926 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
927
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000928 IRBuilder<> Builder(M);
929 if (UseMemMove)
930 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000931 Align, M->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000932 else
933 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000934 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +0000935
Chris Lattner59572292010-11-21 08:06:10 +0000936 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +0000937 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +0000938 M->eraseFromParent();
939 ++NumMemCpyInstr;
940 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000941}
942
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000943/// We've found that the (upward scanning) memory dependence of \p MemCpy is
944/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
945/// weren't copied over by \p MemCpy.
946///
947/// In other words, transform:
948/// \code
949/// memset(dst, c, dst_size);
950/// memcpy(dst, src, src_size);
951/// \endcode
952/// into:
953/// \code
954/// memcpy(dst, src, src_size);
955/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
956/// \endcode
957bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
958 MemSetInst *MemSet) {
959 // We can only transform memset/memcpy with the same destination.
960 if (MemSet->getDest() != MemCpy->getDest())
961 return false;
962
Ahmed Bougacha97876fa2015-05-21 01:43:39 +0000963 // Check that there are no other dependencies on the memset destination.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000964 MemDepResult DstDepInfo =
965 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
966 MemCpy->getIterator(), MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +0000967 if (DstDepInfo.getInst() != MemSet)
968 return false;
969
Ahmed Bougacha9692e302015-04-21 21:28:33 +0000970 // Use the same i8* dest as the memcpy, killing the memset dest if different.
971 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000972 Value *DestSize = MemSet->getLength();
973 Value *SrcSize = MemCpy->getLength();
974
975 // By default, create an unaligned memset.
976 unsigned Align = 1;
977 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
978 // of the sum.
979 const unsigned DestAlign =
Pete Cooper67cf9a72015-11-19 05:56:52 +0000980 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000981 if (DestAlign > 1)
982 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
983 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
984
Ahmed Bougacha97876fa2015-05-21 01:43:39 +0000985 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000986
Ahmed Bougacha05b72c12015-04-18 23:06:04 +0000987 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +0000988 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +0000989 if (DestSize->getType()->getIntegerBitWidth() >
990 SrcSize->getType()->getIntegerBitWidth())
991 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
992 else
993 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +0000994 }
995
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000996 Value *MemsetLen =
997 Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
998 ConstantInt::getNullValue(DestSize->getType()),
999 Builder.CreateSub(DestSize, SrcSize));
1000 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1001 MemsetLen, Align);
1002
1003 MD->removeInstruction(MemSet);
1004 MemSet->eraseFromParent();
1005 return true;
1006}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001007
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001008/// Transform memcpy to memset when its source was just memset.
1009/// In other words, turn:
1010/// \code
1011/// memset(dst1, c, dst1_size);
1012/// memcpy(dst2, dst1, dst2_size);
1013/// \endcode
1014/// into:
1015/// \code
1016/// memset(dst1, c, dst1_size);
1017/// memset(dst2, c, dst2_size);
1018/// \endcode
1019/// When dst2_size <= dst1_size.
1020///
1021/// The \p MemCpy must have a Constant length.
1022bool MemCpyOpt::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1023 MemSetInst *MemSet) {
1024 // This only makes sense on memcpy(..., memset(...), ...).
1025 if (MemSet->getRawDest() != MemCpy->getRawSource())
1026 return false;
1027
1028 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1029 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1030 // Make sure the memcpy doesn't read any more than what the memset wrote.
1031 // Don't worry about sizes larger than i64.
1032 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1033 return false;
1034
Ahmed Bougacha0541c672015-05-21 00:08:35 +00001035 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001036 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001037 CopySize, MemCpy->getAlignment());
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001038 return true;
1039}
1040
Sanjay Patela75c41e2015-08-13 22:53:20 +00001041/// Perform simplification of memcpy's. If we have memcpy A
Gabor Greif62f0aac2010-07-28 22:50:26 +00001042/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1043/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1044/// circumstances). This allows later passes to remove the first memcpy
1045/// altogether.
Chris Lattnerb5557a72009-09-01 17:09:55 +00001046bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +00001047 // We can only optimize non-volatile memcpy's.
1048 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +00001049
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001050 // If the source and destination of the memcpy are the same, then zap it.
1051 if (M->getSource() == M->getDest()) {
1052 MD->removeInstruction(M);
1053 M->eraseFromParent();
1054 return false;
1055 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001056
1057 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001058 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +00001059 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001060 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001061 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +00001062 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001063 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001064 MD->removeInstruction(M);
1065 M->eraseFromParent();
1066 ++NumCpyToSet;
1067 return true;
1068 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001069
Ahmed Bougachab6169662015-05-11 23:09:46 +00001070 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001071
1072 // Try to turn a partially redundant memset + memcpy into
1073 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +00001074 if (DepInfo.isClobber())
1075 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001076 if (processMemSetMemCpyDependence(M, MDep))
1077 return true;
1078
Nick Lewycky00703e72014-02-04 00:18:54 +00001079 // The optimizations after this point require the memcpy size.
1080 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001081 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +00001082
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001083 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +00001084 // a) memcpy-memcpy xform which exposes redundance for DSE.
1085 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001086 // c) memcpy from freshly alloca'd space or space that has just started its
1087 // lifetime copies undefined data, and we can therefore eliminate the
1088 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001089 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001090 if (DepInfo.isClobber()) {
1091 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1092 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001093 CopySize->getZExtValue(), M->getAlignment(),
Duncan Sandsc6ada692012-10-04 10:54:40 +00001094 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001095 MD->removeInstruction(M);
1096 M->eraseFromParent();
1097 return true;
1098 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001099 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001100 }
Ahmed Charles32e983e2012-02-13 06:30:56 +00001101
Chandler Carruthac80dc72015-06-17 07:18:54 +00001102 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001103 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1104 SrcLoc, true, M->getIterator(), M->getParent());
Ahmed Bougachab6169662015-05-11 23:09:46 +00001105
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001106 if (SrcDepInfo.isClobber()) {
1107 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +00001108 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001109 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001110 Instruction *I = SrcDepInfo.getInst();
1111 bool hasUndefContents = false;
1112
1113 if (isa<AllocaInst>(I)) {
1114 hasUndefContents = true;
1115 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1116 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1117 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1118 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1119 hasUndefContents = true;
1120 }
1121
1122 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +00001123 MD->removeInstruction(M);
1124 M->eraseFromParent();
1125 ++NumMemCpyInstr;
1126 return true;
1127 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001128 }
1129
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001130 if (SrcDepInfo.isClobber())
1131 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1132 if (performMemCpyToMemSetOptzn(M, MDep)) {
1133 MD->removeInstruction(M);
1134 M->eraseFromParent();
1135 ++NumCpyToSet;
1136 return true;
1137 }
1138
Owen Andersonad5367f2008-04-29 21:51:00 +00001139 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001140}
1141
Sanjay Patela75c41e2015-08-13 22:53:20 +00001142/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1143/// not to alias.
Chris Lattner1145e332009-09-01 17:56:32 +00001144bool MemCpyOpt::processMemMove(MemMoveInst *M) {
Chandler Carruth7b560d42015-09-09 17:55:00 +00001145 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Chris Lattner1145e332009-09-01 17:56:32 +00001146
Chris Lattner23f61a02011-05-01 18:27:11 +00001147 if (!TLI->has(LibFunc::memmove))
1148 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001149
Chris Lattner1145e332009-09-01 17:56:32 +00001150 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001151 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1152 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001153 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001154
David Greene24199232010-01-05 01:27:47 +00001155 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001156
Chris Lattner1145e332009-09-01 17:56:32 +00001157 // If not, then we know we can transform this.
Jay Foadb804a2b2011-07-12 14:06:48 +00001158 Type *ArgTys[3] = { M->getRawDest()->getType(),
1159 M->getRawSource()->getType(),
1160 M->getLength()->getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001161 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1162 Intrinsic::memcpy, ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001163
Chris Lattner1145e332009-09-01 17:56:32 +00001164 // MemDep may have over conservative information about this instruction, just
1165 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001166 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001167
1168 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001169 return true;
1170}
Nadav Rotem465834c2012-07-24 10:51:42 +00001171
Sanjay Patela75c41e2015-08-13 22:53:20 +00001172/// This is called on every byval argument in call sites.
Chris Lattner58f9f582010-11-21 00:28:59 +00001173bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001174 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001175 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001176 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001177 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001178 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001179 MemDepResult DepInfo = MD->getPointerDependencyFrom(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001180 MemoryLocation(ByValArg, ByValSize), true,
1181 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001182 if (!DepInfo.isClobber())
1183 return false;
1184
1185 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1186 // a memcpy, see if we can byval from the source of the memcpy instead of the
1187 // result.
1188 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001189 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001190 ByValArg->stripPointerCasts() != MDep->getDest())
1191 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001192
Chris Lattner58f9f582010-11-21 00:28:59 +00001193 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001194 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001195 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001196 return false;
1197
Chris Lattner83791ce2011-05-23 00:03:39 +00001198 // Get the alignment of the byval. If the call doesn't specify the alignment,
1199 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +00001200 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +00001201 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001202
Chris Lattner83791ce2011-05-23 00:03:39 +00001203 // If it is greater than the memcpy, then we check to see if we can force the
1204 // source of the memcpy to the alignment we need. If we fail, we bail out.
Chandler Carruth66b31302015-01-04 12:03:27 +00001205 AssumptionCache &AC =
1206 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
1207 *CS->getParent()->getParent());
Hal Finkel60db0582014-09-07 18:57:58 +00001208 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Pete Cooper67cf9a72015-11-19 05:56:52 +00001209 if (MDep->getAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001210 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1211 CS.getInstruction(), &AC, &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001212 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001213
Chris Lattner58f9f582010-11-21 00:28:59 +00001214 // Verify that the copied-from memory doesn't change in between the memcpy and
1215 // the byval call.
1216 // memcpy(a <- b)
1217 // *b = 42;
1218 // foo(*a)
1219 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001220 //
1221 // NOTE: This is conservative, it will stop on any read from the source loc,
1222 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001223 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1224 MemoryLocation::getForSource(MDep), false,
1225 CS.getInstruction()->getIterator(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001226 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1227 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001228
Chris Lattner58f9f582010-11-21 00:28:59 +00001229 Value *TmpCast = MDep->getSource();
1230 if (MDep->getSource()->getType() != ByValArg->getType())
1231 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1232 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001233
Chris Lattner58f9f582010-11-21 00:28:59 +00001234 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
1235 << " " << *MDep << "\n"
1236 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001237
Chris Lattner58f9f582010-11-21 00:28:59 +00001238 // Otherwise we're good! Update the byval argument.
1239 CS.setArgument(ArgNo, TmpCast);
1240 ++NumMemCpyInstr;
1241 return true;
1242}
1243
Sanjay Patela75c41e2015-08-13 22:53:20 +00001244/// Executes one iteration of MemCpyOpt.
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001245bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001246 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001247
Chris Lattnerb5557a72009-09-01 17:09:55 +00001248 // Walk all instruction in the function.
Owen Anderson6a7355c2008-04-21 07:45:10 +00001249 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001250 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001251 // Avoid invalidating the iterator.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001252 Instruction *I = &*BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001253
Chris Lattner58f9f582010-11-21 00:28:59 +00001254 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001255
Owen Anderson6a7355c2008-04-21 07:45:10 +00001256 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001257 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001258 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1259 RepeatInstruction = processMemSet(M, BI);
1260 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001261 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001262 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001263 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001264 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001265 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001266 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001267 MadeChange |= processByValArgument(CS, i);
1268 }
1269
1270 // Reprocess the instruction if desired.
1271 if (RepeatInstruction) {
Chris Lattner7d6433a2011-01-08 22:19:21 +00001272 if (BI != BB->begin()) --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001273 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001274 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001275 }
1276 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001277
Chris Lattnerb5557a72009-09-01 17:09:55 +00001278 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001279}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001280
Sanjay Patela75c41e2015-08-13 22:53:20 +00001281/// This is the main transformation entry point for a function.
Chris Lattnerb5557a72009-09-01 17:09:55 +00001282bool MemCpyOpt::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001283 if (skipOptnoneFunction(F))
1284 return false;
1285
Chris Lattnerb5557a72009-09-01 17:09:55 +00001286 bool MadeChange = false;
Chandler Carruth61440d22016-03-10 00:55:30 +00001287 MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001288 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Nadav Rotem465834c2012-07-24 10:51:42 +00001289
Chris Lattner23f61a02011-05-01 18:27:11 +00001290 // If we don't have at least memset and memcpy, there is little point of doing
1291 // anything here. These are required by a freestanding implementation, so if
1292 // even they are disabled, there is no point in trying hard.
1293 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1294 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001295
Chris Lattnerb5557a72009-09-01 17:09:55 +00001296 while (1) {
1297 if (!iterateOnFunction(F))
1298 break;
1299 MadeChange = true;
1300 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001301
Craig Topperf40110f2014-04-25 05:29:35 +00001302 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001303 return MadeChange;
1304}