blob: c750ece41b4def95252e161247e4e5aa9ba878bc [file] [log] [blame]
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs various transformations related to eliminating memcpy
11// calls, or transforming sets of stores into memset's.
12//
13//===----------------------------------------------------------------------===//
14
Owen Andersonef9a6fd2008-04-09 08:23:16 +000015#include "llvm/Transforms/Scalar.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000016#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/Statistic.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000023#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/GlobalVariable.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000028#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner23f61a02011-05-01 18:27:11 +000030#include "llvm/Target/TargetLibraryInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000031#include "llvm/Transforms/Utils/Local.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000032#include <list>
33using namespace llvm;
34
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "memcpyopt"
36
Owen Andersonef9a6fd2008-04-09 08:23:16 +000037STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
38STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000039STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000040STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000041
Benjamin Kramer15a257d2012-09-13 16:29:49 +000042static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000043 bool &VariableIdxFound, const DataLayout &TD){
Owen Andersonef9a6fd2008-04-09 08:23:16 +000044 // Skip over the first indices.
45 gep_type_iterator GTI = gep_type_begin(GEP);
46 for (unsigned i = 1; i != Idx; ++i, ++GTI)
47 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000048
Owen Andersonef9a6fd2008-04-09 08:23:16 +000049 // Compute the offset implied by the rest of the indices.
50 int64_t Offset = 0;
51 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
52 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +000053 if (!OpC)
Owen Andersonef9a6fd2008-04-09 08:23:16 +000054 return VariableIdxFound = true;
55 if (OpC->isZero()) continue; // No offset.
56
57 // Handle struct indices, which add their field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +000058 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000059 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
60 continue;
61 }
Nadav Rotem465834c2012-07-24 10:51:42 +000062
Owen Andersonef9a6fd2008-04-09 08:23:16 +000063 // Otherwise, we have a sequential type like an array or vector. Multiply
64 // the index by the ElementSize.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000065 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000066 Offset += Size*OpC->getSExtValue();
67 }
68
69 return Offset;
70}
71
72/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
73/// constant offset, and return that constant offset. For example, Ptr1 might
74/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
75static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000076 const DataLayout &TD) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +000077 Ptr1 = Ptr1->stripPointerCasts();
78 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer3ef5e462014-03-10 21:05:13 +000079
80 // Handle the trivial case first.
81 if (Ptr1 == Ptr2) {
82 Offset = 0;
83 return true;
84 }
85
Benjamin Kramer15a257d2012-09-13 16:29:49 +000086 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
87 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +000088
Chris Lattner5120ebf2011-01-08 21:07:56 +000089 bool VariableIdxFound = false;
90
91 // If one pointer is a GEP and the other isn't, then see if the GEP is a
92 // constant offset from the base, as in "P" and "gep P, 1".
Craig Topperf40110f2014-04-25 05:29:35 +000093 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
Chris Lattner5120ebf2011-01-08 21:07:56 +000094 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
95 return !VariableIdxFound;
96 }
97
Craig Topperf40110f2014-04-25 05:29:35 +000098 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
Chris Lattner5120ebf2011-01-08 21:07:56 +000099 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
100 return !VariableIdxFound;
101 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000102
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000103 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
104 // base. After that base, they may have some number of common (and
105 // potentially variable) indices. After that they handle some constant
106 // offset, which determines their offset from each other. At this point, we
107 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000108 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
109 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000110
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000111 // Skip any common indices and track the GEP types.
112 unsigned Idx = 1;
113 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
114 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
115 break;
116
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000117 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
118 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
119 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000120
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000121 Offset = Offset2-Offset1;
122 return true;
123}
124
125
126/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
127/// This allows us to analyze stores like:
128/// store 0 -> P+1
129/// store 0 -> P+0
130/// store 0 -> P+3
131/// store 0 -> P+2
132/// which sometimes happens with stores to arrays of structs etc. When we see
133/// the first store, we make a range [1, 2). The second store extends the range
134/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
135/// two ranges into [0, 3) which is memset'able.
136namespace {
137struct MemsetRange {
138 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000139 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000140 int64_t Start, End;
141
142 /// StartPtr - The getelementptr instruction that points to the start of the
143 /// range.
144 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000145
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000146 /// Alignment - The known alignment of the first store.
147 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000149 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000150 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000151
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000152 bool isProfitableToUseMemset(const DataLayout &TD) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000153
154};
155} // end anon namespace
156
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000157bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
Chad Rosier32775572011-12-05 22:53:09 +0000158 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000159 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000160
161 // If there is nothing to merge, don't do anything.
162 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000163
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000164 // If any of the stores are a memset, then it is always good to extend the
165 // memset.
166 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
167 if (!isa<StoreInst>(TheStores[i]))
168 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000169
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000170 // Assume that the code generator is capable of merging pairs of stores
171 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000172 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000173
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000174 // If we have fewer than 8 stores, it can still be worthwhile to do this.
175 // For example, merging 4 i8 stores into an i32 store is useful almost always.
176 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
177 // memset will be split into 2 32-bit stores anyway) and doing so can
178 // pessimize the llvm optimizer.
179 //
180 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000181 // the maximum GPR width is the same size as the largest legal integer
182 // size. If so, check to see whether we will end up actually reducing the
183 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000184 unsigned Bytes = unsigned(End-Start);
Matt Arsenault899f7d22013-09-16 22:43:16 +0000185 unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
186 if (MaxIntSize == 0)
187 MaxIntSize = 1;
188 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000189
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000190 // Assume the remaining bytes if any are done a byte at a time.
Matt Arsenault899f7d22013-09-16 22:43:16 +0000191 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000192
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000193 // If we will reduce the # stores (according to this heuristic), do the
194 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
195 // etc.
196 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000197}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000198
199
200namespace {
201class MemsetRanges {
202 /// Ranges - A sorted list of the memset ranges. We use std::list here
203 /// because each element is relatively large and expensive to copy.
204 std::list<MemsetRange> Ranges;
205 typedef std::list<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000206 const DataLayout &DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000207public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000208 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000209
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000210 typedef std::list<MemsetRange>::const_iterator const_iterator;
211 const_iterator begin() const { return Ranges.begin(); }
212 const_iterator end() const { return Ranges.end(); }
213 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000214
Chris Lattnerc6381472011-01-08 20:24:01 +0000215 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000216 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
217 addStore(OffsetFromFirst, SI);
218 else
219 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000220 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000221
222 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000223 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000224
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000225 addRange(OffsetFromFirst, StoreSize,
226 SI->getPointerOperand(), SI->getAlignment(), SI);
227 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000228
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000229 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
230 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
231 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
232 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000233
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000234 void addRange(int64_t Start, int64_t Size, Value *Ptr,
235 unsigned Alignment, Instruction *Inst);
236
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000237};
Nadav Rotem465834c2012-07-24 10:51:42 +0000238
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000239} // end anon namespace
240
241
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000242/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000243/// new range for the specified store at the specified offset, merging into
244/// existing ranges as appropriate.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000245///
246/// Do a linear search of the ranges to see if this can be joined and/or to
247/// find the insertion point in the list. We keep the ranges sorted for
248/// simplicity here. This is a linear search of a linked list, which is ugly,
249/// however the number of ranges is limited, so this won't get crazy slow.
250void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
251 unsigned Alignment, Instruction *Inst) {
252 int64_t End = Start+Size;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000253 range_iterator I = Ranges.begin(), E = Ranges.end();
Nadav Rotem465834c2012-07-24 10:51:42 +0000254
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000255 while (I != E && Start > I->End)
256 ++I;
Nadav Rotem465834c2012-07-24 10:51:42 +0000257
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000258 // We now know that I == E, in which case we didn't find anything to merge
259 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
260 // to insert a new range. Handle this now.
261 if (I == E || End < I->Start) {
262 MemsetRange &R = *Ranges.insert(I, MemsetRange());
263 R.Start = Start;
264 R.End = End;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000265 R.StartPtr = Ptr;
266 R.Alignment = Alignment;
267 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000268 return;
269 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000270
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000271 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000272 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000273
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000274 // At this point, we may have an interval that completely contains our store.
275 // If so, just add it to the interval and return.
276 if (I->Start <= Start && I->End >= End)
277 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000278
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000279 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
280 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000281
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000282 // See if the range extends the start of the range. In this case, it couldn't
283 // possibly cause it to join the prior range, because otherwise we would have
284 // stopped on *it*.
285 if (Start < I->Start) {
286 I->Start = Start;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000287 I->StartPtr = Ptr;
288 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000289 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000290
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000291 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
292 // is in or right at the end of I), and that End >= I->Start. Extend I out to
293 // End.
294 if (End > I->End) {
295 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000296 range_iterator NextI = I;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000297 while (++NextI != E && End >= NextI->Start) {
298 // Merge the range in.
299 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
300 if (NextI->End > I->End)
301 I->End = NextI->End;
302 Ranges.erase(NextI);
303 NextI = I;
304 }
305 }
306}
307
308//===----------------------------------------------------------------------===//
309// MemCpyOpt Pass
310//===----------------------------------------------------------------------===//
311
312namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000313 class MemCpyOpt : public FunctionPass {
Chris Lattner58f9f582010-11-21 00:28:59 +0000314 MemoryDependenceAnalysis *MD;
Chris Lattner23f61a02011-05-01 18:27:11 +0000315 TargetLibraryInfo *TLI;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000316 const DataLayout *DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000317 public:
318 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000319 MemCpyOpt() : FunctionPass(ID) {
320 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Craig Topperf40110f2014-04-25 05:29:35 +0000321 MD = nullptr;
322 TLI = nullptr;
323 DL = nullptr;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000324 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000325
Craig Topper3e4c6972014-03-05 09:10:37 +0000326 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000327
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000328 private:
329 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000330 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000331 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000332 AU.addRequired<DominatorTreeWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000333 AU.addRequired<MemoryDependenceAnalysis>();
334 AU.addRequired<AliasAnalysis>();
Chris Lattner23f61a02011-05-01 18:27:11 +0000335 AU.addRequired<TargetLibraryInfo>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000336 AU.addPreserved<AliasAnalysis>();
337 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000338 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000339
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000340 // Helper fuctions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000341 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000342 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000343 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000344 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000345 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000346 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000347 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
348 uint64_t MSize);
Chris Lattner58f9f582010-11-21 00:28:59 +0000349 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000350 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
351 Value *ByteVal);
352
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000353 bool iterateOnFunction(Function &F);
354 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000355
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000356 char MemCpyOpt::ID = 0;
357}
358
359// createMemCpyOptPass - The public interface to this file...
360FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
361
Owen Anderson8ac477f2010-10-12 19:48:12 +0000362INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
363 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000364INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000365INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chris Lattner23f61a02011-05-01 18:27:11 +0000366INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000367INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
368INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
369 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000370
Chris Lattnerc6381472011-01-08 20:24:01 +0000371/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000372/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sands75b5d272011-02-15 09:23:02 +0000373/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattnerc6381472011-01-08 20:24:01 +0000374/// attempts to merge them together into a memcpy/memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000375Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattnerc6381472011-01-08 20:24:01 +0000376 Value *StartPtr, Value *ByteVal) {
Craig Topperf40110f2014-04-25 05:29:35 +0000377 if (!DL) return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000378
Chris Lattnerc6381472011-01-08 20:24:01 +0000379 // Okay, so we now have a single store that can be splatable. Scan to find
380 // all subsequent stores of the same value to offset from the same pointer.
381 // Join these together into ranges, so we can decide whether contiguous blocks
382 // are stored.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000383 MemsetRanges Ranges(*DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000384
Chris Lattnerc6381472011-01-08 20:24:01 +0000385 BasicBlock::iterator BI = StartInst;
386 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000387 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
388 // If the instruction is readnone, ignore it, otherwise bail out. We
389 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000390 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000391 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
392 break;
393 continue;
394 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000395
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000396 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
397 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000398 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000399
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000400 // Check to see if this stored value is of the same byte-splattable value.
401 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
402 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000403
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000404 // Check to see if this store is to a constant offset from the start ptr.
405 int64_t Offset;
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000406 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000407 Offset, *DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000408 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000409
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000410 Ranges.addStore(Offset, NextStore);
411 } else {
412 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000413
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000414 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
415 !isa<ConstantInt>(MSI->getLength()))
416 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000417
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000418 // Check to see if this store is to a constant offset from the start ptr.
419 int64_t Offset;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000420 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000421 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000422
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000423 Ranges.addMemSet(Offset, MSI);
424 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000425 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000426
Chris Lattnerc6381472011-01-08 20:24:01 +0000427 // If we have no ranges, then we just had a single store with nothing that
428 // could be merged in. This is a very common case of course.
429 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000430 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000431
Chris Lattnerc6381472011-01-08 20:24:01 +0000432 // If we had at least one store that could be merged in, add the starting
433 // store as well. We try to avoid this unless there is at least something
434 // interesting as a small compile-time optimization.
435 Ranges.addInst(0, StartInst);
436
437 // If we create any memsets, we put it right before the first instruction that
438 // isn't part of the memset block. This ensure that the memset is dominated
439 // by any addressing instruction needed by the start of the block.
440 IRBuilder<> Builder(BI);
441
442 // Now that we have full information about ranges, loop over the ranges and
443 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000444 Instruction *AMemSet = nullptr;
Chris Lattnerc6381472011-01-08 20:24:01 +0000445 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
446 I != E; ++I) {
447 const MemsetRange &Range = *I;
Nadav Rotem465834c2012-07-24 10:51:42 +0000448
Chris Lattnerc6381472011-01-08 20:24:01 +0000449 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000450
Chris Lattnerc6381472011-01-08 20:24:01 +0000451 // If it is profitable to lower this range to memset, do so now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000452 if (!Range.isProfitableToUseMemset(*DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000453 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000454
Chris Lattnerc6381472011-01-08 20:24:01 +0000455 // Otherwise, we do want to transform this! Create a new memset.
456 // Get the starting pointer of the block.
457 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000458
Chris Lattnerc6381472011-01-08 20:24:01 +0000459 // Determine alignment
460 unsigned Alignment = Range.Alignment;
461 if (Alignment == 0) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000462 Type *EltType =
Chris Lattnerc6381472011-01-08 20:24:01 +0000463 cast<PointerType>(StartPtr->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000464 Alignment = DL->getABITypeAlignment(EltType);
Chris Lattnerc6381472011-01-08 20:24:01 +0000465 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000466
467 AMemSet =
Chris Lattnerc6381472011-01-08 20:24:01 +0000468 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000469
Chris Lattnerc6381472011-01-08 20:24:01 +0000470 DEBUG(dbgs() << "Replace stores:\n";
471 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
472 dbgs() << *Range.TheStores[i] << '\n';
473 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000474
475 if (!Range.TheStores.empty())
476 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
477
Chris Lattnerc6381472011-01-08 20:24:01 +0000478 // Zap all the stores.
Craig Topper31ee5862013-07-03 15:07:05 +0000479 for (SmallVectorImpl<Instruction *>::const_iterator
Chris Lattnerc6381472011-01-08 20:24:01 +0000480 SI = Range.TheStores.begin(),
Chris Lattner7d6433a2011-01-08 22:19:21 +0000481 SE = Range.TheStores.end(); SI != SE; ++SI) {
482 MD->removeInstruction(*SI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000483 (*SI)->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000484 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000485 ++NumMemSetInfer;
486 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000487
Chris Lattnerc6381472011-01-08 20:24:01 +0000488 return AMemSet;
489}
490
491
Chris Lattnerb5557a72009-09-01 17:09:55 +0000492bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000493 if (!SI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000494
Craig Topperf40110f2014-04-25 05:29:35 +0000495 if (!DL) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +0000496
497 // Detect cases where we're performing call slot forwarding, but
498 // happen to be using a load-store pair to implement it, rather than
499 // a memcpy.
500 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000501 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000502 LI->getParent() == SI->getParent()) {
Eli Friedman5da0ff42011-06-02 21:24:42 +0000503 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000504 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000505 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
506 C = dyn_cast<CallInst>(ldep.getInst());
507
508 if (C) {
509 // Check that nothing touches the dest of the "copy" between
510 // the call and the store.
Eli Friedmane8bbc102011-06-15 01:25:56 +0000511 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
512 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
513 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
514 E = C; I != E; --I) {
515 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
Craig Topperf40110f2014-04-25 05:29:35 +0000516 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000517 break;
518 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000519 }
520 }
521
Owen Anderson18e4fed2010-10-15 22:52:12 +0000522 if (C) {
Duncan Sandsc6ada692012-10-04 10:54:40 +0000523 unsigned storeAlign = SI->getAlignment();
524 if (!storeAlign)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
Duncan Sandsc6ada692012-10-04 10:54:40 +0000526 unsigned loadAlign = LI->getAlignment();
527 if (!loadAlign)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000528 loadAlign = DL->getABITypeAlignment(LI->getType());
Duncan Sandsc6ada692012-10-04 10:54:40 +0000529
Owen Anderson18e4fed2010-10-15 22:52:12 +0000530 bool changed = performCallSlotOptzn(LI,
Nadav Rotem465834c2012-07-24 10:51:42 +0000531 SI->getPointerOperand()->stripPointerCasts(),
Owen Anderson18e4fed2010-10-15 22:52:12 +0000532 LI->getPointerOperand()->stripPointerCasts(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000533 DL->getTypeStoreSize(SI->getOperand(0)->getType()),
Duncan Sandsc6ada692012-10-04 10:54:40 +0000534 std::min(storeAlign, loadAlign), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000535 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000536 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000537 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000538 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000539 LI->eraseFromParent();
540 ++NumMemCpyInstr;
541 return true;
542 }
543 }
544 }
545 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000546
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000547 // There are two cases that are interesting for this code to handle: memcpy
548 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000549
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000550 // Ensure that the value being stored is something that can be memset'able a
551 // byte at a time like "0" or "-1" or any width, as well as things like
552 // 0xA0A0A0A0 and 0.0.
Chris Lattnerc6381472011-01-08 20:24:01 +0000553 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
554 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
555 ByteVal)) {
556 BBI = I; // Don't invalidate iterator.
557 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000558 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000559
Chris Lattnerc6381472011-01-08 20:24:01 +0000560 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000561}
562
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000563bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
564 // See if there is another memset or store neighboring this memset which
565 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000566 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
567 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
568 MSI->getValue())) {
569 BBI = I; // Don't invalidate iterator.
570 return true;
571 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000572 return false;
573}
574
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000575
576/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
577/// and checks for the possibility of a call slot optimization by having
578/// the call write its result directly into the destination of the memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000579bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
580 Value *cpyDest, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000581 uint64_t cpyLen, unsigned cpyAlign,
582 CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000583 // The general transformation to keep in mind is
584 //
585 // call @func(..., src, ...)
586 // memcpy(dest, src, ...)
587 //
588 // ->
589 //
590 // memcpy(dest, src, ...)
591 // call @func(..., dest, ...)
592 //
593 // Since moving the memcpy is technically awkward, we additionally check that
594 // src only holds uninitialized values at the moment of the call, meaning that
595 // the memcpy can be discarded rather than moved.
596
597 // Deliberately get the source and destination with bitcasts stripped away,
598 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000599 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000600
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000601 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000602 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000603 if (!srcAlloca)
604 return false;
605
606 // Check that all of src is copied to dest.
Craig Topperf40110f2014-04-25 05:29:35 +0000607 if (!DL) return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000608
Chris Lattnerb5557a72009-09-01 17:09:55 +0000609 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000610 if (!srcArraySize)
611 return false;
612
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000613 uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000614 srcArraySize->getZExtValue();
615
Owen Anderson18e4fed2010-10-15 22:52:12 +0000616 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000617 return false;
618
619 // Check that accessing the first srcSize bytes of dest will not cause a
620 // trap. Otherwise the transform is invalid since it might cause a trap
621 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000622 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000623 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000624 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000625 if (!destArraySize)
626 return false;
627
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000628 uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000629 destArraySize->getZExtValue();
630
631 if (destSize < srcSize)
632 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000633 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000634 // If the destination is an sret parameter then only accesses that are
635 // outside of the returned struct type can trap.
636 if (!A->hasStructRetAttr())
637 return false;
638
Chris Lattner229907c2011-07-18 04:54:35 +0000639 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Shuxin Yang140d5922013-06-08 04:56:05 +0000640 if (!StructTy->isSized()) {
641 // The call may never return and hence the copy-instruction may never
642 // be executed, and therefore it's not safe to say "the destination
643 // has at least <cpyLen> bytes, as implied by the copy-instruction",
644 return false;
645 }
646
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000647 uint64_t destSize = DL->getTypeAllocSize(StructTy);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000648 if (destSize < srcSize)
649 return false;
650 } else {
651 return false;
652 }
653
Duncan Sands933db772012-10-05 07:29:46 +0000654 // Check that dest points to memory that is at least as aligned as src.
655 unsigned srcAlign = srcAlloca->getAlignment();
656 if (!srcAlign)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000657 srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000658 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
659 // If dest is not aligned enough and we can't increase its alignment then
660 // bail out.
661 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
662 return false;
663
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000664 // Check that src is not accessed except via the call and the memcpy. This
665 // guarantees that it holds only undefined values when passed in (so the final
666 // memcpy can be dropped), that it is not read or written between the call and
667 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000668 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
669 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000670 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000671 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000672
Chandler Carruthcdf47882014-03-09 03:16:01 +0000673 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
674 for (User *UU : U->users())
675 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000676 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000677 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000678 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
679 if (!G->hasAllZeroIndices())
680 return false;
681
682 for (User *UU : U->users())
683 srcUseList.push_back(UU);
684 continue;
685 }
686 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
687 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
688 IT->getIntrinsicID() == Intrinsic::lifetime_end)
689 continue;
690
691 if (U != C && U != cpy)
692 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000693 }
694
Nick Lewycky703e4882014-07-14 18:52:02 +0000695 // Check that src isn't captured by the called function since the
696 // transformation can cause aliasing issues in that case.
697 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
698 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
699 return false;
700
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000701 // Since we're changing the parameter to the callsite, we need to make sure
702 // that what would be the new parameter dominates the callsite.
Chandler Carruth73523022014-01-13 13:07:17 +0000703 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000704 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000705 if (!DT.dominates(cpyDestInst, C))
706 return false;
707
708 // In addition to knowing that the call does not access src in some
709 // unexpected manner, for example via a global, which we deduce from
710 // the use analysis, we also need to know that it does not sneakily
711 // access dest. We rely on AA to figure this out for us.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000712 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chad Rosiera968caf2012-05-14 20:35:04 +0000713 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
714 // If necessary, perform additional analysis.
715 if (MR != AliasAnalysis::NoModRef)
716 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
717 if (MR != AliasAnalysis::NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000718 return false;
719
720 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000721 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000722 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000723 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000724 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
725 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
726 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000727 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000728 if (CS.getArgument(i)->getType() == Dest->getType())
729 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000730 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000731 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
732 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000733 }
734
Owen Andersond071a872008-06-01 21:52:16 +0000735 if (!changedArgument)
736 return false;
737
Duncan Sandsc6ada692012-10-04 10:54:40 +0000738 // If the destination wasn't sufficiently aligned then increase its alignment.
739 if (!isDestSufficientlyAligned) {
740 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
741 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
742 }
743
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000744 // Drop any cached information about the call, because we may have changed
745 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000746 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000747
Chris Lattner58f9f582010-11-21 00:28:59 +0000748 // Remove the memcpy.
749 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000750 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000751
752 return true;
753}
754
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000755/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
756/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
757/// copy from MDep's input if we can. MSize is the size of M's copy.
Nadav Rotem465834c2012-07-24 10:51:42 +0000758///
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000759bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
760 uint64_t MSize) {
761 // We can only transforms memcpy's where the dest of one is the source of the
762 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000763 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000764 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000765
Chris Lattnerfd51c522010-12-09 07:39:50 +0000766 // If dep instruction is reading from our current input, then it is a noop
767 // transfer and substituting the input won't change this instruction. Just
768 // ignore the input and let someone else zap MDep. This handles cases like:
769 // memcpy(a <- a)
770 // memcpy(b <- a)
771 if (M->getSource() == MDep->getSource())
772 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000773
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000774 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000775 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000776 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
777 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
778 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
779 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000780
Chris Lattner58f9f582010-11-21 00:28:59 +0000781 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner59572292010-11-21 08:06:10 +0000782
783 // Verify that the copied-from memory doesn't change in between the two
784 // transfers. For example, in:
785 // memcpy(a <- b)
786 // *b = 42;
787 // memcpy(c <- a)
788 // It would be invalid to transform the second memcpy into memcpy(c <- b).
789 //
790 // TODO: If the code between M and MDep is transparent to the destination "c",
791 // then we could still perform the xform by moving M up to the first memcpy.
792 //
793 // NOTE: This is conservative, it will stop on any read from the source loc,
794 // not just the defining memcpy.
795 MemDepResult SourceDep =
796 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
797 false, M, M->getParent());
798 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
799 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000800
Chris Lattner731caac2010-11-18 08:00:57 +0000801 // If the dest of the second might alias the source of the first, then the
802 // source and dest might overlap. We still want to eliminate the intermediate
803 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000804 bool UseMemMove = false;
805 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
806 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000807
Chris Lattner58f9f582010-11-21 00:28:59 +0000808 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +0000809
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000810 // Make sure to use the lesser of the alignment of the source and the dest
811 // since we're changing where we're reading from, but don't want to increase
812 // the alignment past what can be read from or written to.
813 // TODO: Is this worth it if we're creating a less aligned memcpy? For
814 // example we could be moving from movaps -> movq on x86.
Chris Lattner1385dff2010-11-18 08:07:09 +0000815 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotem465834c2012-07-24 10:51:42 +0000816
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000817 IRBuilder<> Builder(M);
818 if (UseMemMove)
819 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
820 Align, M->isVolatile());
821 else
822 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
823 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +0000824
Chris Lattner59572292010-11-21 08:06:10 +0000825 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +0000826 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +0000827 M->eraseFromParent();
828 ++NumMemCpyInstr;
829 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000830}
831
832
Gabor Greif62f0aac2010-07-28 22:50:26 +0000833/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
834/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
835/// B to be a memcpy from X to Z (or potentially a memmove, depending on
836/// circumstances). This allows later passes to remove the first memcpy
837/// altogether.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000838bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +0000839 // We can only optimize non-volatile memcpy's.
840 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +0000841
Chris Lattnerbc4457e2010-12-09 07:45:45 +0000842 // If the source and destination of the memcpy are the same, then zap it.
843 if (M->getSource() == M->getDest()) {
844 MD->removeInstruction(M);
845 M->eraseFromParent();
846 return false;
847 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +0000848
849 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000850 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +0000851 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000852 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000853 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +0000854 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000855 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000856 MD->removeInstruction(M);
857 M->eraseFromParent();
858 ++NumCpyToSet;
859 return true;
860 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +0000861
Nick Lewycky00703e72014-02-04 00:18:54 +0000862 // The optimizations after this point require the memcpy size.
863 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000864 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +0000865
Nick Lewycky99384942014-02-06 06:29:19 +0000866 // The are three possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +0000867 // a) memcpy-memcpy xform which exposes redundance for DSE.
868 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +0000869 // c) memcpy from freshly alloca'd space or space that has just started its
870 // lifetime copies undefined data, and we can therefore eliminate the
871 // memcpy in favor of the data that was already at the destination.
Chris Lattner58f9f582010-11-21 00:28:59 +0000872 MemDepResult DepInfo = MD->getDependency(M);
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000873 if (DepInfo.isClobber()) {
874 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
875 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsc6ada692012-10-04 10:54:40 +0000876 CopySize->getZExtValue(), M->getAlignment(),
877 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000878 MD->removeInstruction(M);
879 M->eraseFromParent();
880 return true;
881 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +0000882 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000883 }
Ahmed Charles32e983e2012-02-13 06:30:56 +0000884
885 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000886 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
887 M, M->getParent());
888 if (SrcDepInfo.isClobber()) {
889 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
890 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Nick Lewycky99384942014-02-06 06:29:19 +0000891 } else if (SrcDepInfo.isDef()) {
Nick Lewycky77d5fb42014-03-26 23:45:15 +0000892 Instruction *I = SrcDepInfo.getInst();
893 bool hasUndefContents = false;
894
895 if (isa<AllocaInst>(I)) {
896 hasUndefContents = true;
897 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
898 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
899 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
900 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
901 hasUndefContents = true;
902 }
903
904 if (hasUndefContents) {
Nick Lewycky99384942014-02-06 06:29:19 +0000905 MD->removeInstruction(M);
906 M->eraseFromParent();
907 ++NumMemCpyInstr;
908 return true;
909 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000910 }
911
Owen Andersonad5367f2008-04-29 21:51:00 +0000912 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000913}
914
Chris Lattner1145e332009-09-01 17:56:32 +0000915/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
916/// are guaranteed not to alias.
917bool MemCpyOpt::processMemMove(MemMoveInst *M) {
918 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
919
Chris Lattner23f61a02011-05-01 18:27:11 +0000920 if (!TLI->has(LibFunc::memmove))
921 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000922
Chris Lattner1145e332009-09-01 17:56:32 +0000923 // See if the pointers alias.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000924 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +0000925 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000926
David Greene24199232010-01-05 01:27:47 +0000927 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000928
Chris Lattner1145e332009-09-01 17:56:32 +0000929 // If not, then we know we can transform this.
930 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +0000931 Type *ArgTys[3] = { M->getRawDest()->getType(),
932 M->getRawSource()->getType(),
933 M->getLength()->getType() };
Gabor Greif3e44ea12010-07-22 10:37:47 +0000934 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramere6e19332011-07-14 17:45:39 +0000935 ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +0000936
Chris Lattner1145e332009-09-01 17:56:32 +0000937 // MemDep may have over conservative information about this instruction, just
938 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +0000939 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +0000940
941 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +0000942 return true;
943}
Nadav Rotem465834c2012-07-24 10:51:42 +0000944
Chris Lattner58f9f582010-11-21 00:28:59 +0000945/// processByValArgument - This is called on every byval argument in call sites.
946bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Craig Topperf40110f2014-04-25 05:29:35 +0000947 if (!DL) return false;
Chris Lattner1145e332009-09-01 17:56:32 +0000948
Chris Lattner59572292010-11-21 08:06:10 +0000949 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +0000950 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +0000951 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000952 uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
Chris Lattner59572292010-11-21 08:06:10 +0000953 MemDepResult DepInfo =
954 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
955 true, CS.getInstruction(),
956 CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +0000957 if (!DepInfo.isClobber())
958 return false;
959
960 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
961 // a memcpy, see if we can byval from the source of the memcpy instead of the
962 // result.
963 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +0000964 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +0000965 ByValArg->stripPointerCasts() != MDep->getDest())
966 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000967
Chris Lattner58f9f582010-11-21 00:28:59 +0000968 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +0000969 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000970 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +0000971 return false;
972
Chris Lattner83791ce2011-05-23 00:03:39 +0000973 // Get the alignment of the byval. If the call doesn't specify the alignment,
974 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +0000975 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +0000976 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000977
Chris Lattner83791ce2011-05-23 00:03:39 +0000978 // If it is greater than the memcpy, then we check to see if we can force the
979 // source of the memcpy to the alignment we need. If we fail, we bail out.
980 if (MDep->getAlignment() < ByValAlign &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000981 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +0000982 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000983
Chris Lattner58f9f582010-11-21 00:28:59 +0000984 // Verify that the copied-from memory doesn't change in between the memcpy and
985 // the byval call.
986 // memcpy(a <- b)
987 // *b = 42;
988 // foo(*a)
989 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +0000990 //
991 // NOTE: This is conservative, it will stop on any read from the source loc,
992 // not just the defining memcpy.
993 MemDepResult SourceDep =
994 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
995 false, CS.getInstruction(), MDep->getParent());
996 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
997 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000998
Chris Lattner58f9f582010-11-21 00:28:59 +0000999 Value *TmpCast = MDep->getSource();
1000 if (MDep->getSource()->getType() != ByValArg->getType())
1001 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1002 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001003
Chris Lattner58f9f582010-11-21 00:28:59 +00001004 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
1005 << " " << *MDep << "\n"
1006 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001007
Chris Lattner58f9f582010-11-21 00:28:59 +00001008 // Otherwise we're good! Update the byval argument.
1009 CS.setArgument(ArgNo, TmpCast);
1010 ++NumMemCpyInstr;
1011 return true;
1012}
1013
1014/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001015bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001016 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001017
Chris Lattnerb5557a72009-09-01 17:09:55 +00001018 // Walk all instruction in the function.
Owen Anderson6a7355c2008-04-21 07:45:10 +00001019 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001020 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001021 // Avoid invalidating the iterator.
1022 Instruction *I = BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001023
Chris Lattner58f9f582010-11-21 00:28:59 +00001024 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001025
Owen Anderson6a7355c2008-04-21 07:45:10 +00001026 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001027 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001028 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1029 RepeatInstruction = processMemSet(M, BI);
1030 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001031 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001032 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001033 RepeatInstruction = processMemMove(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001034 else if (CallSite CS = (Value*)I) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001035 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001036 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001037 MadeChange |= processByValArgument(CS, i);
1038 }
1039
1040 // Reprocess the instruction if desired.
1041 if (RepeatInstruction) {
Chris Lattner7d6433a2011-01-08 22:19:21 +00001042 if (BI != BB->begin()) --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001043 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001044 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001045 }
1046 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001047
Chris Lattnerb5557a72009-09-01 17:09:55 +00001048 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001049}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001050
1051// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1052// function.
1053//
1054bool MemCpyOpt::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001055 if (skipOptnoneFunction(F))
1056 return false;
1057
Chris Lattnerb5557a72009-09-01 17:09:55 +00001058 bool MadeChange = false;
Chris Lattner58f9f582010-11-21 00:28:59 +00001059 MD = &getAnalysis<MemoryDependenceAnalysis>();
Rafael Espindola93512512014-02-25 17:30:31 +00001060 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001061 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chris Lattner23f61a02011-05-01 18:27:11 +00001062 TLI = &getAnalysis<TargetLibraryInfo>();
Nadav Rotem465834c2012-07-24 10:51:42 +00001063
Chris Lattner23f61a02011-05-01 18:27:11 +00001064 // If we don't have at least memset and memcpy, there is little point of doing
1065 // anything here. These are required by a freestanding implementation, so if
1066 // even they are disabled, there is no point in trying hard.
1067 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1068 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001069
Chris Lattnerb5557a72009-09-01 17:09:55 +00001070 while (1) {
1071 if (!iterateOnFunction(F))
1072 break;
1073 MadeChange = true;
1074 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001075
Craig Topperf40110f2014-04-25 05:29:35 +00001076 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001077 return MadeChange;
1078}