blob: 348e12f35b8a8faf062c70540934dfaff37ef665 [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
15#define DEBUG_TYPE "memcpyopt"
16#include "llvm/Transforms/Scalar.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000019#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000024#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/GlobalVariable.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000029#include "llvm/Support/Debug.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner23f61a02011-05-01 18:27:11 +000031#include "llvm/Target/TargetLibraryInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000032#include "llvm/Transforms/Utils/Local.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000033#include <list>
34using namespace llvm;
35
36STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
37STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000038STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000039STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000040
Benjamin Kramer15a257d2012-09-13 16:29:49 +000041static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000042 bool &VariableIdxFound, const DataLayout &TD){
Owen Andersonef9a6fd2008-04-09 08:23:16 +000043 // Skip over the first indices.
44 gep_type_iterator GTI = gep_type_begin(GEP);
45 for (unsigned i = 1; i != Idx; ++i, ++GTI)
46 /*skip along*/;
Nadav Rotem465834c2012-07-24 10:51:42 +000047
Owen Andersonef9a6fd2008-04-09 08:23:16 +000048 // Compute the offset implied by the rest of the indices.
49 int64_t Offset = 0;
50 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
51 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
52 if (OpC == 0)
53 return VariableIdxFound = true;
54 if (OpC->isZero()) continue; // No offset.
55
56 // Handle struct indices, which add their field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +000057 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000058 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
59 continue;
60 }
Nadav Rotem465834c2012-07-24 10:51:42 +000061
Owen Andersonef9a6fd2008-04-09 08:23:16 +000062 // Otherwise, we have a sequential type like an array or vector. Multiply
63 // the index by the ElementSize.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000064 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Owen Andersonef9a6fd2008-04-09 08:23:16 +000065 Offset += Size*OpC->getSExtValue();
66 }
67
68 return Offset;
69}
70
71/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
72/// constant offset, and return that constant offset. For example, Ptr1 might
73/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
74static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000075 const DataLayout &TD) {
Chris Lattnerfa7c29d2011-01-12 01:43:46 +000076 Ptr1 = Ptr1->stripPointerCasts();
77 Ptr2 = Ptr2->stripPointerCasts();
Benjamin Kramer15a257d2012-09-13 16:29:49 +000078 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
79 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
Nadav Rotem465834c2012-07-24 10:51:42 +000080
Chris Lattner5120ebf2011-01-08 21:07:56 +000081 bool VariableIdxFound = false;
82
83 // If one pointer is a GEP and the other isn't, then see if the GEP is a
84 // constant offset from the base, as in "P" and "gep P, 1".
85 if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
86 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD);
87 return !VariableIdxFound;
88 }
89
90 if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
91 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD);
92 return !VariableIdxFound;
93 }
Nadav Rotem465834c2012-07-24 10:51:42 +000094
Owen Andersonef9a6fd2008-04-09 08:23:16 +000095 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
96 // base. After that base, they may have some number of common (and
97 // potentially variable) indices. After that they handle some constant
98 // offset, which determines their offset from each other. At this point, we
99 // handle no other case.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000100 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
101 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000102
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000103 // Skip any common indices and track the GEP types.
104 unsigned Idx = 1;
105 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
106 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
107 break;
108
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000109 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
110 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
111 if (VariableIdxFound) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000112
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000113 Offset = Offset2-Offset1;
114 return true;
115}
116
117
118/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
119/// This allows us to analyze stores like:
120/// store 0 -> P+1
121/// store 0 -> P+0
122/// store 0 -> P+3
123/// store 0 -> P+2
124/// which sometimes happens with stores to arrays of structs etc. When we see
125/// the first store, we make a range [1, 2). The second store extends the range
126/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
127/// two ranges into [0, 3) which is memset'able.
128namespace {
129struct MemsetRange {
130 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +0000131 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000132 int64_t Start, End;
133
134 /// StartPtr - The getelementptr instruction that points to the start of the
135 /// range.
136 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000137
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000138 /// Alignment - The known alignment of the first store.
139 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +0000140
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000141 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000142 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000143
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000144 bool isProfitableToUseMemset(const DataLayout &TD) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000145
146};
147} // end anon namespace
148
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000149bool MemsetRange::isProfitableToUseMemset(const DataLayout &TD) const {
Chad Rosier32775572011-12-05 22:53:09 +0000150 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000151 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000152
153 // If there is nothing to merge, don't do anything.
154 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000155
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000156 // If any of the stores are a memset, then it is always good to extend the
157 // memset.
158 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
159 if (!isa<StoreInst>(TheStores[i]))
160 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000161
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000162 // Assume that the code generator is capable of merging pairs of stores
163 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000164 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000165
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000166 // If we have fewer than 8 stores, it can still be worthwhile to do this.
167 // For example, merging 4 i8 stores into an i32 store is useful almost always.
168 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
169 // memset will be split into 2 32-bit stores anyway) and doing so can
170 // pessimize the llvm optimizer.
171 //
172 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000173 // the maximum GPR width is the same size as the largest legal integer
174 // size. If so, check to see whether we will end up actually reducing the
175 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000176 unsigned Bytes = unsigned(End-Start);
Matt Arsenault899f7d22013-09-16 22:43:16 +0000177 unsigned MaxIntSize = TD.getLargestLegalIntTypeSize();
178 if (MaxIntSize == 0)
179 MaxIntSize = 1;
180 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000181
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000182 // Assume the remaining bytes if any are done a byte at a time.
Matt Arsenault899f7d22013-09-16 22:43:16 +0000183 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000184
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000185 // If we will reduce the # stores (according to this heuristic), do the
186 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
187 // etc.
188 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000189}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000190
191
192namespace {
193class MemsetRanges {
194 /// Ranges - A sorted list of the memset ranges. We use std::list here
195 /// because each element is relatively large and expensive to copy.
196 std::list<MemsetRange> Ranges;
197 typedef std::list<MemsetRange>::iterator range_iterator;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000198 const DataLayout &DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000199public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000200 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000201
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000202 typedef std::list<MemsetRange>::const_iterator const_iterator;
203 const_iterator begin() const { return Ranges.begin(); }
204 const_iterator end() const { return Ranges.end(); }
205 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000206
Chris Lattnerc6381472011-01-08 20:24:01 +0000207 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000208 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
209 addStore(OffsetFromFirst, SI);
210 else
211 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000212 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000213
214 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000215 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000216
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000217 addRange(OffsetFromFirst, StoreSize,
218 SI->getPointerOperand(), SI->getAlignment(), SI);
219 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000220
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000221 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
222 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
223 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
224 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000225
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000226 void addRange(int64_t Start, int64_t Size, Value *Ptr,
227 unsigned Alignment, Instruction *Inst);
228
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000229};
Nadav Rotem465834c2012-07-24 10:51:42 +0000230
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000231} // end anon namespace
232
233
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000234/// addRange - Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000235/// new range for the specified store at the specified offset, merging into
236/// existing ranges as appropriate.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000237///
238/// Do a linear search of the ranges to see if this can be joined and/or to
239/// find the insertion point in the list. We keep the ranges sorted for
240/// simplicity here. This is a linear search of a linked list, which is ugly,
241/// however the number of ranges is limited, so this won't get crazy slow.
242void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
243 unsigned Alignment, Instruction *Inst) {
244 int64_t End = Start+Size;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000245 range_iterator I = Ranges.begin(), E = Ranges.end();
Nadav Rotem465834c2012-07-24 10:51:42 +0000246
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000247 while (I != E && Start > I->End)
248 ++I;
Nadav Rotem465834c2012-07-24 10:51:42 +0000249
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000250 // We now know that I == E, in which case we didn't find anything to merge
251 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
252 // to insert a new range. Handle this now.
253 if (I == E || End < I->Start) {
254 MemsetRange &R = *Ranges.insert(I, MemsetRange());
255 R.Start = Start;
256 R.End = End;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000257 R.StartPtr = Ptr;
258 R.Alignment = Alignment;
259 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000260 return;
261 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000262
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000263 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000264 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000265
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000266 // At this point, we may have an interval that completely contains our store.
267 // If so, just add it to the interval and return.
268 if (I->Start <= Start && I->End >= End)
269 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000270
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000271 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
272 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000273
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000274 // See if the range extends the start of the range. In this case, it couldn't
275 // possibly cause it to join the prior range, because otherwise we would have
276 // stopped on *it*.
277 if (Start < I->Start) {
278 I->Start = Start;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000279 I->StartPtr = Ptr;
280 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000281 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000282
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000283 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
284 // is in or right at the end of I), and that End >= I->Start. Extend I out to
285 // End.
286 if (End > I->End) {
287 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000288 range_iterator NextI = I;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000289 while (++NextI != E && End >= NextI->Start) {
290 // Merge the range in.
291 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
292 if (NextI->End > I->End)
293 I->End = NextI->End;
294 Ranges.erase(NextI);
295 NextI = I;
296 }
297 }
298}
299
300//===----------------------------------------------------------------------===//
301// MemCpyOpt Pass
302//===----------------------------------------------------------------------===//
303
304namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000305 class MemCpyOpt : public FunctionPass {
Chris Lattner58f9f582010-11-21 00:28:59 +0000306 MemoryDependenceAnalysis *MD;
Chris Lattner23f61a02011-05-01 18:27:11 +0000307 TargetLibraryInfo *TLI;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000308 const DataLayout *DL;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000309 public:
310 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000311 MemCpyOpt() : FunctionPass(ID) {
312 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
Chris Lattner58f9f582010-11-21 00:28:59 +0000313 MD = 0;
Chris Lattner23f61a02011-05-01 18:27:11 +0000314 TLI = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 DL = 0;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000316 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000317
Craig Topper3e4c6972014-03-05 09:10:37 +0000318 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000319
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000320 private:
321 // This transformation requires dominator postdominator info
Craig Topper3e4c6972014-03-05 09:10:37 +0000322 void getAnalysisUsage(AnalysisUsage &AU) const override {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000323 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000324 AU.addRequired<DominatorTreeWrapperPass>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000325 AU.addRequired<MemoryDependenceAnalysis>();
326 AU.addRequired<AliasAnalysis>();
Chris Lattner23f61a02011-05-01 18:27:11 +0000327 AU.addRequired<TargetLibraryInfo>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000328 AU.addPreserved<AliasAnalysis>();
329 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000330 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000331
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000332 // Helper fuctions
Chris Lattnerb5557a72009-09-01 17:09:55 +0000333 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000334 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000335 bool processMemCpy(MemCpyInst *M);
Chris Lattner1145e332009-09-01 17:56:32 +0000336 bool processMemMove(MemMoveInst *M);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000337 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000338 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000339 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
340 uint64_t MSize);
Chris Lattner58f9f582010-11-21 00:28:59 +0000341 bool processByValArgument(CallSite CS, unsigned ArgNo);
Chris Lattnerc6381472011-01-08 20:24:01 +0000342 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
343 Value *ByteVal);
344
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000345 bool iterateOnFunction(Function &F);
346 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000347
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000348 char MemCpyOpt::ID = 0;
349}
350
351// createMemCpyOptPass - The public interface to this file...
352FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
353
Owen Anderson8ac477f2010-10-12 19:48:12 +0000354INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
355 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000356INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000357INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chris Lattner23f61a02011-05-01 18:27:11 +0000358INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000359INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
360INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
361 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000362
Chris Lattnerc6381472011-01-08 20:24:01 +0000363/// tryMergingIntoMemset - When scanning forward over instructions, we look for
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000364/// some other patterns to fold away. In particular, this looks for stores to
Duncan Sands75b5d272011-02-15 09:23:02 +0000365/// neighboring locations of memory. If it sees enough consecutive ones, it
Chris Lattnerc6381472011-01-08 20:24:01 +0000366/// attempts to merge them together into a memcpy/memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000367Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
Chris Lattnerc6381472011-01-08 20:24:01 +0000368 Value *StartPtr, Value *ByteVal) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000369 if (DL == 0) return 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000370
Chris Lattnerc6381472011-01-08 20:24:01 +0000371 // Okay, so we now have a single store that can be splatable. Scan to find
372 // all subsequent stores of the same value to offset from the same pointer.
373 // Join these together into ranges, so we can decide whether contiguous blocks
374 // are stored.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000375 MemsetRanges Ranges(*DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000376
Chris Lattnerc6381472011-01-08 20:24:01 +0000377 BasicBlock::iterator BI = StartInst;
378 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000379 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
380 // If the instruction is readnone, ignore it, otherwise bail out. We
381 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000382 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000383 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
384 break;
385 continue;
386 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000387
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000388 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
389 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000390 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000391
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000392 // Check to see if this stored value is of the same byte-splattable value.
393 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
394 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000395
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000396 // Check to see if this store is to a constant offset from the start ptr.
397 int64_t Offset;
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000398 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000399 Offset, *DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000400 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000401
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000402 Ranges.addStore(Offset, NextStore);
403 } else {
404 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000405
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000406 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
407 !isa<ConstantInt>(MSI->getLength()))
408 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000409
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000410 // Check to see if this store is to a constant offset from the start ptr.
411 int64_t Offset;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000412 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *DL))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000413 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000414
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000415 Ranges.addMemSet(Offset, MSI);
416 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000417 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000418
Chris Lattnerc6381472011-01-08 20:24:01 +0000419 // If we have no ranges, then we just had a single store with nothing that
420 // could be merged in. This is a very common case of course.
421 if (Ranges.empty())
422 return 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000423
Chris Lattnerc6381472011-01-08 20:24:01 +0000424 // If we had at least one store that could be merged in, add the starting
425 // store as well. We try to avoid this unless there is at least something
426 // interesting as a small compile-time optimization.
427 Ranges.addInst(0, StartInst);
428
429 // If we create any memsets, we put it right before the first instruction that
430 // isn't part of the memset block. This ensure that the memset is dominated
431 // by any addressing instruction needed by the start of the block.
432 IRBuilder<> Builder(BI);
433
434 // Now that we have full information about ranges, loop over the ranges and
435 // emit memset's for anything big enough to be worthwhile.
436 Instruction *AMemSet = 0;
437 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
438 I != E; ++I) {
439 const MemsetRange &Range = *I;
Nadav Rotem465834c2012-07-24 10:51:42 +0000440
Chris Lattnerc6381472011-01-08 20:24:01 +0000441 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000442
Chris Lattnerc6381472011-01-08 20:24:01 +0000443 // If it is profitable to lower this range to memset, do so now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000444 if (!Range.isProfitableToUseMemset(*DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000445 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000446
Chris Lattnerc6381472011-01-08 20:24:01 +0000447 // Otherwise, we do want to transform this! Create a new memset.
448 // Get the starting pointer of the block.
449 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000450
Chris Lattnerc6381472011-01-08 20:24:01 +0000451 // Determine alignment
452 unsigned Alignment = Range.Alignment;
453 if (Alignment == 0) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000454 Type *EltType =
Chris Lattnerc6381472011-01-08 20:24:01 +0000455 cast<PointerType>(StartPtr->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000456 Alignment = DL->getABITypeAlignment(EltType);
Chris Lattnerc6381472011-01-08 20:24:01 +0000457 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000458
459 AMemSet =
Chris Lattnerc6381472011-01-08 20:24:01 +0000460 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000461
Chris Lattnerc6381472011-01-08 20:24:01 +0000462 DEBUG(dbgs() << "Replace stores:\n";
463 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
464 dbgs() << *Range.TheStores[i] << '\n';
465 dbgs() << "With: " << *AMemSet << '\n');
Devang Patelc7e4fa72011-05-04 21:58:58 +0000466
467 if (!Range.TheStores.empty())
468 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
469
Chris Lattnerc6381472011-01-08 20:24:01 +0000470 // Zap all the stores.
Craig Topper31ee5862013-07-03 15:07:05 +0000471 for (SmallVectorImpl<Instruction *>::const_iterator
Chris Lattnerc6381472011-01-08 20:24:01 +0000472 SI = Range.TheStores.begin(),
Chris Lattner7d6433a2011-01-08 22:19:21 +0000473 SE = Range.TheStores.end(); SI != SE; ++SI) {
474 MD->removeInstruction(*SI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000475 (*SI)->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000476 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000477 ++NumMemSetInfer;
478 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000479
Chris Lattnerc6381472011-01-08 20:24:01 +0000480 return AMemSet;
481}
482
483
Chris Lattnerb5557a72009-09-01 17:09:55 +0000484bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000485 if (!SI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000486
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000487 if (DL == 0) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +0000488
489 // Detect cases where we're performing call slot forwarding, but
490 // happen to be using a load-store pair to implement it, rather than
491 // a memcpy.
492 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000493 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000494 LI->getParent() == SI->getParent()) {
Eli Friedman5da0ff42011-06-02 21:24:42 +0000495 MemDepResult ldep = MD->getDependency(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000496 CallInst *C = 0;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000497 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
498 C = dyn_cast<CallInst>(ldep.getInst());
499
500 if (C) {
501 // Check that nothing touches the dest of the "copy" between
502 // the call and the store.
Eli Friedmane8bbc102011-06-15 01:25:56 +0000503 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
504 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
505 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
506 E = C; I != E; --I) {
507 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
Eli Friedman5da0ff42011-06-02 21:24:42 +0000508 C = 0;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000509 break;
510 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000511 }
512 }
513
Owen Anderson18e4fed2010-10-15 22:52:12 +0000514 if (C) {
Duncan Sandsc6ada692012-10-04 10:54:40 +0000515 unsigned storeAlign = SI->getAlignment();
516 if (!storeAlign)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000517 storeAlign = DL->getABITypeAlignment(SI->getOperand(0)->getType());
Duncan Sandsc6ada692012-10-04 10:54:40 +0000518 unsigned loadAlign = LI->getAlignment();
519 if (!loadAlign)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000520 loadAlign = DL->getABITypeAlignment(LI->getType());
Duncan Sandsc6ada692012-10-04 10:54:40 +0000521
Owen Anderson18e4fed2010-10-15 22:52:12 +0000522 bool changed = performCallSlotOptzn(LI,
Nadav Rotem465834c2012-07-24 10:51:42 +0000523 SI->getPointerOperand()->stripPointerCasts(),
Owen Anderson18e4fed2010-10-15 22:52:12 +0000524 LI->getPointerOperand()->stripPointerCasts(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 DL->getTypeStoreSize(SI->getOperand(0)->getType()),
Duncan Sandsc6ada692012-10-04 10:54:40 +0000526 std::min(storeAlign, loadAlign), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000527 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000528 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000529 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000530 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000531 LI->eraseFromParent();
532 ++NumMemCpyInstr;
533 return true;
534 }
535 }
536 }
537 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000538
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000539 // There are two cases that are interesting for this code to handle: memcpy
540 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000541
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000542 // Ensure that the value being stored is something that can be memset'able a
543 // byte at a time like "0" or "-1" or any width, as well as things like
544 // 0xA0A0A0A0 and 0.0.
Chris Lattnerc6381472011-01-08 20:24:01 +0000545 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
546 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
547 ByteVal)) {
548 BBI = I; // Don't invalidate iterator.
549 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000550 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000551
Chris Lattnerc6381472011-01-08 20:24:01 +0000552 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000553}
554
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000555bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
556 // See if there is another memset or store neighboring this memset which
557 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000558 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
559 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
560 MSI->getValue())) {
561 BBI = I; // Don't invalidate iterator.
562 return true;
563 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000564 return false;
565}
566
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000567
568/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
569/// and checks for the possibility of a call slot optimization by having
570/// the call write its result directly into the destination of the memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000571bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
572 Value *cpyDest, Value *cpySrc,
Duncan Sandsc6ada692012-10-04 10:54:40 +0000573 uint64_t cpyLen, unsigned cpyAlign,
574 CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000575 // The general transformation to keep in mind is
576 //
577 // call @func(..., src, ...)
578 // memcpy(dest, src, ...)
579 //
580 // ->
581 //
582 // memcpy(dest, src, ...)
583 // call @func(..., dest, ...)
584 //
585 // Since moving the memcpy is technically awkward, we additionally check that
586 // src only holds uninitialized values at the moment of the call, meaning that
587 // the memcpy can be discarded rather than moved.
588
589 // Deliberately get the source and destination with bitcasts stripped away,
590 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000591 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000592
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000593 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000594 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000595 if (!srcAlloca)
596 return false;
597
598 // Check that all of src is copied to dest.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000599 if (DL == 0) return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000600
Chris Lattnerb5557a72009-09-01 17:09:55 +0000601 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000602 if (!srcArraySize)
603 return false;
604
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000605 uint64_t srcSize = DL->getTypeAllocSize(srcAlloca->getAllocatedType()) *
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000606 srcArraySize->getZExtValue();
607
Owen Anderson18e4fed2010-10-15 22:52:12 +0000608 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000609 return false;
610
611 // Check that accessing the first srcSize bytes of dest will not cause a
612 // trap. Otherwise the transform is invalid since it might cause a trap
613 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000614 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000615 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000616 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000617 if (!destArraySize)
618 return false;
619
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000620 uint64_t destSize = DL->getTypeAllocSize(A->getAllocatedType()) *
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000621 destArraySize->getZExtValue();
622
623 if (destSize < srcSize)
624 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000625 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000626 // If the destination is an sret parameter then only accesses that are
627 // outside of the returned struct type can trap.
628 if (!A->hasStructRetAttr())
629 return false;
630
Chris Lattner229907c2011-07-18 04:54:35 +0000631 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
Shuxin Yang140d5922013-06-08 04:56:05 +0000632 if (!StructTy->isSized()) {
633 // The call may never return and hence the copy-instruction may never
634 // be executed, and therefore it's not safe to say "the destination
635 // has at least <cpyLen> bytes, as implied by the copy-instruction",
636 return false;
637 }
638
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000639 uint64_t destSize = DL->getTypeAllocSize(StructTy);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000640 if (destSize < srcSize)
641 return false;
642 } else {
643 return false;
644 }
645
Duncan Sands933db772012-10-05 07:29:46 +0000646 // Check that dest points to memory that is at least as aligned as src.
647 unsigned srcAlign = srcAlloca->getAlignment();
648 if (!srcAlign)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000649 srcAlign = DL->getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000650 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
651 // If dest is not aligned enough and we can't increase its alignment then
652 // bail out.
653 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
654 return false;
655
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000656 // Check that src is not accessed except via the call and the memcpy. This
657 // guarantees that it holds only undefined values when passed in (so the final
658 // memcpy can be dropped), that it is not read or written between the call and
659 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000660 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
661 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000662 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000663 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000664
Chandler Carruthcdf47882014-03-09 03:16:01 +0000665 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
666 for (User *UU : U->users())
667 srcUseList.push_back(UU);
668 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
Owen Anderson38099c12008-06-01 22:26:26 +0000669 if (G->hasAllZeroIndices())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000670 for (User *UU : U->users())
671 srcUseList.push_back(UU);
Owen Anderson38099c12008-06-01 22:26:26 +0000672 else
673 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000674 } else if (U != C && U != cpy) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000675 return false;
676 }
677 }
678
679 // Since we're changing the parameter to the callsite, we need to make sure
680 // that what would be the new parameter dominates the callsite.
Chandler Carruth73523022014-01-13 13:07:17 +0000681 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000682 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000683 if (!DT.dominates(cpyDestInst, C))
684 return false;
685
686 // In addition to knowing that the call does not access src in some
687 // unexpected manner, for example via a global, which we deduce from
688 // the use analysis, we also need to know that it does not sneakily
689 // access dest. We rely on AA to figure this out for us.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000690 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chad Rosiera968caf2012-05-14 20:35:04 +0000691 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
692 // If necessary, perform additional analysis.
693 if (MR != AliasAnalysis::NoModRef)
694 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
695 if (MR != AliasAnalysis::NoModRef)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000696 return false;
697
698 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000699 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000700 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000701 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000702 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
703 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
704 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000705 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000706 if (CS.getArgument(i)->getType() == Dest->getType())
707 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000708 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000709 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
710 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000711 }
712
Owen Andersond071a872008-06-01 21:52:16 +0000713 if (!changedArgument)
714 return false;
715
Duncan Sandsc6ada692012-10-04 10:54:40 +0000716 // If the destination wasn't sufficiently aligned then increase its alignment.
717 if (!isDestSufficientlyAligned) {
718 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
719 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
720 }
721
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000722 // Drop any cached information about the call, because we may have changed
723 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000724 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000725
Chris Lattner58f9f582010-11-21 00:28:59 +0000726 // Remove the memcpy.
727 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000728 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000729
730 return true;
731}
732
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000733/// processMemCpyMemCpyDependence - We've found that the (upward scanning)
734/// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
735/// copy from MDep's input if we can. MSize is the size of M's copy.
Nadav Rotem465834c2012-07-24 10:51:42 +0000736///
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000737bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
738 uint64_t MSize) {
739 // We can only transforms memcpy's where the dest of one is the source of the
740 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000741 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000742 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000743
Chris Lattnerfd51c522010-12-09 07:39:50 +0000744 // If dep instruction is reading from our current input, then it is a noop
745 // transfer and substituting the input won't change this instruction. Just
746 // ignore the input and let someone else zap MDep. This handles cases like:
747 // memcpy(a <- a)
748 // memcpy(b <- a)
749 if (M->getSource() == MDep->getSource())
750 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000751
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000752 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000753 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000754 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
755 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
756 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
757 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000758
Chris Lattner58f9f582010-11-21 00:28:59 +0000759 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner59572292010-11-21 08:06:10 +0000760
761 // Verify that the copied-from memory doesn't change in between the two
762 // transfers. For example, in:
763 // memcpy(a <- b)
764 // *b = 42;
765 // memcpy(c <- a)
766 // It would be invalid to transform the second memcpy into memcpy(c <- b).
767 //
768 // TODO: If the code between M and MDep is transparent to the destination "c",
769 // then we could still perform the xform by moving M up to the first memcpy.
770 //
771 // NOTE: This is conservative, it will stop on any read from the source loc,
772 // not just the defining memcpy.
773 MemDepResult SourceDep =
774 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
775 false, M, M->getParent());
776 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
777 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000778
Chris Lattner731caac2010-11-18 08:00:57 +0000779 // If the dest of the second might alias the source of the first, then the
780 // source and dest might overlap. We still want to eliminate the intermediate
781 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000782 bool UseMemMove = false;
783 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
784 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000785
Chris Lattner58f9f582010-11-21 00:28:59 +0000786 // If all checks passed, then we can transform M.
Nadav Rotem465834c2012-07-24 10:51:42 +0000787
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000788 // Make sure to use the lesser of the alignment of the source and the dest
789 // since we're changing where we're reading from, but don't want to increase
790 // the alignment past what can be read from or written to.
791 // TODO: Is this worth it if we're creating a less aligned memcpy? For
792 // example we could be moving from movaps -> movq on x86.
Chris Lattner1385dff2010-11-18 08:07:09 +0000793 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
Nadav Rotem465834c2012-07-24 10:51:42 +0000794
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000795 IRBuilder<> Builder(M);
796 if (UseMemMove)
797 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
798 Align, M->isVolatile());
799 else
800 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
801 Align, M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +0000802
Chris Lattner59572292010-11-21 08:06:10 +0000803 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +0000804 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +0000805 M->eraseFromParent();
806 ++NumMemCpyInstr;
807 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000808}
809
810
Gabor Greif62f0aac2010-07-28 22:50:26 +0000811/// processMemCpy - perform simplification of memcpy's. If we have memcpy A
812/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
813/// B to be a memcpy from X to Z (or potentially a memmove, depending on
814/// circumstances). This allows later passes to remove the first memcpy
815/// altogether.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000816bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +0000817 // We can only optimize non-volatile memcpy's.
818 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +0000819
Chris Lattnerbc4457e2010-12-09 07:45:45 +0000820 // If the source and destination of the memcpy are the same, then zap it.
821 if (M->getSource() == M->getDest()) {
822 MD->removeInstruction(M);
823 M->eraseFromParent();
824 return false;
825 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +0000826
827 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000828 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +0000829 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000830 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000831 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +0000832 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000833 M->getAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +0000834 MD->removeInstruction(M);
835 M->eraseFromParent();
836 ++NumCpyToSet;
837 return true;
838 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +0000839
Nick Lewycky00703e72014-02-04 00:18:54 +0000840 // The optimizations after this point require the memcpy size.
841 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
842 if (CopySize == 0) return false;
843
Nick Lewycky99384942014-02-06 06:29:19 +0000844 // The are three possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +0000845 // a) memcpy-memcpy xform which exposes redundance for DSE.
846 // b) call-memcpy xform for return slot optimization.
Nick Lewycky99384942014-02-06 06:29:19 +0000847 // c) memcpy from freshly alloca'd space copies undefined data, and we can
848 // therefore eliminate the memcpy in favor of the data that was already
849 // at the destination.
Chris Lattner58f9f582010-11-21 00:28:59 +0000850 MemDepResult DepInfo = MD->getDependency(M);
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000851 if (DepInfo.isClobber()) {
852 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
853 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Duncan Sandsc6ada692012-10-04 10:54:40 +0000854 CopySize->getZExtValue(), M->getAlignment(),
855 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000856 MD->removeInstruction(M);
857 M->eraseFromParent();
858 return true;
859 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +0000860 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000861 }
Ahmed Charles32e983e2012-02-13 06:30:56 +0000862
863 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000864 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
865 M, M->getParent());
866 if (SrcDepInfo.isClobber()) {
867 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
868 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
Nick Lewycky99384942014-02-06 06:29:19 +0000869 } else if (SrcDepInfo.isDef()) {
870 if (isa<AllocaInst>(SrcDepInfo.getInst())) {
871 MD->removeInstruction(M);
872 M->eraseFromParent();
873 ++NumMemCpyInstr;
874 return true;
875 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +0000876 }
877
Owen Andersonad5367f2008-04-29 21:51:00 +0000878 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000879}
880
Chris Lattner1145e332009-09-01 17:56:32 +0000881/// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
882/// are guaranteed not to alias.
883bool MemCpyOpt::processMemMove(MemMoveInst *M) {
884 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
885
Chris Lattner23f61a02011-05-01 18:27:11 +0000886 if (!TLI->has(LibFunc::memmove))
887 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000888
Chris Lattner1145e332009-09-01 17:56:32 +0000889 // See if the pointers alias.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000890 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +0000891 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000892
David Greene24199232010-01-05 01:27:47 +0000893 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000894
Chris Lattner1145e332009-09-01 17:56:32 +0000895 // If not, then we know we can transform this.
896 Module *Mod = M->getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +0000897 Type *ArgTys[3] = { M->getRawDest()->getType(),
898 M->getRawSource()->getType(),
899 M->getLength()->getType() };
Gabor Greif3e44ea12010-07-22 10:37:47 +0000900 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
Benjamin Kramere6e19332011-07-14 17:45:39 +0000901 ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +0000902
Chris Lattner1145e332009-09-01 17:56:32 +0000903 // MemDep may have over conservative information about this instruction, just
904 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +0000905 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +0000906
907 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +0000908 return true;
909}
Nadav Rotem465834c2012-07-24 10:51:42 +0000910
Chris Lattner58f9f582010-11-21 00:28:59 +0000911/// processByValArgument - This is called on every byval argument in call sites.
912bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000913 if (DL == 0) return false;
Chris Lattner1145e332009-09-01 17:56:32 +0000914
Chris Lattner59572292010-11-21 08:06:10 +0000915 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +0000916 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +0000917 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000918 uint64_t ByValSize = DL->getTypeAllocSize(ByValTy);
Chris Lattner59572292010-11-21 08:06:10 +0000919 MemDepResult DepInfo =
920 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
921 true, CS.getInstruction(),
922 CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +0000923 if (!DepInfo.isClobber())
924 return false;
925
926 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
927 // a memcpy, see if we can byval from the source of the memcpy instead of the
928 // result.
929 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
930 if (MDep == 0 || MDep->isVolatile() ||
931 ByValArg->stripPointerCasts() != MDep->getDest())
932 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000933
Chris Lattner58f9f582010-11-21 00:28:59 +0000934 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +0000935 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Chris Lattner59572292010-11-21 08:06:10 +0000936 if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +0000937 return false;
938
Chris Lattner83791ce2011-05-23 00:03:39 +0000939 // Get the alignment of the byval. If the call doesn't specify the alignment,
940 // then it is some target specific value that we can't know.
Chris Lattner58f9f582010-11-21 00:28:59 +0000941 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
Chris Lattner83791ce2011-05-23 00:03:39 +0000942 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000943
Chris Lattner83791ce2011-05-23 00:03:39 +0000944 // If it is greater than the memcpy, then we check to see if we can force the
945 // source of the memcpy to the alignment we need. If we fail, we bail out.
946 if (MDep->getAlignment() < ByValAlign &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000947 getOrEnforceKnownAlignment(MDep->getSource(),ByValAlign, DL) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +0000948 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000949
Chris Lattner58f9f582010-11-21 00:28:59 +0000950 // Verify that the copied-from memory doesn't change in between the memcpy and
951 // the byval call.
952 // memcpy(a <- b)
953 // *b = 42;
954 // foo(*a)
955 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +0000956 //
957 // NOTE: This is conservative, it will stop on any read from the source loc,
958 // not just the defining memcpy.
959 MemDepResult SourceDep =
960 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
961 false, CS.getInstruction(), MDep->getParent());
962 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
963 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000964
Chris Lattner58f9f582010-11-21 00:28:59 +0000965 Value *TmpCast = MDep->getSource();
966 if (MDep->getSource()->getType() != ByValArg->getType())
967 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
968 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +0000969
Chris Lattner58f9f582010-11-21 00:28:59 +0000970 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
971 << " " << *MDep << "\n"
972 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000973
Chris Lattner58f9f582010-11-21 00:28:59 +0000974 // Otherwise we're good! Update the byval argument.
975 CS.setArgument(ArgNo, TmpCast);
976 ++NumMemCpyInstr;
977 return true;
978}
979
980/// iterateOnFunction - Executes one iteration of MemCpyOpt.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000981bool MemCpyOpt::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +0000982 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000983
Chris Lattnerb5557a72009-09-01 17:09:55 +0000984 // Walk all instruction in the function.
Owen Anderson6a7355c2008-04-21 07:45:10 +0000985 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000986 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Chris Lattnerb5557a72009-09-01 17:09:55 +0000987 // Avoid invalidating the iterator.
988 Instruction *I = BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000989
Chris Lattner58f9f582010-11-21 00:28:59 +0000990 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000991
Owen Anderson6a7355c2008-04-21 07:45:10 +0000992 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +0000993 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000994 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
995 RepeatInstruction = processMemSet(M, BI);
996 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +0000997 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000998 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +0000999 RepeatInstruction = processMemMove(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001000 else if (CallSite CS = (Value*)I) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001001 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001002 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001003 MadeChange |= processByValArgument(CS, i);
1004 }
1005
1006 // Reprocess the instruction if desired.
1007 if (RepeatInstruction) {
Chris Lattner7d6433a2011-01-08 22:19:21 +00001008 if (BI != BB->begin()) --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001009 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001010 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001011 }
1012 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001013
Chris Lattnerb5557a72009-09-01 17:09:55 +00001014 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001015}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001016
1017// MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1018// function.
1019//
1020bool MemCpyOpt::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001021 if (skipOptnoneFunction(F))
1022 return false;
1023
Chris Lattnerb5557a72009-09-01 17:09:55 +00001024 bool MadeChange = false;
Chris Lattner58f9f582010-11-21 00:28:59 +00001025 MD = &getAnalysis<MemoryDependenceAnalysis>();
Rafael Espindola93512512014-02-25 17:30:31 +00001026 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1027 DL = DLP ? &DLP->getDataLayout() : 0;
Chris Lattner23f61a02011-05-01 18:27:11 +00001028 TLI = &getAnalysis<TargetLibraryInfo>();
Nadav Rotem465834c2012-07-24 10:51:42 +00001029
Chris Lattner23f61a02011-05-01 18:27:11 +00001030 // If we don't have at least memset and memcpy, there is little point of doing
1031 // anything here. These are required by a freestanding implementation, so if
1032 // even they are disabled, there is no point in trying hard.
1033 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1034 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001035
Chris Lattnerb5557a72009-09-01 17:09:55 +00001036 while (1) {
1037 if (!iterateOnFunction(F))
1038 break;
1039 MadeChange = true;
1040 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001041
Chris Lattner58f9f582010-11-21 00:28:59 +00001042 MD = 0;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001043 return MadeChange;
1044}