blob: a800471375386d92f0bf528b6c4572b095119e88 [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
Amaury Sechetbdb261b2016-03-14 22:52:27 +000015#include "llvm/ADT/DenseSet.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000016#include "llvm/ADT/iterator_range.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/Analysis/AssumptionCache.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/MemoryDependenceAnalysis.h"
23#include "llvm/Analysis/MemoryLocation.h"
24#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000025#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000026#include "llvm/IR/Argument.h"
27#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000029#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000032#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000034#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Instruction.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/IRBuilder.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000040#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Module.h"
42#include "llvm/IR/Operator.h"
43#include "llvm/IR/Type.h"
44#include "llvm/IR/User.h"
45#include "llvm/IR/Value.h"
46#include "llvm/Pass.h"
47#include "llvm/Support/Casting.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000048#include "llvm/Support/Debug.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000050#include "llvm/Support/raw_ostream.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000051#include "llvm/Transforms/Scalar.h"
52#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Transforms/Utils/Local.h"
Nick Lewyckyf836c892015-07-21 21:56:26 +000054#include <algorithm>
Eugene Zelenko34c23272017-01-18 00:57:48 +000055#include <cassert>
56#include <cstdint>
57
Owen Andersonef9a6fd2008-04-09 08:23:16 +000058using namespace llvm;
59
Chandler Carruth964daaa2014-04-22 02:55:47 +000060#define DEBUG_TYPE "memcpyopt"
61
Owen Andersonef9a6fd2008-04-09 08:23:16 +000062STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
63STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000064STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000065STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000066
Benjamin Kramer15a257d2012-09-13 16:29:49 +000067static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000068 bool &VariableIdxFound,
69 const DataLayout &DL) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000070 // Skip over the first indices.
71 gep_type_iterator GTI = gep_type_begin(GEP);
72 for (unsigned i = 1; i != Idx; ++i, ++GTI)
73 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000074
Owen Andersonef9a6fd2008-04-09 08:23:16 +000075 // Compute the offset implied by the rest of the indices.
76 int64_t Offset = 0;
77 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
78 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +000079 if (!OpC)
Owen Andersonef9a6fd2008-04-09 08:23:16 +000080 return VariableIdxFound = true;
81 if (OpC->isZero()) continue; // No offset.
82
83 // Handle struct indices, which add their field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +000084 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000085 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000086 continue;
87 }
Nadav Rotem465834c2012-07-24 10:51:42 +000088
Owen Andersonef9a6fd2008-04-09 08:23:16 +000089 // Otherwise, we have a sequential type like an array or vector. Multiply
90 // the index by the ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000091 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000092 Offset += Size*OpC->getSExtValue();
93 }
94
95 return Offset;
96}
97
Sanjay Patela75c41e2015-08-13 22:53:20 +000098/// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
99/// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
100/// might be &A[40]. In this case offset would be -8.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000101static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000102 const DataLayout &DL) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +0000103 Ptr1 = Ptr1->stripPointerCasts();
104 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer3ef5e462014-03-10 21:05:13 +0000105
106 // Handle the trivial case first.
107 if (Ptr1 == Ptr2) {
108 Offset = 0;
109 return true;
110 }
111
Benjamin Kramer15a257d2012-09-13 16:29:49 +0000112 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
113 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +0000114
Chris Lattner5120ebf2011-01-08 21:07:56 +0000115 bool VariableIdxFound = false;
116
117 // If one pointer is a GEP and the other isn't, then see if the GEP is a
118 // constant offset from the base, as in "P" and "gep P, 1".
Craig Topperf40110f2014-04-25 05:29:35 +0000119 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000120 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +0000121 return !VariableIdxFound;
122 }
123
Craig Topperf40110f2014-04-25 05:29:35 +0000124 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000125 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
Chris Lattner5120ebf2011-01-08 21:07:56 +0000126 return !VariableIdxFound;
127 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000128
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000129 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
130 // base. After that base, they may have some number of common (and
131 // potentially variable) indices. After that they handle some constant
132 // offset, which determines their offset from each other. At this point, we
133 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000134 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
135 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000136
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000137 // Skip any common indices and track the GEP types.
138 unsigned Idx = 1;
139 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
140 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
141 break;
142
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
144 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000145 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000146
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000147 Offset = Offset2-Offset1;
148 return true;
149}
150
Eugene Zelenko34c23272017-01-18 00:57:48 +0000151namespace {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000152
Sanjay Patela75c41e2015-08-13 22:53:20 +0000153/// Represents a range of memset'd bytes with the ByteVal value.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000154/// This allows us to analyze stores like:
155/// store 0 -> P+1
156/// store 0 -> P+0
157/// store 0 -> P+3
158/// store 0 -> P+2
159/// which sometimes happens with stores to arrays of structs etc. When we see
160/// the first store, we make a range [1, 2). The second store extends the range
161/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
162/// two ranges into [0, 3) which is memset'able.
Tim Northover39617352016-05-10 21:49:40 +0000163struct MemsetRange {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000164 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000165 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000166 int64_t Start, End;
167
168 /// StartPtr - The getelementptr instruction that points to the start of the
169 /// range.
Tim Northover39617352016-05-10 21:49:40 +0000170 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000171
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000172 /// Alignment - The known alignment of the first store.
173 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000174
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000175 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000176 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000177
Tim Northover39617352016-05-10 21:49:40 +0000178 bool isProfitableToUseMemset(const DataLayout &DL) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000179};
Eugene Zelenko34c23272017-01-18 00:57:48 +0000180
181} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000182
Tim Northover39617352016-05-10 21:49:40 +0000183bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
184 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000185 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000186
187 // If there is nothing to merge, don't do anything.
188 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000189
Tim Northover39617352016-05-10 21:49:40 +0000190 // If any of the stores are a memset, then it is always good to extend the
191 // memset.
Craig Toppere325e382015-11-20 07:18:48 +0000192 for (Instruction *SI : TheStores)
Tim Northover39617352016-05-10 21:49:40 +0000193 if (!isa<StoreInst>(SI))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000194 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000195
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000196 // Assume that the code generator is capable of merging pairs of stores
197 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000198 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000199
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000200 // If we have fewer than 8 stores, it can still be worthwhile to do this.
201 // For example, merging 4 i8 stores into an i32 store is useful almost always.
202 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
203 // memset will be split into 2 32-bit stores anyway) and doing so can
204 // pessimize the llvm optimizer.
205 //
206 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000207 // the maximum GPR width is the same size as the largest legal integer
208 // size. If so, check to see whether we will end up actually reducing the
209 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000210 unsigned Bytes = unsigned(End-Start);
Jun Bum Limbe11bdc2016-05-13 18:38:35 +0000211 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
Matt Arsenault899f7d22013-09-16 22:43:16 +0000212 if (MaxIntSize == 0)
213 MaxIntSize = 1;
214 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000215
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000216 // Assume the remaining bytes if any are done a byte at a time.
Craig Toppera5ea5282015-11-21 17:44:42 +0000217 unsigned NumByteStores = Bytes % MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000218
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000219 // If we will reduce the # stores (according to this heuristic), do the
220 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
221 // etc.
222 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000223}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000224
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000225namespace {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000226
Tim Northover39617352016-05-10 21:49:40 +0000227class MemsetRanges {
Sanjay Patela75c41e2015-08-13 22:53:20 +0000228 /// A sorted list of the memset ranges.
Tim Northover39617352016-05-10 21:49:40 +0000229 SmallVector<MemsetRange, 8> Ranges;
230 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000231 const DataLayout &DL;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000232
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000233public:
Tim Northover39617352016-05-10 21:49:40 +0000234 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000235
Tim Northover39617352016-05-10 21:49:40 +0000236 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000237 const_iterator begin() const { return Ranges.begin(); }
238 const_iterator end() const { return Ranges.end(); }
239 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000240
Chris Lattnerc6381472011-01-08 20:24:01 +0000241 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000242 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
243 addStore(OffsetFromFirst, SI);
244 else
245 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000246 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000247
248 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000249 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000250
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000251 addRange(OffsetFromFirst, StoreSize,
Tim Northover39617352016-05-10 21:49:40 +0000252 SI->getPointerOperand(), SI->getAlignment(), SI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000253 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000254
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000255 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
256 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Tim Northover39617352016-05-10 21:49:40 +0000257 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000258 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000259
Tim Northover39617352016-05-10 21:49:40 +0000260 void addRange(int64_t Start, int64_t Size, Value *Ptr,
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000261 unsigned Alignment, Instruction *Inst);
262
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000263};
Nadav Rotem465834c2012-07-24 10:51:42 +0000264
Eugene Zelenko34c23272017-01-18 00:57:48 +0000265} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000266
Tim Northover39617352016-05-10 21:49:40 +0000267/// Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000268/// new range for the specified store at the specified offset, merging into
269/// existing ranges as appropriate.
Tim Northover39617352016-05-10 21:49:40 +0000270void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
271 unsigned Alignment, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000272 int64_t End = Start+Size;
Nadav Rotem465834c2012-07-24 10:51:42 +0000273
Nick Lewyckyf836c892015-07-21 21:56:26 +0000274 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
Tim Northover39617352016-05-10 21:49:40 +0000275 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
Nadav Rotem465834c2012-07-24 10:51:42 +0000276
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000277 // We now know that I == E, in which case we didn't find anything to merge
278 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
279 // to insert a new range. Handle this now.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000280 if (I == Ranges.end() || End < I->Start) {
Tim Northover39617352016-05-10 21:49:40 +0000281 MemsetRange &R = *Ranges.insert(I, MemsetRange());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000282 R.Start = Start;
283 R.End = End;
Tim Northover39617352016-05-10 21:49:40 +0000284 R.StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000285 R.Alignment = Alignment;
286 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000287 return;
288 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000289
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000290 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000291 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000292
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000293 // At this point, we may have an interval that completely contains our store.
294 // If so, just add it to the interval and return.
295 if (I->Start <= Start && I->End >= End)
296 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000297
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000298 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
299 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000300
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000301 // See if the range extends the start of the range. In this case, it couldn't
302 // possibly cause it to join the prior range, because otherwise we would have
303 // stopped on *it*.
304 if (Start < I->Start) {
305 I->Start = Start;
Tim Northover39617352016-05-10 21:49:40 +0000306 I->StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000307 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000308 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000309
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000310 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
311 // is in or right at the end of I), and that End >= I->Start. Extend I out to
312 // End.
313 if (End > I->End) {
314 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000315 range_iterator NextI = I;
Nick Lewyckyf836c892015-07-21 21:56:26 +0000316 while (++NextI != Ranges.end() && End >= NextI->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000317 // Merge the range in.
318 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
319 if (NextI->End > I->End)
320 I->End = NextI->End;
321 Ranges.erase(NextI);
322 NextI = I;
323 }
324 }
325}
326
327//===----------------------------------------------------------------------===//
Sean Silva6347df02016-06-14 02:44:55 +0000328// MemCpyOptLegacyPass Pass
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000329//===----------------------------------------------------------------------===//
330
331namespace {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000332
Sean Silva6347df02016-06-14 02:44:55 +0000333 class MemCpyOptLegacyPass : public FunctionPass {
334 MemCpyOptPass Impl;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000335
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000336 public:
337 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko34c23272017-01-18 00:57:48 +0000338
Sean Silva6347df02016-06-14 02:44:55 +0000339 MemCpyOptLegacyPass() : FunctionPass(ID) {
340 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000341 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000342
Craig Topper3e4c6972014-03-05 09:10:37 +0000343 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000344
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000345 private:
346 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000347 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000348 AU.setPreservesCFG();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000349 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000350 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000351 AU.addRequired<MemoryDependenceWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000352 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000353 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000354 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth61440d22016-03-10 00:55:30 +0000355 AU.addPreserved<MemoryDependenceWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000356 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000357
Matt Walaa4afccd2015-06-12 18:16:51 +0000358 // Helper functions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000359 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000360 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Tim Northover39617352016-05-10 21:49:40 +0000361 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000362 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000363 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000364 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Ahmed Bougacha15a31f62015-05-16 01:23:47 +0000365 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000366 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +0000367 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
Chris Lattner58f9f582010-11-21 00:28:59 +0000368 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000369 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
370 Value *ByteVal);
371
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000372 bool iterateOnFunction(Function &F);
373 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000374
Sean Silva6347df02016-06-14 02:44:55 +0000375 char MemCpyOptLegacyPass::ID = 0;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000376
377} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000378
Sanjay Patela75c41e2015-08-13 22:53:20 +0000379/// The public interface to this file...
Sean Silva6347df02016-06-14 02:44:55 +0000380FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000381
Sean Silva6347df02016-06-14 02:44:55 +0000382INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000383 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000384INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000385INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth61440d22016-03-10 00:55:30 +0000386INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000387INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000388INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
389INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Sean Silva6347df02016-06-14 02:44:55 +0000390INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000391 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000392
Sanjay Patela75c41e2015-08-13 22:53:20 +0000393/// When scanning forward over instructions, we look for some other patterns to
394/// fold away. In particular, this looks for stores to neighboring locations of
395/// memory. If it sees enough consecutive ones, it attempts to merge them
396/// together into a memcpy/memset.
Sean Silva6347df02016-06-14 02:44:55 +0000397Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
398 Value *StartPtr,
399 Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000401
Chris Lattnerc6381472011-01-08 20:24:01 +0000402 // Okay, so we now have a single store that can be splatable. Scan to find
403 // all subsequent stores of the same value to offset from the same pointer.
404 // Join these together into ranges, so we can decide whether contiguous blocks
405 // are stored.
Tim Northover39617352016-05-10 21:49:40 +0000406 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000407
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000408 BasicBlock::iterator BI(StartInst);
Chris Lattnerc6381472011-01-08 20:24:01 +0000409 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000410 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
411 // If the instruction is readnone, ignore it, otherwise bail out. We
412 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000413 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000414 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
415 break;
416 continue;
417 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000418
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000419 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
420 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000421 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000422
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000423 // Check to see if this stored value is of the same byte-splattable value.
424 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
425 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000426
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000427 // Check to see if this store is to a constant offset from the start ptr.
428 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000429 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
430 DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000431 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000432
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000433 Ranges.addStore(Offset, NextStore);
434 } else {
435 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000436
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000437 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
438 !isa<ConstantInt>(MSI->getLength()))
439 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000440
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000441 // Check to see if this store is to a constant offset from the start ptr.
442 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000443 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000444 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000445
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000446 Ranges.addMemSet(Offset, MSI);
447 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000448 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000449
Chris Lattnerc6381472011-01-08 20:24:01 +0000450 // If we have no ranges, then we just had a single store with nothing that
451 // could be merged in. This is a very common case of course.
452 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000453 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000454
Chris Lattnerc6381472011-01-08 20:24:01 +0000455 // If we had at least one store that could be merged in, add the starting
456 // store as well. We try to avoid this unless there is at least something
457 // interesting as a small compile-time optimization.
458 Ranges.addInst(0, StartInst);
459
460 // If we create any memsets, we put it right before the first instruction that
461 // isn't part of the memset block. This ensure that the memset is dominated
462 // by any addressing instruction needed by the start of the block.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000463 IRBuilder<> Builder(&*BI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000464
465 // Now that we have full information about ranges, loop over the ranges and
466 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000467 Instruction *AMemSet = nullptr;
Tim Northover39617352016-05-10 21:49:40 +0000468 for (const MemsetRange &Range : Ranges) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000469
Chris Lattnerc6381472011-01-08 20:24:01 +0000470 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000471
Chris Lattnerc6381472011-01-08 20:24:01 +0000472 // If it is profitable to lower this range to memset, do so now.
Tim Northover39617352016-05-10 21:49:40 +0000473 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000474 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000475
Chris Lattnerc6381472011-01-08 20:24:01 +0000476 // Otherwise, we do want to transform this! Create a new memset.
477 // Get the starting pointer of the block.
Tim Northover39617352016-05-10 21:49:40 +0000478 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000479
Tim Northover39617352016-05-10 21:49:40 +0000480 // Determine alignment
481 unsigned Alignment = Range.Alignment;
482 if (Alignment == 0) {
483 Type *EltType =
484 cast<PointerType>(StartPtr->getType())->getElementType();
485 Alignment = DL.getABITypeAlignment(EltType);
486 }
487
488 AMemSet =
489 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000490
Chris Lattnerc6381472011-01-08 20:24:01 +0000491 DEBUG(dbgs() << "Replace stores:\n";
Craig Toppere325e382015-11-20 07:18:48 +0000492 for (Instruction *SI : Range.TheStores)
493 dbgs() << *SI << '\n';
Chris Lattnerc6381472011-01-08 20:24:01 +0000494 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000495
496 if (!Range.TheStores.empty())
497 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
498
Chris Lattnerc6381472011-01-08 20:24:01 +0000499 // Zap all the stores.
Craig Toppere325e382015-11-20 07:18:48 +0000500 for (Instruction *SI : Range.TheStores) {
501 MD->removeInstruction(SI);
502 SI->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000503 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000504 ++NumMemSetInfer;
505 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000506
Chris Lattnerc6381472011-01-08 20:24:01 +0000507 return AMemSet;
508}
509
Tim Northover39617352016-05-10 21:49:40 +0000510static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
511 const LoadInst *LI) {
512 unsigned StoreAlign = SI->getAlignment();
513 if (!StoreAlign)
514 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
515 unsigned LoadAlign = LI->getAlignment();
516 if (!LoadAlign)
517 LoadAlign = DL.getABITypeAlignment(LI->getType());
Amaury Secheta0c242c2016-01-05 20:17:48 +0000518
Tim Northover39617352016-05-10 21:49:40 +0000519 return std::min(StoreAlign, LoadAlign);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000520}
Chris Lattnerc6381472011-01-08 20:24:01 +0000521
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000522// This method try to lift a store instruction before position P.
523// It will lift the store and its argument + that anything that
David Majnemerd99068d2016-05-26 19:24:24 +0000524// may alias with these.
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000525// The method returns true if it was successful.
Bryant Wong7cb74462016-12-27 17:58:12 +0000526static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P,
527 const LoadInst *LI) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000528 // If the store alias this position, early bail out.
529 MemoryLocation StoreLoc = MemoryLocation::get(SI);
530 if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef)
531 return false;
532
533 // Keep track of the arguments of all instruction we plan to lift
534 // so we can make sure to lift them as well if apropriate.
535 DenseSet<Instruction*> Args;
536 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
537 if (Ptr->getParent() == SI->getParent())
538 Args.insert(Ptr);
539
540 // Instruction to lift before P.
541 SmallVector<Instruction*, 8> ToLift;
542
543 // Memory locations of lifted instructions.
Bryant Wong7cb74462016-12-27 17:58:12 +0000544 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000545
546 // Lifted callsites.
547 SmallVector<ImmutableCallSite, 8> CallSites;
548
Bryant Wong7cb74462016-12-27 17:58:12 +0000549 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
550
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000551 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
552 auto *C = &*I;
553
554 bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef;
555
556 bool NeedLift = false;
557 if (Args.erase(C))
558 NeedLift = true;
559 else if (MayAlias) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000560 NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
David Majnemer0a16c222016-08-11 21:15:00 +0000561 return AA.getModRefInfo(C, ML);
562 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000563
564 if (!NeedLift)
Eugene Zelenko34c23272017-01-18 00:57:48 +0000565 NeedLift =
566 llvm::any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) {
567 return AA.getModRefInfo(C, CS);
568 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000569 }
570
571 if (!NeedLift)
572 continue;
573
574 if (MayAlias) {
Bryant Wong7cb74462016-12-27 17:58:12 +0000575 // Since LI is implicitly moved downwards past the lifted instructions,
576 // none of them may modify its source.
577 if (AA.getModRefInfo(C, LoadLoc) & MRI_Mod)
578 return false;
579 else if (auto CS = ImmutableCallSite(C)) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000580 // If we can't lift this before P, it's game over.
581 if (AA.getModRefInfo(P, CS) != MRI_NoModRef)
582 return false;
583
584 CallSites.push_back(CS);
585 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
586 // If we can't lift this before P, it's game over.
587 auto ML = MemoryLocation::get(C);
588 if (AA.getModRefInfo(P, ML) != MRI_NoModRef)
589 return false;
590
591 MemLocs.push_back(ML);
592 } else
593 // We don't know how to lift this instruction.
594 return false;
595 }
596
597 ToLift.push_back(C);
598 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
599 if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
600 if (A->getParent() == SI->getParent())
601 Args.insert(A);
602 }
603
604 // We made it, we need to lift
Eugene Zelenko34c23272017-01-18 00:57:48 +0000605 for (auto *I : llvm::reverse(ToLift)) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000606 DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
607 I->moveBefore(P);
608 }
609
610 return true;
611}
612
Sean Silva6347df02016-06-14 02:44:55 +0000613bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000614 if (!SI->isSimple()) return false;
Andrea Di Biagio99493df2015-10-09 10:53:41 +0000615
616 // Avoid merging nontemporal stores since the resulting
617 // memcpy/memset would not be able to preserve the nontemporal hint.
618 // In theory we could teach how to propagate the !nontemporal metadata to
619 // memset calls. However, that change would force the backend to
620 // conservatively expand !nontemporal memset calls back to sequences of
621 // store instructions (effectively undoing the merging).
622 if (SI->getMetadata(LLVMContext::MD_nontemporal))
623 return false;
624
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000626
Amaury Secheta0c242c2016-01-05 20:17:48 +0000627 // Load to store forwarding can be interpreted as memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000628 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000629 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000630 LI->getParent() == SI->getParent()) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000631
632 auto *T = LI->getType();
633 if (T->isAggregateType()) {
Sean Silva6347df02016-06-14 02:44:55 +0000634 AliasAnalysis &AA = LookupAliasAnalysis();
Amaury Secheta0c242c2016-01-05 20:17:48 +0000635 MemoryLocation LoadLoc = MemoryLocation::get(LI);
636
637 // We use alias analysis to check if an instruction may store to
638 // the memory we load from in between the load and the store. If
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000639 // such an instruction is found, we try to promote there instead
640 // of at the store position.
641 Instruction *P = SI;
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000642 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
643 if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) {
644 P = &I;
645 break;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000646 }
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000647 }
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000648
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000649 // We found an instruction that may write to the loaded memory.
650 // We can try to promote at this position instead of the store
651 // position if nothing alias the store memory after this and the store
652 // destination is not in the range.
653 if (P && P != SI) {
Bryant Wong7cb74462016-12-27 17:58:12 +0000654 if (!moveUp(AA, SI, P, LI))
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000655 P = nullptr;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000656 }
657
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000658 // If a valid insertion position is found, then we can promote
659 // the load/store pair to a memcpy.
660 if (P) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000661 // If we load from memory that may alias the memory we store to,
662 // memmove must be used to preserve semantic. If not, memcpy can
663 // be used.
664 bool UseMemMove = false;
665 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
666 UseMemMove = true;
667
668 unsigned Align = findCommonAlignment(DL, SI, LI);
669 uint64_t Size = DL.getTypeStoreSize(T);
670
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000671 IRBuilder<> Builder(P);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000672 Instruction *M;
673 if (UseMemMove)
674 M = Builder.CreateMemMove(SI->getPointerOperand(),
675 LI->getPointerOperand(), Size,
676 Align, SI->isVolatile());
677 else
678 M = Builder.CreateMemCpy(SI->getPointerOperand(),
679 LI->getPointerOperand(), Size,
680 Align, SI->isVolatile());
681
682 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
683 << " => " << *M << "\n");
684
685 MD->removeInstruction(SI);
686 SI->eraseFromParent();
687 MD->removeInstruction(LI);
688 LI->eraseFromParent();
689 ++NumMemCpyInstr;
690
691 // Make sure we do not invalidate the iterator.
692 BBI = M->getIterator();
693 return true;
694 }
695 }
696
697 // Detect cases where we're performing call slot forwarding, but
698 // happen to be using a load-store pair to implement it, rather than
699 // a memcpy.
Eli Friedman5da0ff42011-06-02 21:24:42 +0000700 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000701 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000702 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
703 C = dyn_cast<CallInst>(ldep.getInst());
704
705 if (C) {
706 // Check that nothing touches the dest of the "copy" between
707 // the call and the store.
David Majnemerd99068d2016-05-26 19:24:24 +0000708 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
709 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
Sean Silva6347df02016-06-14 02:44:55 +0000710 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000711 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000712 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
713 I != E; --I) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000714 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000715 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000716 break;
717 }
David Majnemerd99068d2016-05-26 19:24:24 +0000718 // The store to dest may never happen if an exception can be thrown
719 // between the load and the store.
720 if (I->mayThrow() && !CpyDestIsLocal) {
721 C = nullptr;
722 break;
723 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000724 }
725 }
726
Owen Anderson18e4fed2010-10-15 22:52:12 +0000727 if (C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000728 bool changed = performCallSlotOptzn(
729 LI, SI->getPointerOperand()->stripPointerCasts(),
730 LI->getPointerOperand()->stripPointerCasts(),
731 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
Amaury Secheta0c242c2016-01-05 20:17:48 +0000732 findCommonAlignment(DL, SI, LI), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000733 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000734 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000735 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000736 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000737 LI->eraseFromParent();
738 ++NumMemCpyInstr;
739 return true;
740 }
741 }
742 }
743 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000744
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000745 // There are two cases that are interesting for this code to handle: memcpy
746 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000747
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000748 // Ensure that the value being stored is something that can be memset'able a
749 // byte at a time like "0" or "-1" or any width, as well as things like
750 // 0xA0A0A0A0 and 0.0.
Amaury Sechet3235c082016-01-06 19:47:24 +0000751 auto *V = SI->getOperand(0);
752 if (Value *ByteVal = isBytewiseValue(V)) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000753 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
754 ByteVal)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000755 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerc6381472011-01-08 20:24:01 +0000756 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000757 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000758
Amaury Sechet3235c082016-01-06 19:47:24 +0000759 // If we have an aggregate, we try to promote it to memset regardless
760 // of opportunity for merging as it can expose optimization opportunities
761 // in subsequent passes.
762 auto *T = V->getType();
763 if (T->isAggregateType()) {
764 uint64_t Size = DL.getTypeStoreSize(T);
765 unsigned Align = SI->getAlignment();
766 if (!Align)
767 Align = DL.getABITypeAlignment(T);
768 IRBuilder<> Builder(SI);
769 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
770 Size, Align, SI->isVolatile());
771
772 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
773
774 MD->removeInstruction(SI);
775 SI->eraseFromParent();
776 NumMemSetInfer++;
777
778 // Make sure we do not invalidate the iterator.
779 BBI = M->getIterator();
780 return true;
781 }
782 }
783
Chris Lattnerc6381472011-01-08 20:24:01 +0000784 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000785}
786
Sean Silva6347df02016-06-14 02:44:55 +0000787bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000788 // See if there is another memset or store neighboring this memset which
789 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000790 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
791 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
792 MSI->getValue())) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000793 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000794 return true;
795 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000796 return false;
797}
798
Sanjay Patela75c41e2015-08-13 22:53:20 +0000799/// Takes a memcpy and a call that it depends on,
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000800/// and checks for the possibility of a call slot optimization by having
801/// the call write its result directly into the destination of the memcpy.
Sean Silva6347df02016-06-14 02:44:55 +0000802bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
803 Value *cpySrc, uint64_t cpyLen,
804 unsigned cpyAlign, CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000805 // The general transformation to keep in mind is
806 //
807 // call @func(..., src, ...)
808 // memcpy(dest, src, ...)
809 //
810 // ->
811 //
812 // memcpy(dest, src, ...)
813 // call @func(..., dest, ...)
814 //
815 // Since moving the memcpy is technically awkward, we additionally check that
816 // src only holds uninitialized values at the moment of the call, meaning that
817 // the memcpy can be discarded rather than moved.
818
Tim Shen7aa0ad62016-06-08 19:42:32 +0000819 // Lifetime marks shouldn't be operated on.
820 if (Function *F = C->getCalledFunction())
821 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
822 return false;
823
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000824 // Deliberately get the source and destination with bitcasts stripped away,
825 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000826 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000827
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000828 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000829 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000830 if (!srcAlloca)
831 return false;
832
Chris Lattnerb5557a72009-09-01 17:09:55 +0000833 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000834 if (!srcArraySize)
835 return false;
836
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 const DataLayout &DL = cpy->getModule()->getDataLayout();
838 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
839 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000840
Owen Anderson18e4fed2010-10-15 22:52:12 +0000841 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000842 return false;
843
844 // Check that accessing the first srcSize bytes of dest will not cause a
845 // trap. Otherwise the transform is invalid since it might cause a trap
846 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000847 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000848 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000849 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000850 if (!destArraySize)
851 return false;
852
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000853 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
854 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000855
856 if (destSize < srcSize)
857 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000858 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
David Majnemerd99068d2016-05-26 19:24:24 +0000859 // The store to dest may never happen if the call can throw.
860 if (C->mayThrow())
861 return false;
862
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000863 if (A->getDereferenceableBytes() < srcSize) {
864 // If the destination is an sret parameter then only accesses that are
865 // outside of the returned struct type can trap.
866 if (!A->hasStructRetAttr())
867 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000868
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000869 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
870 if (!StructTy->isSized()) {
871 // The call may never return and hence the copy-instruction may never
872 // be executed, and therefore it's not safe to say "the destination
873 // has at least <cpyLen> bytes, as implied by the copy-instruction",
874 return false;
875 }
876
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000877 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000878 if (destSize < srcSize)
879 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000880 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000881 } else {
882 return false;
883 }
884
Duncan Sands933db772012-10-05 07:29:46 +0000885 // Check that dest points to memory that is at least as aligned as src.
886 unsigned srcAlign = srcAlloca->getAlignment();
887 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000888 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000889 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
890 // If dest is not aligned enough and we can't increase its alignment then
891 // bail out.
892 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
893 return false;
894
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000895 // Check that src is not accessed except via the call and the memcpy. This
896 // guarantees that it holds only undefined values when passed in (so the final
897 // memcpy can be dropped), that it is not read or written between the call and
898 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000899 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
900 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000901 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000902 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000903
Chandler Carruthcdf47882014-03-09 03:16:01 +0000904 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
905 for (User *UU : U->users())
906 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000907 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000908 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000909 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
910 if (!G->hasAllZeroIndices())
911 return false;
912
913 for (User *UU : U->users())
914 srcUseList.push_back(UU);
915 continue;
916 }
917 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
918 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
919 IT->getIntrinsicID() == Intrinsic::lifetime_end)
920 continue;
921
922 if (U != C && U != cpy)
923 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000924 }
925
Nick Lewycky703e4882014-07-14 18:52:02 +0000926 // Check that src isn't captured by the called function since the
927 // transformation can cause aliasing issues in that case.
928 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
929 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
930 return false;
931
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000932 // Since we're changing the parameter to the callsite, we need to make sure
933 // that what would be the new parameter dominates the callsite.
Sean Silva6347df02016-06-14 02:44:55 +0000934 DominatorTree &DT = LookupDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000935 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000936 if (!DT.dominates(cpyDestInst, C))
937 return false;
938
939 // In addition to knowing that the call does not access src in some
940 // unexpected manner, for example via a global, which we deduce from
941 // the use analysis, we also need to know that it does not sneakily
942 // access dest. We rely on AA to figure this out for us.
Sean Silva6347df02016-06-14 02:44:55 +0000943 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruth194f59c2015-07-22 23:15:57 +0000944 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
Chad Rosiera968caf2012-05-14 20:35:04 +0000945 // If necessary, perform additional analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000946 if (MR != MRI_NoModRef)
Chad Rosiera968caf2012-05-14 20:35:04 +0000947 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000948 if (MR != MRI_NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000949 return false;
950
951 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000952 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000953 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000954 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000955 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
956 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
957 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000958 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000959 if (CS.getArgument(i)->getType() == Dest->getType())
960 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000961 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000962 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
963 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000964 }
965
Owen Andersond071a872008-06-01 21:52:16 +0000966 if (!changedArgument)
967 return false;
968
Duncan Sandsc6ada692012-10-04 10:54:40 +0000969 // If the destination wasn't sufficiently aligned then increase its alignment.
970 if (!isDestSufficientlyAligned) {
971 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
972 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
973 }
974
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000975 // Drop any cached information about the call, because we may have changed
976 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000977 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000978
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000979 // Update AA metadata
980 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
981 // handled here, but combineMetadata doesn't support them yet
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +0000982 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
983 LLVMContext::MD_noalias,
984 LLVMContext::MD_invariant_group};
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000985 combineMetadata(C, cpy, KnownIDs);
986
Chris Lattner58f9f582010-11-21 00:28:59 +0000987 // Remove the memcpy.
988 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000989 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000990
991 return true;
992}
993
Sanjay Patela75c41e2015-08-13 22:53:20 +0000994/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
995/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
Sean Silva6347df02016-06-14 02:44:55 +0000996bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
997 MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000998 // We can only transforms memcpy's where the dest of one is the source of the
999 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +00001000 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001001 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001002
Chris Lattnerfd51c522010-12-09 07:39:50 +00001003 // If dep instruction is reading from our current input, then it is a noop
1004 // transfer and substituting the input won't change this instruction. Just
1005 // ignore the input and let someone else zap MDep. This handles cases like:
1006 // memcpy(a <- a)
1007 // memcpy(b <- a)
1008 if (M->getSource() == MDep->getSource())
1009 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001010
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001011 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001012 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +00001013 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1014 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1015 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1016 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001017
Sean Silva6347df02016-06-14 02:44:55 +00001018 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner59572292010-11-21 08:06:10 +00001019
1020 // Verify that the copied-from memory doesn't change in between the two
1021 // transfers. For example, in:
1022 // memcpy(a <- b)
1023 // *b = 42;
1024 // memcpy(c <- a)
1025 // It would be invalid to transform the second memcpy into memcpy(c <- b).
1026 //
1027 // TODO: If the code between M and MDep is transparent to the destination "c",
1028 // then we could still perform the xform by moving M up to the first memcpy.
1029 //
1030 // NOTE: This is conservative, it will stop on any read from the source loc,
1031 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001032 MemDepResult SourceDep =
1033 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1034 M->getIterator(), M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001035 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1036 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001037
Chris Lattner731caac2010-11-18 08:00:57 +00001038 // If the dest of the second might alias the source of the first, then the
1039 // source and dest might overlap. We still want to eliminate the intermediate
1040 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001041 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +00001042 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1043 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001044 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001045
Chris Lattner58f9f582010-11-21 00:28:59 +00001046 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +00001047
Pete Cooper67cf9a72015-11-19 05:56:52 +00001048 // Make sure to use the lesser of the alignment of the source and the dest
1049 // since we're changing where we're reading from, but don't want to increase
1050 // the alignment past what can be read from or written to.
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001051 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1052 // example we could be moving from movaps -> movq on x86.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001053 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
1054
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001055 IRBuilder<> Builder(M);
1056 if (UseMemMove)
1057 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001058 Align, M->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001059 else
1060 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001061 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +00001062
Chris Lattner59572292010-11-21 08:06:10 +00001063 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +00001064 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +00001065 M->eraseFromParent();
1066 ++NumMemCpyInstr;
1067 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001068}
1069
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001070/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1071/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1072/// weren't copied over by \p MemCpy.
1073///
1074/// In other words, transform:
1075/// \code
1076/// memset(dst, c, dst_size);
1077/// memcpy(dst, src, src_size);
1078/// \endcode
1079/// into:
1080/// \code
1081/// memcpy(dst, src, src_size);
1082/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1083/// \endcode
Sean Silva6347df02016-06-14 02:44:55 +00001084bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1085 MemSetInst *MemSet) {
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001086 // We can only transform memset/memcpy with the same destination.
1087 if (MemSet->getDest() != MemCpy->getDest())
1088 return false;
1089
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001090 // Check that there are no other dependencies on the memset destination.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001091 MemDepResult DstDepInfo =
1092 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1093 MemCpy->getIterator(), MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001094 if (DstDepInfo.getInst() != MemSet)
1095 return false;
1096
Ahmed Bougacha9692e302015-04-21 21:28:33 +00001097 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1098 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001099 Value *DestSize = MemSet->getLength();
1100 Value *SrcSize = MemCpy->getLength();
1101
1102 // By default, create an unaligned memset.
1103 unsigned Align = 1;
1104 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1105 // of the sum.
1106 const unsigned DestAlign =
Pete Cooper67cf9a72015-11-19 05:56:52 +00001107 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001108 if (DestAlign > 1)
1109 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1110 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1111
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001112 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001113
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001114 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001115 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001116 if (DestSize->getType()->getIntegerBitWidth() >
1117 SrcSize->getType()->getIntegerBitWidth())
1118 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1119 else
1120 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001121 }
1122
Benjamin Kramer1697d392016-11-07 17:47:28 +00001123 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1124 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1125 Value *MemsetLen = Builder.CreateSelect(
1126 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001127 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1128 MemsetLen, Align);
1129
1130 MD->removeInstruction(MemSet);
1131 MemSet->eraseFromParent();
1132 return true;
1133}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001134
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001135/// Transform memcpy to memset when its source was just memset.
1136/// In other words, turn:
1137/// \code
1138/// memset(dst1, c, dst1_size);
1139/// memcpy(dst2, dst1, dst2_size);
1140/// \endcode
1141/// into:
1142/// \code
1143/// memset(dst1, c, dst1_size);
1144/// memset(dst2, c, dst2_size);
1145/// \endcode
1146/// When dst2_size <= dst1_size.
1147///
1148/// The \p MemCpy must have a Constant length.
Sean Silva6347df02016-06-14 02:44:55 +00001149bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1150 MemSetInst *MemSet) {
Tim Shena3dbead2016-08-25 19:27:26 +00001151 AliasAnalysis &AA = LookupAliasAnalysis();
1152
Tim Shen3ad8b432016-08-25 21:03:46 +00001153 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1154 // memcpying from the same address. Otherwise it is hard to reason about.
Tim Shena3dbead2016-08-25 19:27:26 +00001155 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001156 return false;
1157
1158 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1159 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1160 // Make sure the memcpy doesn't read any more than what the memset wrote.
1161 // Don't worry about sizes larger than i64.
1162 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1163 return false;
1164
Ahmed Bougacha0541c672015-05-21 00:08:35 +00001165 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001166 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001167 CopySize, MemCpy->getAlignment());
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001168 return true;
1169}
1170
Sanjay Patela75c41e2015-08-13 22:53:20 +00001171/// Perform simplification of memcpy's. If we have memcpy A
Gabor Greif62f0aac2010-07-28 22:50:26 +00001172/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1173/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1174/// circumstances). This allows later passes to remove the first memcpy
1175/// altogether.
Sean Silva6347df02016-06-14 02:44:55 +00001176bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +00001177 // We can only optimize non-volatile memcpy's.
1178 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +00001179
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001180 // If the source and destination of the memcpy are the same, then zap it.
1181 if (M->getSource() == M->getDest()) {
1182 MD->removeInstruction(M);
1183 M->eraseFromParent();
1184 return false;
1185 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001186
1187 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001188 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +00001189 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001190 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001191 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +00001192 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001193 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001194 MD->removeInstruction(M);
1195 M->eraseFromParent();
1196 ++NumCpyToSet;
1197 return true;
1198 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001199
Ahmed Bougachab6169662015-05-11 23:09:46 +00001200 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001201
1202 // Try to turn a partially redundant memset + memcpy into
1203 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +00001204 if (DepInfo.isClobber())
1205 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001206 if (processMemSetMemCpyDependence(M, MDep))
1207 return true;
1208
Nick Lewycky00703e72014-02-04 00:18:54 +00001209 // The optimizations after this point require the memcpy size.
1210 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001211 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +00001212
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001213 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +00001214 // a) memcpy-memcpy xform which exposes redundance for DSE.
1215 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001216 // c) memcpy from freshly alloca'd space or space that has just started its
1217 // lifetime copies undefined data, and we can therefore eliminate the
1218 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001219 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001220 if (DepInfo.isClobber()) {
1221 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1222 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001223 CopySize->getZExtValue(), M->getAlignment(),
Duncan Sandsc6ada692012-10-04 10:54:40 +00001224 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001225 MD->removeInstruction(M);
1226 M->eraseFromParent();
1227 return true;
1228 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001229 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001230 }
Ahmed Charles32e983e2012-02-13 06:30:56 +00001231
Chandler Carruthac80dc72015-06-17 07:18:54 +00001232 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001233 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1234 SrcLoc, true, M->getIterator(), M->getParent());
Ahmed Bougachab6169662015-05-11 23:09:46 +00001235
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001236 if (SrcDepInfo.isClobber()) {
1237 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +00001238 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001239 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001240 Instruction *I = SrcDepInfo.getInst();
1241 bool hasUndefContents = false;
1242
1243 if (isa<AllocaInst>(I)) {
1244 hasUndefContents = true;
1245 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1246 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1247 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1248 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1249 hasUndefContents = true;
1250 }
1251
1252 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +00001253 MD->removeInstruction(M);
1254 M->eraseFromParent();
1255 ++NumMemCpyInstr;
1256 return true;
1257 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001258 }
1259
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001260 if (SrcDepInfo.isClobber())
1261 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1262 if (performMemCpyToMemSetOptzn(M, MDep)) {
1263 MD->removeInstruction(M);
1264 M->eraseFromParent();
1265 ++NumCpyToSet;
1266 return true;
1267 }
1268
Owen Andersonad5367f2008-04-29 21:51:00 +00001269 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001270}
1271
Sanjay Patela75c41e2015-08-13 22:53:20 +00001272/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1273/// not to alias.
Sean Silva6347df02016-06-14 02:44:55 +00001274bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1275 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner1145e332009-09-01 17:56:32 +00001276
David L. Jonesd21529f2017-01-23 23:16:46 +00001277 if (!TLI->has(LibFunc_memmove))
Chris Lattner23f61a02011-05-01 18:27:11 +00001278 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001279
Chris Lattner1145e332009-09-01 17:56:32 +00001280 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001281 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1282 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001283 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001284
Sean Silva6347df02016-06-14 02:44:55 +00001285 DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1286 << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001287
Chris Lattner1145e332009-09-01 17:56:32 +00001288 // If not, then we know we can transform this.
Jay Foadb804a2b2011-07-12 14:06:48 +00001289 Type *ArgTys[3] = { M->getRawDest()->getType(),
1290 M->getRawSource()->getType(),
1291 M->getLength()->getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001292 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1293 Intrinsic::memcpy, ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001294
Chris Lattner1145e332009-09-01 17:56:32 +00001295 // MemDep may have over conservative information about this instruction, just
1296 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001297 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001298
1299 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001300 return true;
1301}
Nadav Rotem465834c2012-07-24 10:51:42 +00001302
Sanjay Patela75c41e2015-08-13 22:53:20 +00001303/// This is called on every byval argument in call sites.
Sean Silva6347df02016-06-14 02:44:55 +00001304bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001305 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001306 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001307 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001308 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001309 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001310 MemDepResult DepInfo = MD->getPointerDependencyFrom(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001311 MemoryLocation(ByValArg, ByValSize), true,
1312 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001313 if (!DepInfo.isClobber())
1314 return false;
1315
1316 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1317 // a memcpy, see if we can byval from the source of the memcpy instead of the
1318 // result.
1319 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001320 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001321 ByValArg->stripPointerCasts() != MDep->getDest())
1322 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001323
Chris Lattner58f9f582010-11-21 00:28:59 +00001324 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001325 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001326 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001327 return false;
1328
Chris Lattner83791ce2011-05-23 00:03:39 +00001329 // Get the alignment of the byval. If the call doesn't specify the alignment,
1330 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +00001331 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +00001332 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001333
Chris Lattner83791ce2011-05-23 00:03:39 +00001334 // If it is greater than the memcpy, then we check to see if we can force the
1335 // source of the memcpy to the alignment we need. If we fail, we bail out.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001336 AssumptionCache &AC = LookupAssumptionCache();
Sean Silva6347df02016-06-14 02:44:55 +00001337 DominatorTree &DT = LookupDomTree();
Pete Cooper67cf9a72015-11-19 05:56:52 +00001338 if (MDep->getAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001339 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001340 CS.getInstruction(), &AC, &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001341 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001342
Chris Lattner58f9f582010-11-21 00:28:59 +00001343 // Verify that the copied-from memory doesn't change in between the memcpy and
1344 // the byval call.
1345 // memcpy(a <- b)
1346 // *b = 42;
1347 // foo(*a)
1348 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001349 //
1350 // NOTE: This is conservative, it will stop on any read from the source loc,
1351 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001352 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1353 MemoryLocation::getForSource(MDep), false,
1354 CS.getInstruction()->getIterator(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001355 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1356 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001357
Chris Lattner58f9f582010-11-21 00:28:59 +00001358 Value *TmpCast = MDep->getSource();
1359 if (MDep->getSource()->getType() != ByValArg->getType())
1360 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1361 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001362
Sean Silva6347df02016-06-14 02:44:55 +00001363 DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
Chris Lattner58f9f582010-11-21 00:28:59 +00001364 << " " << *MDep << "\n"
1365 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001366
Chris Lattner58f9f582010-11-21 00:28:59 +00001367 // Otherwise we're good! Update the byval argument.
1368 CS.setArgument(ArgNo, TmpCast);
1369 ++NumMemCpyInstr;
1370 return true;
1371}
1372
Sean Silva6347df02016-06-14 02:44:55 +00001373/// Executes one iteration of MemCpyOptPass.
1374bool MemCpyOptPass::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001375 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001376
Chris Lattnerb5557a72009-09-01 17:09:55 +00001377 // Walk all instruction in the function.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001378 for (BasicBlock &BB : F) {
1379 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001380 // Avoid invalidating the iterator.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001381 Instruction *I = &*BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001382
Chris Lattner58f9f582010-11-21 00:28:59 +00001383 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001384
Owen Anderson6a7355c2008-04-21 07:45:10 +00001385 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001386 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001387 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1388 RepeatInstruction = processMemSet(M, BI);
1389 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Tim Northover39617352016-05-10 21:49:40 +00001390 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001391 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001392 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001393 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001394 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001395 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001396 MadeChange |= processByValArgument(CS, i);
1397 }
1398
1399 // Reprocess the instruction if desired.
1400 if (RepeatInstruction) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001401 if (BI != BB.begin())
1402 --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001403 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001404 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001405 }
1406 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001407
Chris Lattnerb5557a72009-09-01 17:09:55 +00001408 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001409}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001410
Sean Silva6347df02016-06-14 02:44:55 +00001411PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
Sean Silva6347df02016-06-14 02:44:55 +00001412 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1413 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1414
1415 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1416 return AM.getResult<AAManager>(F);
1417 };
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001418 auto LookupAssumptionCache = [&]() -> AssumptionCache & {
1419 return AM.getResult<AssumptionAnalysis>(F);
1420 };
Sean Silva6347df02016-06-14 02:44:55 +00001421 auto LookupDomTree = [&]() -> DominatorTree & {
1422 return AM.getResult<DominatorTreeAnalysis>(F);
1423 };
1424
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001425 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
1426 LookupAssumptionCache, LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001427 if (!MadeChange)
1428 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001429
Sean Silva6347df02016-06-14 02:44:55 +00001430 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001431 PA.preserveSet<CFGAnalyses>();
Sean Silva6347df02016-06-14 02:44:55 +00001432 PA.preserve<GlobalsAA>();
1433 PA.preserve<MemoryDependenceAnalysis>();
1434 return PA;
1435}
1436
1437bool MemCpyOptPass::runImpl(
1438 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
1439 std::function<AliasAnalysis &()> LookupAliasAnalysis_,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001440 std::function<AssumptionCache &()> LookupAssumptionCache_,
Sean Silva6347df02016-06-14 02:44:55 +00001441 std::function<DominatorTree &()> LookupDomTree_) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001442 bool MadeChange = false;
Sean Silva6347df02016-06-14 02:44:55 +00001443 MD = MD_;
1444 TLI = TLI_;
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001445 LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001446 LookupAssumptionCache = std::move(LookupAssumptionCache_);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001447 LookupDomTree = std::move(LookupDomTree_);
Nadav Rotem465834c2012-07-24 10:51:42 +00001448
Chris Lattner23f61a02011-05-01 18:27:11 +00001449 // If we don't have at least memset and memcpy, there is little point of doing
1450 // anything here. These are required by a freestanding implementation, so if
1451 // even they are disabled, there is no point in trying hard.
David L. Jonesd21529f2017-01-23 23:16:46 +00001452 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
Chris Lattner23f61a02011-05-01 18:27:11 +00001453 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001454
Eugene Zelenko34c23272017-01-18 00:57:48 +00001455 while (true) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001456 if (!iterateOnFunction(F))
1457 break;
1458 MadeChange = true;
1459 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001460
Craig Topperf40110f2014-04-25 05:29:35 +00001461 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001462 return MadeChange;
1463}
Sean Silva6347df02016-06-14 02:44:55 +00001464
1465/// This is the main transformation entry point for a function.
1466bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1467 if (skipFunction(F))
1468 return false;
1469
1470 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1471 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1472
1473 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1474 return getAnalysis<AAResultsWrapperPass>().getAAResults();
1475 };
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001476 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
1477 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1478 };
Sean Silva6347df02016-06-14 02:44:55 +00001479 auto LookupDomTree = [this]() -> DominatorTree & {
1480 return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1481 };
1482
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001483 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,
1484 LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001485}