blob: f161d6710abf3701cf83ba3993381b19dc935004 [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
George Burgess IVecb95f52017-03-08 21:28:19 +0000333class MemCpyOptLegacyPass : public FunctionPass {
334 MemCpyOptPass Impl;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000335
George Burgess IVecb95f52017-03-08 21:28:19 +0000336public:
337 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko34c23272017-01-18 00:57:48 +0000338
George Burgess IVecb95f52017-03-08 21:28:19 +0000339 MemCpyOptLegacyPass() : FunctionPass(ID) {
340 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
341 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000342
George Burgess IVecb95f52017-03-08 21:28:19 +0000343 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000344
George Burgess IVecb95f52017-03-08 21:28:19 +0000345private:
346 // This transformation requires dominator postdominator info
347 void getAnalysisUsage(AnalysisUsage &AU) const override {
348 AU.setPreservesCFG();
349 AU.addRequired<AssumptionCacheTracker>();
350 AU.addRequired<DominatorTreeWrapperPass>();
351 AU.addRequired<MemoryDependenceWrapperPass>();
352 AU.addRequired<AAResultsWrapperPass>();
353 AU.addRequired<TargetLibraryInfoWrapperPass>();
354 AU.addPreserved<GlobalsAAWrapperPass>();
355 AU.addPreserved<MemoryDependenceWrapperPass>();
356 }
357};
Nadav Rotem465834c2012-07-24 10:51:42 +0000358
George Burgess IVecb95f52017-03-08 21:28:19 +0000359char MemCpyOptLegacyPass::ID = 0;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000360
361} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000362
Sanjay Patela75c41e2015-08-13 22:53:20 +0000363/// The public interface to this file...
Sean Silva6347df02016-06-14 02:44:55 +0000364FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000365
Sean Silva6347df02016-06-14 02:44:55 +0000366INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000367 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000368INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000369INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth61440d22016-03-10 00:55:30 +0000370INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000371INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000372INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
373INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Sean Silva6347df02016-06-14 02:44:55 +0000374INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000375 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000376
Sanjay Patela75c41e2015-08-13 22:53:20 +0000377/// When scanning forward over instructions, we look for some other patterns to
378/// fold away. In particular, this looks for stores to neighboring locations of
379/// memory. If it sees enough consecutive ones, it attempts to merge them
380/// together into a memcpy/memset.
Sean Silva6347df02016-06-14 02:44:55 +0000381Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
382 Value *StartPtr,
383 Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000384 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000385
Chris Lattnerc6381472011-01-08 20:24:01 +0000386 // Okay, so we now have a single store that can be splatable. Scan to find
387 // all subsequent stores of the same value to offset from the same pointer.
388 // Join these together into ranges, so we can decide whether contiguous blocks
389 // are stored.
Tim Northover39617352016-05-10 21:49:40 +0000390 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000391
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000392 BasicBlock::iterator BI(StartInst);
Chris Lattnerc6381472011-01-08 20:24:01 +0000393 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000394 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
395 // If the instruction is readnone, ignore it, otherwise bail out. We
396 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000397 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000398 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
399 break;
400 continue;
401 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000402
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000403 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
404 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000405 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000406
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000407 // Check to see if this stored value is of the same byte-splattable value.
408 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
409 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000410
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000411 // Check to see if this store is to a constant offset from the start ptr.
412 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000413 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
414 DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000415 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000416
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000417 Ranges.addStore(Offset, NextStore);
418 } else {
419 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000420
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000421 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
422 !isa<ConstantInt>(MSI->getLength()))
423 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000424
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000425 // Check to see if this store is to a constant offset from the start ptr.
426 int64_t Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000427 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000428 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000429
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000430 Ranges.addMemSet(Offset, MSI);
431 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000432 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000433
Chris Lattnerc6381472011-01-08 20:24:01 +0000434 // If we have no ranges, then we just had a single store with nothing that
435 // could be merged in. This is a very common case of course.
436 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000437 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000438
Chris Lattnerc6381472011-01-08 20:24:01 +0000439 // If we had at least one store that could be merged in, add the starting
440 // store as well. We try to avoid this unless there is at least something
441 // interesting as a small compile-time optimization.
442 Ranges.addInst(0, StartInst);
443
444 // If we create any memsets, we put it right before the first instruction that
445 // isn't part of the memset block. This ensure that the memset is dominated
446 // by any addressing instruction needed by the start of the block.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000447 IRBuilder<> Builder(&*BI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000448
449 // Now that we have full information about ranges, loop over the ranges and
450 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000451 Instruction *AMemSet = nullptr;
Tim Northover39617352016-05-10 21:49:40 +0000452 for (const MemsetRange &Range : Ranges) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000453
Chris Lattnerc6381472011-01-08 20:24:01 +0000454 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000455
Chris Lattnerc6381472011-01-08 20:24:01 +0000456 // If it is profitable to lower this range to memset, do so now.
Tim Northover39617352016-05-10 21:49:40 +0000457 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000458 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000459
Chris Lattnerc6381472011-01-08 20:24:01 +0000460 // Otherwise, we do want to transform this! Create a new memset.
461 // Get the starting pointer of the block.
Tim Northover39617352016-05-10 21:49:40 +0000462 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000463
Tim Northover39617352016-05-10 21:49:40 +0000464 // Determine alignment
465 unsigned Alignment = Range.Alignment;
466 if (Alignment == 0) {
467 Type *EltType =
468 cast<PointerType>(StartPtr->getType())->getElementType();
469 Alignment = DL.getABITypeAlignment(EltType);
470 }
471
472 AMemSet =
473 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000474
Chris Lattnerc6381472011-01-08 20:24:01 +0000475 DEBUG(dbgs() << "Replace stores:\n";
Craig Toppere325e382015-11-20 07:18:48 +0000476 for (Instruction *SI : Range.TheStores)
477 dbgs() << *SI << '\n';
Chris Lattnerc6381472011-01-08 20:24:01 +0000478 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000479
480 if (!Range.TheStores.empty())
481 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
482
Chris Lattnerc6381472011-01-08 20:24:01 +0000483 // Zap all the stores.
Craig Toppere325e382015-11-20 07:18:48 +0000484 for (Instruction *SI : Range.TheStores) {
485 MD->removeInstruction(SI);
486 SI->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000487 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000488 ++NumMemSetInfer;
489 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000490
Chris Lattnerc6381472011-01-08 20:24:01 +0000491 return AMemSet;
492}
493
Tim Northover39617352016-05-10 21:49:40 +0000494static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
495 const LoadInst *LI) {
496 unsigned StoreAlign = SI->getAlignment();
497 if (!StoreAlign)
498 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
499 unsigned LoadAlign = LI->getAlignment();
500 if (!LoadAlign)
501 LoadAlign = DL.getABITypeAlignment(LI->getType());
Amaury Secheta0c242c2016-01-05 20:17:48 +0000502
Tim Northover39617352016-05-10 21:49:40 +0000503 return std::min(StoreAlign, LoadAlign);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000504}
Chris Lattnerc6381472011-01-08 20:24:01 +0000505
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000506// This method try to lift a store instruction before position P.
507// It will lift the store and its argument + that anything that
David Majnemerd99068d2016-05-26 19:24:24 +0000508// may alias with these.
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000509// The method returns true if it was successful.
Bryant Wong7cb74462016-12-27 17:58:12 +0000510static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P,
511 const LoadInst *LI) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000512 // If the store alias this position, early bail out.
513 MemoryLocation StoreLoc = MemoryLocation::get(SI);
514 if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef)
515 return false;
516
517 // Keep track of the arguments of all instruction we plan to lift
518 // so we can make sure to lift them as well if apropriate.
519 DenseSet<Instruction*> Args;
520 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
521 if (Ptr->getParent() == SI->getParent())
522 Args.insert(Ptr);
523
524 // Instruction to lift before P.
525 SmallVector<Instruction*, 8> ToLift;
526
527 // Memory locations of lifted instructions.
Bryant Wong7cb74462016-12-27 17:58:12 +0000528 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000529
530 // Lifted callsites.
531 SmallVector<ImmutableCallSite, 8> CallSites;
532
Bryant Wong7cb74462016-12-27 17:58:12 +0000533 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
534
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000535 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
536 auto *C = &*I;
537
538 bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef;
539
540 bool NeedLift = false;
541 if (Args.erase(C))
542 NeedLift = true;
543 else if (MayAlias) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000544 NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
David Majnemer0a16c222016-08-11 21:15:00 +0000545 return AA.getModRefInfo(C, ML);
546 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000547
548 if (!NeedLift)
Eugene Zelenko34c23272017-01-18 00:57:48 +0000549 NeedLift =
550 llvm::any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) {
551 return AA.getModRefInfo(C, CS);
552 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000553 }
554
555 if (!NeedLift)
556 continue;
557
558 if (MayAlias) {
Bryant Wong7cb74462016-12-27 17:58:12 +0000559 // Since LI is implicitly moved downwards past the lifted instructions,
560 // none of them may modify its source.
561 if (AA.getModRefInfo(C, LoadLoc) & MRI_Mod)
562 return false;
563 else if (auto CS = ImmutableCallSite(C)) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000564 // If we can't lift this before P, it's game over.
565 if (AA.getModRefInfo(P, CS) != MRI_NoModRef)
566 return false;
567
568 CallSites.push_back(CS);
569 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
570 // If we can't lift this before P, it's game over.
571 auto ML = MemoryLocation::get(C);
572 if (AA.getModRefInfo(P, ML) != MRI_NoModRef)
573 return false;
574
575 MemLocs.push_back(ML);
576 } else
577 // We don't know how to lift this instruction.
578 return false;
579 }
580
581 ToLift.push_back(C);
582 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
583 if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
584 if (A->getParent() == SI->getParent())
585 Args.insert(A);
586 }
587
588 // We made it, we need to lift
Eugene Zelenko34c23272017-01-18 00:57:48 +0000589 for (auto *I : llvm::reverse(ToLift)) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000590 DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
591 I->moveBefore(P);
592 }
593
594 return true;
595}
596
Sean Silva6347df02016-06-14 02:44:55 +0000597bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000598 if (!SI->isSimple()) return false;
Andrea Di Biagio99493df2015-10-09 10:53:41 +0000599
600 // Avoid merging nontemporal stores since the resulting
601 // memcpy/memset would not be able to preserve the nontemporal hint.
602 // In theory we could teach how to propagate the !nontemporal metadata to
603 // memset calls. However, that change would force the backend to
604 // conservatively expand !nontemporal memset calls back to sequences of
605 // store instructions (effectively undoing the merging).
606 if (SI->getMetadata(LLVMContext::MD_nontemporal))
607 return false;
608
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000609 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000610
Amaury Secheta0c242c2016-01-05 20:17:48 +0000611 // Load to store forwarding can be interpreted as memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000612 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000613 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000614 LI->getParent() == SI->getParent()) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000615
616 auto *T = LI->getType();
617 if (T->isAggregateType()) {
Sean Silva6347df02016-06-14 02:44:55 +0000618 AliasAnalysis &AA = LookupAliasAnalysis();
Amaury Secheta0c242c2016-01-05 20:17:48 +0000619 MemoryLocation LoadLoc = MemoryLocation::get(LI);
620
621 // We use alias analysis to check if an instruction may store to
622 // the memory we load from in between the load and the store. If
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000623 // such an instruction is found, we try to promote there instead
624 // of at the store position.
625 Instruction *P = SI;
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000626 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
627 if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) {
628 P = &I;
629 break;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000630 }
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000631 }
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000632
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000633 // We found an instruction that may write to the loaded memory.
634 // We can try to promote at this position instead of the store
635 // position if nothing alias the store memory after this and the store
636 // destination is not in the range.
637 if (P && P != SI) {
Bryant Wong7cb74462016-12-27 17:58:12 +0000638 if (!moveUp(AA, SI, P, LI))
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000639 P = nullptr;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000640 }
641
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000642 // If a valid insertion position is found, then we can promote
643 // the load/store pair to a memcpy.
644 if (P) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000645 // If we load from memory that may alias the memory we store to,
646 // memmove must be used to preserve semantic. If not, memcpy can
647 // be used.
648 bool UseMemMove = false;
649 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
650 UseMemMove = true;
651
652 unsigned Align = findCommonAlignment(DL, SI, LI);
653 uint64_t Size = DL.getTypeStoreSize(T);
654
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000655 IRBuilder<> Builder(P);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000656 Instruction *M;
657 if (UseMemMove)
658 M = Builder.CreateMemMove(SI->getPointerOperand(),
659 LI->getPointerOperand(), Size,
660 Align, SI->isVolatile());
661 else
662 M = Builder.CreateMemCpy(SI->getPointerOperand(),
663 LI->getPointerOperand(), Size,
664 Align, SI->isVolatile());
665
666 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
667 << " => " << *M << "\n");
668
669 MD->removeInstruction(SI);
670 SI->eraseFromParent();
671 MD->removeInstruction(LI);
672 LI->eraseFromParent();
673 ++NumMemCpyInstr;
674
675 // Make sure we do not invalidate the iterator.
676 BBI = M->getIterator();
677 return true;
678 }
679 }
680
681 // Detect cases where we're performing call slot forwarding, but
682 // happen to be using a load-store pair to implement it, rather than
683 // a memcpy.
Eli Friedman5da0ff42011-06-02 21:24:42 +0000684 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000685 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000686 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
687 C = dyn_cast<CallInst>(ldep.getInst());
688
689 if (C) {
690 // Check that nothing touches the dest of the "copy" between
691 // the call and the store.
David Majnemerd99068d2016-05-26 19:24:24 +0000692 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
693 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
Sean Silva6347df02016-06-14 02:44:55 +0000694 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000695 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000696 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
697 I != E; --I) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000698 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000699 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000700 break;
701 }
David Majnemerd99068d2016-05-26 19:24:24 +0000702 // The store to dest may never happen if an exception can be thrown
703 // between the load and the store.
704 if (I->mayThrow() && !CpyDestIsLocal) {
705 C = nullptr;
706 break;
707 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000708 }
709 }
710
Owen Anderson18e4fed2010-10-15 22:52:12 +0000711 if (C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000712 bool changed = performCallSlotOptzn(
713 LI, SI->getPointerOperand()->stripPointerCasts(),
714 LI->getPointerOperand()->stripPointerCasts(),
715 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
Amaury Secheta0c242c2016-01-05 20:17:48 +0000716 findCommonAlignment(DL, SI, LI), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000717 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000718 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000719 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000720 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000721 LI->eraseFromParent();
722 ++NumMemCpyInstr;
723 return true;
724 }
725 }
726 }
727 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000728
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000729 // There are two cases that are interesting for this code to handle: memcpy
730 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000731
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000732 // Ensure that the value being stored is something that can be memset'able a
733 // byte at a time like "0" or "-1" or any width, as well as things like
734 // 0xA0A0A0A0 and 0.0.
Amaury Sechet3235c082016-01-06 19:47:24 +0000735 auto *V = SI->getOperand(0);
736 if (Value *ByteVal = isBytewiseValue(V)) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000737 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
738 ByteVal)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000739 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerc6381472011-01-08 20:24:01 +0000740 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000741 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000742
Amaury Sechet3235c082016-01-06 19:47:24 +0000743 // If we have an aggregate, we try to promote it to memset regardless
744 // of opportunity for merging as it can expose optimization opportunities
745 // in subsequent passes.
746 auto *T = V->getType();
747 if (T->isAggregateType()) {
748 uint64_t Size = DL.getTypeStoreSize(T);
749 unsigned Align = SI->getAlignment();
750 if (!Align)
751 Align = DL.getABITypeAlignment(T);
752 IRBuilder<> Builder(SI);
753 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
754 Size, Align, SI->isVolatile());
755
756 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
757
758 MD->removeInstruction(SI);
759 SI->eraseFromParent();
760 NumMemSetInfer++;
761
762 // Make sure we do not invalidate the iterator.
763 BBI = M->getIterator();
764 return true;
765 }
766 }
767
Chris Lattnerc6381472011-01-08 20:24:01 +0000768 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000769}
770
Sean Silva6347df02016-06-14 02:44:55 +0000771bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000772 // See if there is another memset or store neighboring this memset which
773 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000774 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
775 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
776 MSI->getValue())) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000777 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000778 return true;
779 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000780 return false;
781}
782
Sanjay Patela75c41e2015-08-13 22:53:20 +0000783/// Takes a memcpy and a call that it depends on,
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000784/// and checks for the possibility of a call slot optimization by having
785/// the call write its result directly into the destination of the memcpy.
Sean Silva6347df02016-06-14 02:44:55 +0000786bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
787 Value *cpySrc, uint64_t cpyLen,
788 unsigned cpyAlign, CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000789 // The general transformation to keep in mind is
790 //
791 // call @func(..., src, ...)
792 // memcpy(dest, src, ...)
793 //
794 // ->
795 //
796 // memcpy(dest, src, ...)
797 // call @func(..., dest, ...)
798 //
799 // Since moving the memcpy is technically awkward, we additionally check that
800 // src only holds uninitialized values at the moment of the call, meaning that
801 // the memcpy can be discarded rather than moved.
802
Tim Shen7aa0ad62016-06-08 19:42:32 +0000803 // Lifetime marks shouldn't be operated on.
804 if (Function *F = C->getCalledFunction())
805 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
806 return false;
807
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000808 // Deliberately get the source and destination with bitcasts stripped away,
809 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000810 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000811
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000812 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000813 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000814 if (!srcAlloca)
815 return false;
816
Chris Lattnerb5557a72009-09-01 17:09:55 +0000817 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000818 if (!srcArraySize)
819 return false;
820
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000821 const DataLayout &DL = cpy->getModule()->getDataLayout();
822 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
823 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000824
Owen Anderson18e4fed2010-10-15 22:52:12 +0000825 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000826 return false;
827
828 // Check that accessing the first srcSize bytes of dest will not cause a
829 // trap. Otherwise the transform is invalid since it might cause a trap
830 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000831 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000832 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000833 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000834 if (!destArraySize)
835 return false;
836
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
838 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000839
840 if (destSize < srcSize)
841 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000842 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
David Majnemerd99068d2016-05-26 19:24:24 +0000843 // The store to dest may never happen if the call can throw.
844 if (C->mayThrow())
845 return false;
846
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000847 if (A->getDereferenceableBytes() < srcSize) {
848 // If the destination is an sret parameter then only accesses that are
849 // outside of the returned struct type can trap.
850 if (!A->hasStructRetAttr())
851 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000852
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000853 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
854 if (!StructTy->isSized()) {
855 // The call may never return and hence the copy-instruction may never
856 // be executed, and therefore it's not safe to say "the destination
857 // has at least <cpyLen> bytes, as implied by the copy-instruction",
858 return false;
859 }
860
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000861 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000862 if (destSize < srcSize)
863 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000864 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000865 } else {
866 return false;
867 }
868
Duncan Sands933db772012-10-05 07:29:46 +0000869 // Check that dest points to memory that is at least as aligned as src.
870 unsigned srcAlign = srcAlloca->getAlignment();
871 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000872 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000873 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
874 // If dest is not aligned enough and we can't increase its alignment then
875 // bail out.
876 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
877 return false;
878
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000879 // Check that src is not accessed except via the call and the memcpy. This
880 // guarantees that it holds only undefined values when passed in (so the final
881 // memcpy can be dropped), that it is not read or written between the call and
882 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000883 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
884 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000885 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000886 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000887
Chandler Carruthcdf47882014-03-09 03:16:01 +0000888 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
889 for (User *UU : U->users())
890 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000891 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000892 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000893 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
894 if (!G->hasAllZeroIndices())
895 return false;
896
897 for (User *UU : U->users())
898 srcUseList.push_back(UU);
899 continue;
900 }
901 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
902 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
903 IT->getIntrinsicID() == Intrinsic::lifetime_end)
904 continue;
905
906 if (U != C && U != cpy)
907 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000908 }
909
Nick Lewycky703e4882014-07-14 18:52:02 +0000910 // Check that src isn't captured by the called function since the
911 // transformation can cause aliasing issues in that case.
912 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
913 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
914 return false;
915
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000916 // Since we're changing the parameter to the callsite, we need to make sure
917 // that what would be the new parameter dominates the callsite.
Sean Silva6347df02016-06-14 02:44:55 +0000918 DominatorTree &DT = LookupDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000919 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000920 if (!DT.dominates(cpyDestInst, C))
921 return false;
922
923 // In addition to knowing that the call does not access src in some
924 // unexpected manner, for example via a global, which we deduce from
925 // the use analysis, we also need to know that it does not sneakily
926 // access dest. We rely on AA to figure this out for us.
Sean Silva6347df02016-06-14 02:44:55 +0000927 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruth194f59c2015-07-22 23:15:57 +0000928 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
Chad Rosiera968caf2012-05-14 20:35:04 +0000929 // If necessary, perform additional analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000930 if (MR != MRI_NoModRef)
Chad Rosiera968caf2012-05-14 20:35:04 +0000931 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000932 if (MR != MRI_NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000933 return false;
934
Fiona Glasera9bd5722017-03-14 22:37:38 +0000935 // We can't create address space casts here because we don't know if they're
936 // safe for the target.
937 if (cpySrc->getType()->getPointerAddressSpace() !=
938 cpyDest->getType()->getPointerAddressSpace())
939 return false;
940 for (unsigned i = 0; i < CS.arg_size(); ++i)
941 if (CS.getArgument(i)->stripPointerCasts() == cpySrc &&
942 cpySrc->getType()->getPointerAddressSpace() !=
943 CS.getArgument(i)->getType()->getPointerAddressSpace())
944 return false;
945
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000946 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000947 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000948 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000949 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000950 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
951 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
952 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000953 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000954 if (CS.getArgument(i)->getType() == Dest->getType())
955 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000956 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000957 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
958 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000959 }
960
Owen Andersond071a872008-06-01 21:52:16 +0000961 if (!changedArgument)
962 return false;
963
Duncan Sandsc6ada692012-10-04 10:54:40 +0000964 // If the destination wasn't sufficiently aligned then increase its alignment.
965 if (!isDestSufficientlyAligned) {
966 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
967 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
968 }
969
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000970 // Drop any cached information about the call, because we may have changed
971 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000972 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000973
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000974 // Update AA metadata
975 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
976 // handled here, but combineMetadata doesn't support them yet
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +0000977 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
978 LLVMContext::MD_noalias,
979 LLVMContext::MD_invariant_group};
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000980 combineMetadata(C, cpy, KnownIDs);
981
Chris Lattner58f9f582010-11-21 00:28:59 +0000982 // Remove the memcpy.
983 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000984 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000985
986 return true;
987}
988
Sanjay Patela75c41e2015-08-13 22:53:20 +0000989/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
990/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
Sean Silva6347df02016-06-14 02:44:55 +0000991bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
992 MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000993 // We can only transforms memcpy's where the dest of one is the source of the
994 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000995 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000996 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000997
Chris Lattnerfd51c522010-12-09 07:39:50 +0000998 // If dep instruction is reading from our current input, then it is a noop
999 // transfer and substituting the input won't change this instruction. Just
1000 // ignore the input and let someone else zap MDep. This handles cases like:
1001 // memcpy(a <- a)
1002 // memcpy(b <- a)
1003 if (M->getSource() == MDep->getSource())
1004 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001005
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001006 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001007 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +00001008 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1009 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1010 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1011 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001012
Sean Silva6347df02016-06-14 02:44:55 +00001013 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner59572292010-11-21 08:06:10 +00001014
1015 // Verify that the copied-from memory doesn't change in between the two
1016 // transfers. For example, in:
1017 // memcpy(a <- b)
1018 // *b = 42;
1019 // memcpy(c <- a)
1020 // It would be invalid to transform the second memcpy into memcpy(c <- b).
1021 //
1022 // TODO: If the code between M and MDep is transparent to the destination "c",
1023 // then we could still perform the xform by moving M up to the first memcpy.
1024 //
1025 // NOTE: This is conservative, it will stop on any read from the source loc,
1026 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001027 MemDepResult SourceDep =
1028 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1029 M->getIterator(), M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001030 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1031 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001032
Chris Lattner731caac2010-11-18 08:00:57 +00001033 // If the dest of the second might alias the source of the first, then the
1034 // source and dest might overlap. We still want to eliminate the intermediate
1035 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001036 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +00001037 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1038 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001039 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001040
Chris Lattner58f9f582010-11-21 00:28:59 +00001041 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +00001042
Pete Cooper67cf9a72015-11-19 05:56:52 +00001043 // Make sure to use the lesser of the alignment of the source and the dest
1044 // since we're changing where we're reading from, but don't want to increase
1045 // the alignment past what can be read from or written to.
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001046 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1047 // example we could be moving from movaps -> movq on x86.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001048 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
1049
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001050 IRBuilder<> Builder(M);
1051 if (UseMemMove)
1052 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001053 Align, M->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001054 else
1055 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001056 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +00001057
Chris Lattner59572292010-11-21 08:06:10 +00001058 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +00001059 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +00001060 M->eraseFromParent();
1061 ++NumMemCpyInstr;
1062 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001063}
1064
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001065/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1066/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1067/// weren't copied over by \p MemCpy.
1068///
1069/// In other words, transform:
1070/// \code
1071/// memset(dst, c, dst_size);
1072/// memcpy(dst, src, src_size);
1073/// \endcode
1074/// into:
1075/// \code
1076/// memcpy(dst, src, src_size);
1077/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1078/// \endcode
Sean Silva6347df02016-06-14 02:44:55 +00001079bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1080 MemSetInst *MemSet) {
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001081 // We can only transform memset/memcpy with the same destination.
1082 if (MemSet->getDest() != MemCpy->getDest())
1083 return false;
1084
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001085 // Check that there are no other dependencies on the memset destination.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001086 MemDepResult DstDepInfo =
1087 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1088 MemCpy->getIterator(), MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001089 if (DstDepInfo.getInst() != MemSet)
1090 return false;
1091
Ahmed Bougacha9692e302015-04-21 21:28:33 +00001092 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1093 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001094 Value *DestSize = MemSet->getLength();
1095 Value *SrcSize = MemCpy->getLength();
1096
1097 // By default, create an unaligned memset.
1098 unsigned Align = 1;
1099 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1100 // of the sum.
1101 const unsigned DestAlign =
Pete Cooper67cf9a72015-11-19 05:56:52 +00001102 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001103 if (DestAlign > 1)
1104 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1105 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1106
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001107 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001108
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001109 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001110 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001111 if (DestSize->getType()->getIntegerBitWidth() >
1112 SrcSize->getType()->getIntegerBitWidth())
1113 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1114 else
1115 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001116 }
1117
Benjamin Kramer1697d392016-11-07 17:47:28 +00001118 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1119 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1120 Value *MemsetLen = Builder.CreateSelect(
1121 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001122 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1123 MemsetLen, Align);
1124
1125 MD->removeInstruction(MemSet);
1126 MemSet->eraseFromParent();
1127 return true;
1128}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001129
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001130/// Transform memcpy to memset when its source was just memset.
1131/// In other words, turn:
1132/// \code
1133/// memset(dst1, c, dst1_size);
1134/// memcpy(dst2, dst1, dst2_size);
1135/// \endcode
1136/// into:
1137/// \code
1138/// memset(dst1, c, dst1_size);
1139/// memset(dst2, c, dst2_size);
1140/// \endcode
1141/// When dst2_size <= dst1_size.
1142///
1143/// The \p MemCpy must have a Constant length.
Sean Silva6347df02016-06-14 02:44:55 +00001144bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1145 MemSetInst *MemSet) {
Tim Shena3dbead2016-08-25 19:27:26 +00001146 AliasAnalysis &AA = LookupAliasAnalysis();
1147
Tim Shen3ad8b432016-08-25 21:03:46 +00001148 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1149 // memcpying from the same address. Otherwise it is hard to reason about.
Tim Shena3dbead2016-08-25 19:27:26 +00001150 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001151 return false;
1152
1153 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1154 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1155 // Make sure the memcpy doesn't read any more than what the memset wrote.
1156 // Don't worry about sizes larger than i64.
1157 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1158 return false;
1159
Ahmed Bougacha0541c672015-05-21 00:08:35 +00001160 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001161 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001162 CopySize, MemCpy->getAlignment());
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001163 return true;
1164}
1165
Sanjay Patela75c41e2015-08-13 22:53:20 +00001166/// Perform simplification of memcpy's. If we have memcpy A
Gabor Greif62f0aac2010-07-28 22:50:26 +00001167/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1168/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1169/// circumstances). This allows later passes to remove the first memcpy
1170/// altogether.
Sean Silva6347df02016-06-14 02:44:55 +00001171bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +00001172 // We can only optimize non-volatile memcpy's.
1173 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +00001174
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001175 // If the source and destination of the memcpy are the same, then zap it.
1176 if (M->getSource() == M->getDest()) {
1177 MD->removeInstruction(M);
1178 M->eraseFromParent();
1179 return false;
1180 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001181
1182 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001183 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +00001184 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001185 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001186 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +00001187 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001188 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001189 MD->removeInstruction(M);
1190 M->eraseFromParent();
1191 ++NumCpyToSet;
1192 return true;
1193 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001194
Ahmed Bougachab6169662015-05-11 23:09:46 +00001195 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001196
1197 // Try to turn a partially redundant memset + memcpy into
1198 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +00001199 if (DepInfo.isClobber())
1200 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001201 if (processMemSetMemCpyDependence(M, MDep))
1202 return true;
1203
Nick Lewycky00703e72014-02-04 00:18:54 +00001204 // The optimizations after this point require the memcpy size.
1205 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001206 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +00001207
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001208 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +00001209 // a) memcpy-memcpy xform which exposes redundance for DSE.
1210 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001211 // c) memcpy from freshly alloca'd space or space that has just started its
1212 // lifetime copies undefined data, and we can therefore eliminate the
1213 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001214 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001215 if (DepInfo.isClobber()) {
1216 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1217 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001218 CopySize->getZExtValue(), M->getAlignment(),
Duncan Sandsc6ada692012-10-04 10:54:40 +00001219 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001220 MD->removeInstruction(M);
1221 M->eraseFromParent();
1222 return true;
1223 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001224 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001225 }
Ahmed Charles32e983e2012-02-13 06:30:56 +00001226
Chandler Carruthac80dc72015-06-17 07:18:54 +00001227 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001228 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1229 SrcLoc, true, M->getIterator(), M->getParent());
Ahmed Bougachab6169662015-05-11 23:09:46 +00001230
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001231 if (SrcDepInfo.isClobber()) {
1232 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +00001233 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001234 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001235 Instruction *I = SrcDepInfo.getInst();
1236 bool hasUndefContents = false;
1237
1238 if (isa<AllocaInst>(I)) {
1239 hasUndefContents = true;
1240 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1241 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1242 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1243 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1244 hasUndefContents = true;
1245 }
1246
1247 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +00001248 MD->removeInstruction(M);
1249 M->eraseFromParent();
1250 ++NumMemCpyInstr;
1251 return true;
1252 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001253 }
1254
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001255 if (SrcDepInfo.isClobber())
1256 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1257 if (performMemCpyToMemSetOptzn(M, MDep)) {
1258 MD->removeInstruction(M);
1259 M->eraseFromParent();
1260 ++NumCpyToSet;
1261 return true;
1262 }
1263
Owen Andersonad5367f2008-04-29 21:51:00 +00001264 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001265}
1266
Sanjay Patela75c41e2015-08-13 22:53:20 +00001267/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1268/// not to alias.
Sean Silva6347df02016-06-14 02:44:55 +00001269bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1270 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner1145e332009-09-01 17:56:32 +00001271
David L. Jonesd21529f2017-01-23 23:16:46 +00001272 if (!TLI->has(LibFunc_memmove))
Chris Lattner23f61a02011-05-01 18:27:11 +00001273 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001274
Chris Lattner1145e332009-09-01 17:56:32 +00001275 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001276 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1277 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001278 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001279
Sean Silva6347df02016-06-14 02:44:55 +00001280 DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1281 << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001282
Chris Lattner1145e332009-09-01 17:56:32 +00001283 // If not, then we know we can transform this.
Jay Foadb804a2b2011-07-12 14:06:48 +00001284 Type *ArgTys[3] = { M->getRawDest()->getType(),
1285 M->getRawSource()->getType(),
1286 M->getLength()->getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001287 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1288 Intrinsic::memcpy, ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001289
Chris Lattner1145e332009-09-01 17:56:32 +00001290 // MemDep may have over conservative information about this instruction, just
1291 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001292 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001293
1294 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001295 return true;
1296}
Nadav Rotem465834c2012-07-24 10:51:42 +00001297
Sanjay Patela75c41e2015-08-13 22:53:20 +00001298/// This is called on every byval argument in call sites.
Sean Silva6347df02016-06-14 02:44:55 +00001299bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001300 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001301 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001302 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001303 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001304 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001305 MemDepResult DepInfo = MD->getPointerDependencyFrom(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001306 MemoryLocation(ByValArg, ByValSize), true,
1307 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001308 if (!DepInfo.isClobber())
1309 return false;
1310
1311 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1312 // a memcpy, see if we can byval from the source of the memcpy instead of the
1313 // result.
1314 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001315 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001316 ByValArg->stripPointerCasts() != MDep->getDest())
1317 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001318
Chris Lattner58f9f582010-11-21 00:28:59 +00001319 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001320 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001321 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001322 return false;
1323
Chris Lattner83791ce2011-05-23 00:03:39 +00001324 // Get the alignment of the byval. If the call doesn't specify the alignment,
1325 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +00001326 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +00001327 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001328
Chris Lattner83791ce2011-05-23 00:03:39 +00001329 // If it is greater than the memcpy, then we check to see if we can force the
1330 // source of the memcpy to the alignment we need. If we fail, we bail out.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001331 AssumptionCache &AC = LookupAssumptionCache();
Sean Silva6347df02016-06-14 02:44:55 +00001332 DominatorTree &DT = LookupDomTree();
Pete Cooper67cf9a72015-11-19 05:56:52 +00001333 if (MDep->getAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001334 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001335 CS.getInstruction(), &AC, &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001336 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001337
Chris Lattner58f9f582010-11-21 00:28:59 +00001338 // Verify that the copied-from memory doesn't change in between the memcpy and
1339 // the byval call.
1340 // memcpy(a <- b)
1341 // *b = 42;
1342 // foo(*a)
1343 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001344 //
1345 // NOTE: This is conservative, it will stop on any read from the source loc,
1346 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001347 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1348 MemoryLocation::getForSource(MDep), false,
1349 CS.getInstruction()->getIterator(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001350 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1351 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001352
Chris Lattner58f9f582010-11-21 00:28:59 +00001353 Value *TmpCast = MDep->getSource();
1354 if (MDep->getSource()->getType() != ByValArg->getType())
1355 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1356 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001357
Sean Silva6347df02016-06-14 02:44:55 +00001358 DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
Chris Lattner58f9f582010-11-21 00:28:59 +00001359 << " " << *MDep << "\n"
1360 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001361
Chris Lattner58f9f582010-11-21 00:28:59 +00001362 // Otherwise we're good! Update the byval argument.
1363 CS.setArgument(ArgNo, TmpCast);
1364 ++NumMemCpyInstr;
1365 return true;
1366}
1367
Sean Silva6347df02016-06-14 02:44:55 +00001368/// Executes one iteration of MemCpyOptPass.
1369bool MemCpyOptPass::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001370 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001371
Chris Lattnerb5557a72009-09-01 17:09:55 +00001372 // Walk all instruction in the function.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001373 for (BasicBlock &BB : F) {
1374 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001375 // Avoid invalidating the iterator.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001376 Instruction *I = &*BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001377
Chris Lattner58f9f582010-11-21 00:28:59 +00001378 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001379
Owen Anderson6a7355c2008-04-21 07:45:10 +00001380 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001381 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001382 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1383 RepeatInstruction = processMemSet(M, BI);
1384 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Tim Northover39617352016-05-10 21:49:40 +00001385 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001386 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001387 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001388 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001389 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001390 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001391 MadeChange |= processByValArgument(CS, i);
1392 }
1393
1394 // Reprocess the instruction if desired.
1395 if (RepeatInstruction) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001396 if (BI != BB.begin())
1397 --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001398 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001399 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001400 }
1401 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001402
Chris Lattnerb5557a72009-09-01 17:09:55 +00001403 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001404}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001405
Sean Silva6347df02016-06-14 02:44:55 +00001406PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
Sean Silva6347df02016-06-14 02:44:55 +00001407 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1408 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1409
1410 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1411 return AM.getResult<AAManager>(F);
1412 };
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001413 auto LookupAssumptionCache = [&]() -> AssumptionCache & {
1414 return AM.getResult<AssumptionAnalysis>(F);
1415 };
Sean Silva6347df02016-06-14 02:44:55 +00001416 auto LookupDomTree = [&]() -> DominatorTree & {
1417 return AM.getResult<DominatorTreeAnalysis>(F);
1418 };
1419
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001420 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
1421 LookupAssumptionCache, LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001422 if (!MadeChange)
1423 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001424
Sean Silva6347df02016-06-14 02:44:55 +00001425 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001426 PA.preserveSet<CFGAnalyses>();
Sean Silva6347df02016-06-14 02:44:55 +00001427 PA.preserve<GlobalsAA>();
1428 PA.preserve<MemoryDependenceAnalysis>();
1429 return PA;
1430}
1431
1432bool MemCpyOptPass::runImpl(
1433 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
1434 std::function<AliasAnalysis &()> LookupAliasAnalysis_,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001435 std::function<AssumptionCache &()> LookupAssumptionCache_,
Sean Silva6347df02016-06-14 02:44:55 +00001436 std::function<DominatorTree &()> LookupDomTree_) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001437 bool MadeChange = false;
Sean Silva6347df02016-06-14 02:44:55 +00001438 MD = MD_;
1439 TLI = TLI_;
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001440 LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001441 LookupAssumptionCache = std::move(LookupAssumptionCache_);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001442 LookupDomTree = std::move(LookupDomTree_);
Nadav Rotem465834c2012-07-24 10:51:42 +00001443
Chris Lattner23f61a02011-05-01 18:27:11 +00001444 // If we don't have at least memset and memcpy, there is little point of doing
1445 // anything here. These are required by a freestanding implementation, so if
1446 // even they are disabled, there is no point in trying hard.
David L. Jonesd21529f2017-01-23 23:16:46 +00001447 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
Chris Lattner23f61a02011-05-01 18:27:11 +00001448 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001449
Eugene Zelenko34c23272017-01-18 00:57:48 +00001450 while (true) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001451 if (!iterateOnFunction(F))
1452 break;
1453 MadeChange = true;
1454 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001455
Craig Topperf40110f2014-04-25 05:29:35 +00001456 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001457 return MadeChange;
1458}
Sean Silva6347df02016-06-14 02:44:55 +00001459
1460/// This is the main transformation entry point for a function.
1461bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1462 if (skipFunction(F))
1463 return false;
1464
1465 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1466 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1467
1468 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1469 return getAnalysis<AAResultsWrapperPass>().getAAResults();
1470 };
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001471 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
1472 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1473 };
Sean Silva6347df02016-06-14 02:44:55 +00001474 auto LookupDomTree = [this]() -> DominatorTree & {
1475 return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1476 };
1477
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001478 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,
1479 LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001480}