blob: 16078566e94387f9355d879e451a733746d3af70 [file] [log] [blame]
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Owen Andersonef9a6fd2008-04-09 08:23:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs various transformations related to eliminating memcpy
10// calls, or transforming sets of stores into memset's.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
Amaury Sechetbdb261b2016-03-14 22:52:27 +000015#include "llvm/ADT/DenseSet.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000016#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/ADT/STLExtras.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/ADT/iterator_range.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000021#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000022#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/GlobalsModRef.h"
24#include "llvm/Analysis/MemoryDependenceAnalysis.h"
25#include "llvm/Analysis/MemoryLocation.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000027#include "llvm/Transforms/Utils/Local.h"
Chris Lattner9cb10352010-12-26 20:15:01 +000028#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000029#include "llvm/IR/Argument.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000030#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CallSite.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000032#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DataLayout.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000034#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000037#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/GlobalVariable.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/IR/IRBuilder.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000040#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/Intrinsics.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000045#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/Module.h"
47#include "llvm/IR/Operator.h"
Eugene Zelenko306d2992017-10-18 21:46:47 +000048#include "llvm/IR/PassManager.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000049#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/Casting.h"
Owen Andersonef9a6fd2008-04-09 08:23:16 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000055#include "llvm/Support/MathExtras.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000057#include "llvm/Transforms/Scalar.h"
Nick Lewyckyf836c892015-07-21 21:56:26 +000058#include <algorithm>
Eugene Zelenko34c23272017-01-18 00:57:48 +000059#include <cassert>
60#include <cstdint>
Eugene Zelenko306d2992017-10-18 21:46:47 +000061#include <utility>
Eugene Zelenko34c23272017-01-18 00:57:48 +000062
Owen Andersonef9a6fd2008-04-09 08:23:16 +000063using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "memcpyopt"
66
Owen Andersonef9a6fd2008-04-09 08:23:16 +000067STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
68STATISTIC(NumMemSetInfer, "Number of memsets inferred");
Duncan Sands0edc7102009-09-03 13:37:16 +000069STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
Benjamin Kramerea9152e2010-12-24 21:17:12 +000070STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
Owen Andersonef9a6fd2008-04-09 08:23:16 +000071
Eugene Zelenko34c23272017-01-18 00:57:48 +000072namespace {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000073
Sanjay Patela75c41e2015-08-13 22:53:20 +000074/// Represents a range of memset'd bytes with the ByteVal value.
Owen Andersonef9a6fd2008-04-09 08:23:16 +000075/// This allows us to analyze stores like:
76/// store 0 -> P+1
77/// store 0 -> P+0
78/// store 0 -> P+3
79/// store 0 -> P+2
80/// which sometimes happens with stores to arrays of structs etc. When we see
81/// the first store, we make a range [1, 2). The second store extends the range
82/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
83/// two ranges into [0, 3) which is memset'able.
Tim Northover39617352016-05-10 21:49:40 +000084struct MemsetRange {
Owen Andersonef9a6fd2008-04-09 08:23:16 +000085 // Start/End - A semi range that describes the span that this range covers.
Nadav Rotem465834c2012-07-24 10:51:42 +000086 // The range is closed at the start and open at the end: [Start, End).
Owen Andersonef9a6fd2008-04-09 08:23:16 +000087 int64_t Start, End;
88
89 /// StartPtr - The getelementptr instruction that points to the start of the
90 /// range.
Tim Northover39617352016-05-10 21:49:40 +000091 Value *StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +000092
Owen Andersonef9a6fd2008-04-09 08:23:16 +000093 /// Alignment - The known alignment of the first store.
94 unsigned Alignment;
Nadav Rotem465834c2012-07-24 10:51:42 +000095
Owen Andersonef9a6fd2008-04-09 08:23:16 +000096 /// TheStores - The actual stores that make up this range.
Chris Lattner4dc1fd92011-01-08 20:54:51 +000097 SmallVector<Instruction*, 16> TheStores;
Nadav Rotem465834c2012-07-24 10:51:42 +000098
Tim Northover39617352016-05-10 21:49:40 +000099 bool isProfitableToUseMemset(const DataLayout &DL) const;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000100};
Eugene Zelenko34c23272017-01-18 00:57:48 +0000101
102} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000103
Tim Northover39617352016-05-10 21:49:40 +0000104bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
105 // If we found more than 4 stores to merge or 16 bytes, use memset.
Chad Rosier19446a02011-12-05 22:37:00 +0000106 if (TheStores.size() >= 4 || End-Start >= 16) return true;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000107
108 // If there is nothing to merge, don't do anything.
109 if (TheStores.size() < 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000110
Tim Northover39617352016-05-10 21:49:40 +0000111 // If any of the stores are a memset, then it is always good to extend the
112 // memset.
Craig Toppere325e382015-11-20 07:18:48 +0000113 for (Instruction *SI : TheStores)
Tim Northover39617352016-05-10 21:49:40 +0000114 if (!isa<StoreInst>(SI))
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000115 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000116
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000117 // Assume that the code generator is capable of merging pairs of stores
118 // together if it wants to.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000119 if (TheStores.size() == 2) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000120
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000121 // If we have fewer than 8 stores, it can still be worthwhile to do this.
122 // For example, merging 4 i8 stores into an i32 store is useful almost always.
123 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
124 // memset will be split into 2 32-bit stores anyway) and doing so can
125 // pessimize the llvm optimizer.
126 //
127 // Since we don't have perfect knowledge here, make some assumptions: assume
Matt Arsenault899f7d22013-09-16 22:43:16 +0000128 // the maximum GPR width is the same size as the largest legal integer
129 // size. If so, check to see whether we will end up actually reducing the
130 // number of stores used.
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000131 unsigned Bytes = unsigned(End-Start);
Jun Bum Limbe11bdc2016-05-13 18:38:35 +0000132 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
Matt Arsenault899f7d22013-09-16 22:43:16 +0000133 if (MaxIntSize == 0)
134 MaxIntSize = 1;
135 unsigned NumPointerStores = Bytes / MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000136
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000137 // Assume the remaining bytes if any are done a byte at a time.
Craig Toppera5ea5282015-11-21 17:44:42 +0000138 unsigned NumByteStores = Bytes % MaxIntSize;
Nadav Rotem465834c2012-07-24 10:51:42 +0000139
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000140 // If we will reduce the # stores (according to this heuristic), do the
141 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
142 // etc.
143 return TheStores.size() > NumPointerStores+NumByteStores;
Nadav Rotem465834c2012-07-24 10:51:42 +0000144}
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000145
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000146namespace {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000147
Tim Northover39617352016-05-10 21:49:40 +0000148class MemsetRanges {
Eugene Zelenko306d2992017-10-18 21:46:47 +0000149 using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
150
Sanjay Patela75c41e2015-08-13 22:53:20 +0000151 /// A sorted list of the memset ranges.
Tim Northover39617352016-05-10 21:49:40 +0000152 SmallVector<MemsetRange, 8> Ranges;
Eugene Zelenko306d2992017-10-18 21:46:47 +0000153
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000154 const DataLayout &DL;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000155
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000156public:
Tim Northover39617352016-05-10 21:49:40 +0000157 MemsetRanges(const DataLayout &DL) : DL(DL) {}
Nadav Rotem465834c2012-07-24 10:51:42 +0000158
Eugene Zelenko306d2992017-10-18 21:46:47 +0000159 using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
160
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000161 const_iterator begin() const { return Ranges.begin(); }
162 const_iterator end() const { return Ranges.end(); }
163 bool empty() const { return Ranges.empty(); }
Nadav Rotem465834c2012-07-24 10:51:42 +0000164
Chris Lattnerc6381472011-01-08 20:24:01 +0000165 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000166 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
167 addStore(OffsetFromFirst, SI);
168 else
169 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
Chris Lattnerc6381472011-01-08 20:24:01 +0000170 }
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000171
172 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000173 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
Nadav Rotem465834c2012-07-24 10:51:42 +0000174
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000175 addRange(OffsetFromFirst, StoreSize,
Tim Northover39617352016-05-10 21:49:40 +0000176 SI->getPointerOperand(), SI->getAlignment(), SI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000177 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000178
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000179 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
180 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000181 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000182 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000183
Tim Northover39617352016-05-10 21:49:40 +0000184 void addRange(int64_t Start, int64_t Size, Value *Ptr,
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000185 unsigned Alignment, Instruction *Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000186};
Nadav Rotem465834c2012-07-24 10:51:42 +0000187
Eugene Zelenko34c23272017-01-18 00:57:48 +0000188} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000189
Tim Northover39617352016-05-10 21:49:40 +0000190/// Add a new store to the MemsetRanges data structure. This adds a
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000191/// new range for the specified store at the specified offset, merging into
192/// existing ranges as appropriate.
Tim Northover39617352016-05-10 21:49:40 +0000193void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
194 unsigned Alignment, Instruction *Inst) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000195 int64_t End = Start+Size;
Nadav Rotem465834c2012-07-24 10:51:42 +0000196
Fangrui Song78ee2fb2019-06-30 11:19:56 +0000197 range_iterator I = partition_point(
198 Ranges, [=](const MemsetRange &O) { return O.End < Start; });
Nadav Rotem465834c2012-07-24 10:51:42 +0000199
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000200 // We now know that I == E, in which case we didn't find anything to merge
201 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
202 // to insert a new range. Handle this now.
Nick Lewyckyf836c892015-07-21 21:56:26 +0000203 if (I == Ranges.end() || End < I->Start) {
Tim Northover39617352016-05-10 21:49:40 +0000204 MemsetRange &R = *Ranges.insert(I, MemsetRange());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000205 R.Start = Start;
206 R.End = End;
Tim Northover39617352016-05-10 21:49:40 +0000207 R.StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000208 R.Alignment = Alignment;
209 R.TheStores.push_back(Inst);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000210 return;
211 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000212
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000213 // This store overlaps with I, add it.
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000214 I->TheStores.push_back(Inst);
Nadav Rotem465834c2012-07-24 10:51:42 +0000215
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000216 // At this point, we may have an interval that completely contains our store.
217 // If so, just add it to the interval and return.
218 if (I->Start <= Start && I->End >= End)
219 return;
Nadav Rotem465834c2012-07-24 10:51:42 +0000220
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000221 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
222 // but is not entirely contained within the range.
Nadav Rotem465834c2012-07-24 10:51:42 +0000223
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000224 // See if the range extends the start of the range. In this case, it couldn't
225 // possibly cause it to join the prior range, because otherwise we would have
226 // stopped on *it*.
227 if (Start < I->Start) {
228 I->Start = Start;
Tim Northover39617352016-05-10 21:49:40 +0000229 I->StartPtr = Ptr;
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000230 I->Alignment = Alignment;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000231 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000232
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000233 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
234 // is in or right at the end of I), and that End >= I->Start. Extend I out to
235 // End.
236 if (End > I->End) {
237 I->End = End;
Nick Lewyckybfd4ad62009-03-19 05:51:39 +0000238 range_iterator NextI = I;
Nick Lewyckyf836c892015-07-21 21:56:26 +0000239 while (++NextI != Ranges.end() && End >= NextI->Start) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000240 // Merge the range in.
241 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
242 if (NextI->End > I->End)
243 I->End = NextI->End;
244 Ranges.erase(NextI);
245 NextI = I;
246 }
247 }
248}
249
250//===----------------------------------------------------------------------===//
Sean Silva6347df02016-06-14 02:44:55 +0000251// MemCpyOptLegacyPass Pass
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000252//===----------------------------------------------------------------------===//
253
254namespace {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000255
George Burgess IVecb95f52017-03-08 21:28:19 +0000256class MemCpyOptLegacyPass : public FunctionPass {
257 MemCpyOptPass Impl;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000258
George Burgess IVecb95f52017-03-08 21:28:19 +0000259public:
260 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko34c23272017-01-18 00:57:48 +0000261
George Burgess IVecb95f52017-03-08 21:28:19 +0000262 MemCpyOptLegacyPass() : FunctionPass(ID) {
263 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
264 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000265
George Burgess IVecb95f52017-03-08 21:28:19 +0000266 bool runOnFunction(Function &F) override;
Chris Lattnerc6381472011-01-08 20:24:01 +0000267
George Burgess IVecb95f52017-03-08 21:28:19 +0000268private:
269 // This transformation requires dominator postdominator info
270 void getAnalysisUsage(AnalysisUsage &AU) const override {
271 AU.setPreservesCFG();
272 AU.addRequired<AssumptionCacheTracker>();
273 AU.addRequired<DominatorTreeWrapperPass>();
274 AU.addRequired<MemoryDependenceWrapperPass>();
275 AU.addRequired<AAResultsWrapperPass>();
276 AU.addRequired<TargetLibraryInfoWrapperPass>();
277 AU.addPreserved<GlobalsAAWrapperPass>();
278 AU.addPreserved<MemoryDependenceWrapperPass>();
279 }
280};
Nadav Rotem465834c2012-07-24 10:51:42 +0000281
Eugene Zelenko34c23272017-01-18 00:57:48 +0000282} // end anonymous namespace
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000283
Eugene Zelenko306d2992017-10-18 21:46:47 +0000284char MemCpyOptLegacyPass::ID = 0;
285
Sanjay Patela75c41e2015-08-13 22:53:20 +0000286/// The public interface to this file...
Sean Silva6347df02016-06-14 02:44:55 +0000287FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000288
Sean Silva6347df02016-06-14 02:44:55 +0000289INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000290 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000291INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000292INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth61440d22016-03-10 00:55:30 +0000293INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000294INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000295INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
296INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Sean Silva6347df02016-06-14 02:44:55 +0000297INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
Owen Anderson8ac477f2010-10-12 19:48:12 +0000298 false, false)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000299
Sanjay Patela75c41e2015-08-13 22:53:20 +0000300/// When scanning forward over instructions, we look for some other patterns to
301/// fold away. In particular, this looks for stores to neighboring locations of
302/// memory. If it sees enough consecutive ones, it attempts to merge them
303/// together into a memcpy/memset.
Sean Silva6347df02016-06-14 02:44:55 +0000304Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
305 Value *StartPtr,
306 Value *ByteVal) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000307 const DataLayout &DL = StartInst->getModule()->getDataLayout();
Nadav Rotem465834c2012-07-24 10:51:42 +0000308
Chris Lattnerc6381472011-01-08 20:24:01 +0000309 // Okay, so we now have a single store that can be splatable. Scan to find
310 // all subsequent stores of the same value to offset from the same pointer.
311 // Join these together into ranges, so we can decide whether contiguous blocks
312 // are stored.
Tim Northover39617352016-05-10 21:49:40 +0000313 MemsetRanges Ranges(DL);
Nadav Rotem465834c2012-07-24 10:51:42 +0000314
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000315 BasicBlock::iterator BI(StartInst);
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000316 for (++BI; !BI->isTerminator(); ++BI) {
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000317 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
318 // If the instruction is readnone, ignore it, otherwise bail out. We
319 // don't even allow readonly here because we don't want something like:
Chris Lattnerc6381472011-01-08 20:24:01 +0000320 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000321 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
322 break;
323 continue;
324 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000325
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000326 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
327 // If this is a store, see if we can merge it in.
Eli Friedman9a468152011-08-17 22:22:24 +0000328 if (!NextStore->isSimple()) break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000329
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000330 // Check to see if this stored value is of the same byte-splattable value.
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000331 Value *StoredByte = isBytewiseValue(NextStore->getOperand(0), DL);
JF Bastien73d8e4e2018-09-21 05:17:42 +0000332 if (isa<UndefValue>(ByteVal) && StoredByte)
333 ByteVal = StoredByte;
334 if (ByteVal != StoredByte)
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000335 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000336
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000337 // Check to see if this store is to a constant offset from the start ptr.
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +0000338 Optional<int64_t> Offset =
339 isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
340 if (!Offset)
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000341 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000342
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +0000343 Ranges.addStore(*Offset, NextStore);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000344 } else {
345 MemSetInst *MSI = cast<MemSetInst>(BI);
Nadav Rotem465834c2012-07-24 10:51:42 +0000346
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000347 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
348 !isa<ConstantInt>(MSI->getLength()))
349 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000350
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000351 // Check to see if this store is to a constant offset from the start ptr.
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +0000352 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
353 if (!Offset)
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000354 break;
Nadav Rotem465834c2012-07-24 10:51:42 +0000355
Evgeniy Stepanov55ccd162019-08-19 21:08:04 +0000356 Ranges.addMemSet(*Offset, MSI);
Chris Lattner4dc1fd92011-01-08 20:54:51 +0000357 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000358 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000359
Chris Lattnerc6381472011-01-08 20:24:01 +0000360 // If we have no ranges, then we just had a single store with nothing that
361 // could be merged in. This is a very common case of course.
362 if (Ranges.empty())
Craig Topperf40110f2014-04-25 05:29:35 +0000363 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000364
Chris Lattnerc6381472011-01-08 20:24:01 +0000365 // If we had at least one store that could be merged in, add the starting
366 // store as well. We try to avoid this unless there is at least something
367 // interesting as a small compile-time optimization.
368 Ranges.addInst(0, StartInst);
369
370 // If we create any memsets, we put it right before the first instruction that
371 // isn't part of the memset block. This ensure that the memset is dominated
372 // by any addressing instruction needed by the start of the block.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000373 IRBuilder<> Builder(&*BI);
Chris Lattnerc6381472011-01-08 20:24:01 +0000374
375 // Now that we have full information about ranges, loop over the ranges and
376 // emit memset's for anything big enough to be worthwhile.
Craig Topperf40110f2014-04-25 05:29:35 +0000377 Instruction *AMemSet = nullptr;
Tim Northover39617352016-05-10 21:49:40 +0000378 for (const MemsetRange &Range : Ranges) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000379 if (Range.TheStores.size() == 1) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000380
Chris Lattnerc6381472011-01-08 20:24:01 +0000381 // If it is profitable to lower this range to memset, do so now.
Tim Northover39617352016-05-10 21:49:40 +0000382 if (!Range.isProfitableToUseMemset(DL))
Chris Lattnerc6381472011-01-08 20:24:01 +0000383 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000384
Chris Lattnerc6381472011-01-08 20:24:01 +0000385 // Otherwise, we do want to transform this! Create a new memset.
386 // Get the starting pointer of the block.
Tim Northover39617352016-05-10 21:49:40 +0000387 StartPtr = Range.StartPtr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000388
Tim Northover39617352016-05-10 21:49:40 +0000389 // Determine alignment
390 unsigned Alignment = Range.Alignment;
391 if (Alignment == 0) {
392 Type *EltType =
393 cast<PointerType>(StartPtr->getType())->getElementType();
394 Alignment = DL.getABITypeAlignment(EltType);
395 }
396
Reid Kleckner6d310012017-12-28 05:10:33 +0000397 AMemSet =
398 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
Nadav Rotem465834c2012-07-24 10:51:42 +0000399
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000400 LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
401 : Range.TheStores) dbgs()
402 << *SI << '\n';
403 dbgs() << "With: " << *AMemSet << '\n');
Reid Kleckner6d310012017-12-28 05:10:33 +0000404
405 if (!Range.TheStores.empty())
406 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
Devang Patelc7e4fa72011-05-04 21:58:58 +0000407
Chris Lattnerc6381472011-01-08 20:24:01 +0000408 // Zap all the stores.
Craig Toppere325e382015-11-20 07:18:48 +0000409 for (Instruction *SI : Range.TheStores) {
410 MD->removeInstruction(SI);
411 SI->eraseFromParent();
Chris Lattner7d6433a2011-01-08 22:19:21 +0000412 }
Chris Lattnerc6381472011-01-08 20:24:01 +0000413 ++NumMemSetInfer;
414 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000415
Chris Lattnerc6381472011-01-08 20:24:01 +0000416 return AMemSet;
417}
418
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000419static unsigned findStoreAlignment(const DataLayout &DL, const StoreInst *SI) {
Tim Northover39617352016-05-10 21:49:40 +0000420 unsigned StoreAlign = SI->getAlignment();
421 if (!StoreAlign)
422 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000423 return StoreAlign;
424}
425
426static unsigned findLoadAlignment(const DataLayout &DL, const LoadInst *LI) {
Tim Northover39617352016-05-10 21:49:40 +0000427 unsigned LoadAlign = LI->getAlignment();
428 if (!LoadAlign)
429 LoadAlign = DL.getABITypeAlignment(LI->getType());
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000430 return LoadAlign;
431}
Amaury Secheta0c242c2016-01-05 20:17:48 +0000432
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000433static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
434 const LoadInst *LI) {
435 unsigned StoreAlign = findStoreAlignment(DL, SI);
436 unsigned LoadAlign = findLoadAlignment(DL, LI);
437 return MinAlign(StoreAlign, LoadAlign);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000438}
Chris Lattnerc6381472011-01-08 20:24:01 +0000439
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000440// This method try to lift a store instruction before position P.
441// It will lift the store and its argument + that anything that
David Majnemerd99068d2016-05-26 19:24:24 +0000442// may alias with these.
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000443// The method returns true if it was successful.
Bryant Wong7cb74462016-12-27 17:58:12 +0000444static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P,
445 const LoadInst *LI) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000446 // If the store alias this position, early bail out.
447 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000448 if (isModOrRefSet(AA.getModRefInfo(P, StoreLoc)))
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000449 return false;
450
451 // Keep track of the arguments of all instruction we plan to lift
Hiroshi Inouef2096492018-06-14 05:41:49 +0000452 // so we can make sure to lift them as well if appropriate.
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000453 DenseSet<Instruction*> Args;
454 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
455 if (Ptr->getParent() == SI->getParent())
456 Args.insert(Ptr);
457
458 // Instruction to lift before P.
459 SmallVector<Instruction*, 8> ToLift;
460
461 // Memory locations of lifted instructions.
Bryant Wong7cb74462016-12-27 17:58:12 +0000462 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000463
Chandler Carruth363ac682019-01-07 05:42:51 +0000464 // Lifted calls.
465 SmallVector<const CallBase *, 8> Calls;
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000466
Bryant Wong7cb74462016-12-27 17:58:12 +0000467 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
468
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000469 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
470 auto *C = &*I;
471
Alina Sbirlea63d22502017-12-05 20:12:23 +0000472 bool MayAlias = isModOrRefSet(AA.getModRefInfo(C, None));
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000473
474 bool NeedLift = false;
475 if (Args.erase(C))
476 NeedLift = true;
477 else if (MayAlias) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000478 NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
Alina Sbirlea63d22502017-12-05 20:12:23 +0000479 return isModOrRefSet(AA.getModRefInfo(C, ML));
David Majnemer0a16c222016-08-11 21:15:00 +0000480 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000481
482 if (!NeedLift)
Chandler Carruth363ac682019-01-07 05:42:51 +0000483 NeedLift = llvm::any_of(Calls, [C, &AA](const CallBase *Call) {
484 return isModOrRefSet(AA.getModRefInfo(C, Call));
485 });
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000486 }
487
488 if (!NeedLift)
489 continue;
490
491 if (MayAlias) {
Bryant Wong7cb74462016-12-27 17:58:12 +0000492 // Since LI is implicitly moved downwards past the lifted instructions,
493 // none of them may modify its source.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000494 if (isModSet(AA.getModRefInfo(C, LoadLoc)))
Bryant Wong7cb74462016-12-27 17:58:12 +0000495 return false;
Chandler Carruth363ac682019-01-07 05:42:51 +0000496 else if (const auto *Call = dyn_cast<CallBase>(C)) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000497 // If we can't lift this before P, it's game over.
Chandler Carruth363ac682019-01-07 05:42:51 +0000498 if (isModOrRefSet(AA.getModRefInfo(P, Call)))
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000499 return false;
500
Chandler Carruth363ac682019-01-07 05:42:51 +0000501 Calls.push_back(Call);
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000502 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
503 // If we can't lift this before P, it's game over.
504 auto ML = MemoryLocation::get(C);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000505 if (isModOrRefSet(AA.getModRefInfo(P, ML)))
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000506 return false;
507
508 MemLocs.push_back(ML);
509 } else
510 // We don't know how to lift this instruction.
511 return false;
512 }
513
514 ToLift.push_back(C);
515 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
516 if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
517 if (A->getParent() == SI->getParent())
518 Args.insert(A);
519 }
520
521 // We made it, we need to lift
Eugene Zelenko34c23272017-01-18 00:57:48 +0000522 for (auto *I : llvm::reverse(ToLift)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000523 LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000524 I->moveBefore(P);
525 }
526
527 return true;
528}
529
Sean Silva6347df02016-06-14 02:44:55 +0000530bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
Eli Friedman9a468152011-08-17 22:22:24 +0000531 if (!SI->isSimple()) return false;
Andrea Di Biagio99493df2015-10-09 10:53:41 +0000532
533 // Avoid merging nontemporal stores since the resulting
534 // memcpy/memset would not be able to preserve the nontemporal hint.
535 // In theory we could teach how to propagate the !nontemporal metadata to
536 // memset calls. However, that change would force the backend to
537 // conservatively expand !nontemporal memset calls back to sequences of
538 // store instructions (effectively undoing the merging).
539 if (SI->getMetadata(LLVMContext::MD_nontemporal))
540 return false;
541
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000542 const DataLayout &DL = SI->getModule()->getDataLayout();
Owen Anderson18e4fed2010-10-15 22:52:12 +0000543
Amaury Secheta0c242c2016-01-05 20:17:48 +0000544 // Load to store forwarding can be interpreted as memcpy.
Owen Anderson18e4fed2010-10-15 22:52:12 +0000545 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
Eli Friedman9a468152011-08-17 22:22:24 +0000546 if (LI->isSimple() && LI->hasOneUse() &&
Eli Friedmane8bbc102011-06-15 01:25:56 +0000547 LI->getParent() == SI->getParent()) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000548
549 auto *T = LI->getType();
550 if (T->isAggregateType()) {
Sean Silva6347df02016-06-14 02:44:55 +0000551 AliasAnalysis &AA = LookupAliasAnalysis();
Amaury Secheta0c242c2016-01-05 20:17:48 +0000552 MemoryLocation LoadLoc = MemoryLocation::get(LI);
553
554 // We use alias analysis to check if an instruction may store to
555 // the memory we load from in between the load and the store. If
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000556 // such an instruction is found, we try to promote there instead
557 // of at the store position.
558 Instruction *P = SI;
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000559 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
Alina Sbirlea63d22502017-12-05 20:12:23 +0000560 if (isModSet(AA.getModRefInfo(&I, LoadLoc))) {
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000561 P = &I;
562 break;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000563 }
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000564 }
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000565
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000566 // We found an instruction that may write to the loaded memory.
567 // We can try to promote at this position instead of the store
568 // position if nothing alias the store memory after this and the store
569 // destination is not in the range.
570 if (P && P != SI) {
Bryant Wong7cb74462016-12-27 17:58:12 +0000571 if (!moveUp(AA, SI, P, LI))
Amaury Sechetbdb261b2016-03-14 22:52:27 +0000572 P = nullptr;
Amaury Secheta0c242c2016-01-05 20:17:48 +0000573 }
574
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000575 // If a valid insertion position is found, then we can promote
576 // the load/store pair to a memcpy.
577 if (P) {
Amaury Secheta0c242c2016-01-05 20:17:48 +0000578 // If we load from memory that may alias the memory we store to,
579 // memmove must be used to preserve semantic. If not, memcpy can
580 // be used.
581 bool UseMemMove = false;
582 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
583 UseMemMove = true;
584
Amaury Secheta0c242c2016-01-05 20:17:48 +0000585 uint64_t Size = DL.getTypeStoreSize(T);
586
Amaury Sechetd3b2c0f2016-01-06 09:30:39 +0000587 IRBuilder<> Builder(P);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000588 Instruction *M;
589 if (UseMemMove)
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000590 M = Builder.CreateMemMove(
591 SI->getPointerOperand(), findStoreAlignment(DL, SI),
Xin Tong47beee22019-01-04 02:13:22 +0000592 LI->getPointerOperand(), findLoadAlignment(DL, LI), Size);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000593 else
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000594 M = Builder.CreateMemCpy(
595 SI->getPointerOperand(), findStoreAlignment(DL, SI),
Xin Tong47beee22019-01-04 02:13:22 +0000596 LI->getPointerOperand(), findLoadAlignment(DL, LI), Size);
Amaury Secheta0c242c2016-01-05 20:17:48 +0000597
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000598 LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
599 << *M << "\n");
Amaury Secheta0c242c2016-01-05 20:17:48 +0000600
601 MD->removeInstruction(SI);
602 SI->eraseFromParent();
603 MD->removeInstruction(LI);
604 LI->eraseFromParent();
605 ++NumMemCpyInstr;
606
607 // Make sure we do not invalidate the iterator.
608 BBI = M->getIterator();
609 return true;
610 }
611 }
612
613 // Detect cases where we're performing call slot forwarding, but
614 // happen to be using a load-store pair to implement it, rather than
615 // a memcpy.
Eli Friedman5da0ff42011-06-02 21:24:42 +0000616 MemDepResult ldep = MD->getDependency(LI);
Craig Topperf40110f2014-04-25 05:29:35 +0000617 CallInst *C = nullptr;
Eli Friedman5da0ff42011-06-02 21:24:42 +0000618 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
619 C = dyn_cast<CallInst>(ldep.getInst());
620
621 if (C) {
622 // Check that nothing touches the dest of the "copy" between
623 // the call and the store.
David Majnemerd99068d2016-05-26 19:24:24 +0000624 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
625 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
Sean Silva6347df02016-06-14 02:44:55 +0000626 AliasAnalysis &AA = LookupAliasAnalysis();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000627 MemoryLocation StoreLoc = MemoryLocation::get(SI);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000628 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
629 I != E; --I) {
Alina Sbirlea63d22502017-12-05 20:12:23 +0000630 if (isModOrRefSet(AA.getModRefInfo(&*I, StoreLoc))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000631 C = nullptr;
Eli Friedmane8bbc102011-06-15 01:25:56 +0000632 break;
633 }
David Majnemerd99068d2016-05-26 19:24:24 +0000634 // The store to dest may never happen if an exception can be thrown
635 // between the load and the store.
636 if (I->mayThrow() && !CpyDestIsLocal) {
637 C = nullptr;
638 break;
639 }
Eli Friedman5da0ff42011-06-02 21:24:42 +0000640 }
641 }
642
Owen Anderson18e4fed2010-10-15 22:52:12 +0000643 if (C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644 bool changed = performCallSlotOptzn(
645 LI, SI->getPointerOperand()->stripPointerCasts(),
646 LI->getPointerOperand()->stripPointerCasts(),
647 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
Amaury Secheta0c242c2016-01-05 20:17:48 +0000648 findCommonAlignment(DL, SI, LI), C);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000649 if (changed) {
Chris Lattner58f9f582010-11-21 00:28:59 +0000650 MD->removeInstruction(SI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000651 SI->eraseFromParent();
Chris Lattnercaf5c0d2011-01-09 19:26:10 +0000652 MD->removeInstruction(LI);
Owen Anderson18e4fed2010-10-15 22:52:12 +0000653 LI->eraseFromParent();
654 ++NumMemCpyInstr;
655 return true;
656 }
657 }
658 }
659 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000660
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000661 // There are two cases that are interesting for this code to handle: memcpy
662 // and memset. Right now we only handle memset.
Nadav Rotem465834c2012-07-24 10:51:42 +0000663
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000664 // Ensure that the value being stored is something that can be memset'able a
665 // byte at a time like "0" or "-1" or any width, as well as things like
666 // 0xA0A0A0A0 and 0.0.
Amaury Sechet3235c082016-01-06 19:47:24 +0000667 auto *V = SI->getOperand(0);
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000668 if (Value *ByteVal = isBytewiseValue(V, DL)) {
Chris Lattnerc6381472011-01-08 20:24:01 +0000669 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
670 ByteVal)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000671 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerc6381472011-01-08 20:24:01 +0000672 return true;
Mon P Wangc576ee92010-04-04 03:10:48 +0000673 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000674
Amaury Sechet3235c082016-01-06 19:47:24 +0000675 // If we have an aggregate, we try to promote it to memset regardless
676 // of opportunity for merging as it can expose optimization opportunities
677 // in subsequent passes.
678 auto *T = V->getType();
679 if (T->isAggregateType()) {
680 uint64_t Size = DL.getTypeStoreSize(T);
681 unsigned Align = SI->getAlignment();
682 if (!Align)
683 Align = DL.getABITypeAlignment(T);
684 IRBuilder<> Builder(SI);
Xin Tong47beee22019-01-04 02:13:22 +0000685 auto *M =
686 Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size, Align);
Amaury Sechet3235c082016-01-06 19:47:24 +0000687
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000688 LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
Amaury Sechet3235c082016-01-06 19:47:24 +0000689
690 MD->removeInstruction(SI);
691 SI->eraseFromParent();
692 NumMemSetInfer++;
693
694 // Make sure we do not invalidate the iterator.
695 BBI = M->getIterator();
696 return true;
697 }
698 }
699
Chris Lattnerc6381472011-01-08 20:24:01 +0000700 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000701}
702
Sean Silva6347df02016-06-14 02:44:55 +0000703bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000704 // See if there is another memset or store neighboring this memset which
705 // allows us to widen out the memset to do a single larger store.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000706 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
707 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
708 MSI->getValue())) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000709 BBI = I->getIterator(); // Don't invalidate iterator.
Chris Lattnerff6ed2a2011-01-08 22:11:56 +0000710 return true;
711 }
Chris Lattner9a1d63b2011-01-08 21:19:19 +0000712 return false;
713}
714
Sanjay Patela75c41e2015-08-13 22:53:20 +0000715/// Takes a memcpy and a call that it depends on,
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000716/// and checks for the possibility of a call slot optimization by having
717/// the call write its result directly into the destination of the memcpy.
Sean Silva6347df02016-06-14 02:44:55 +0000718bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
719 Value *cpySrc, uint64_t cpyLen,
720 unsigned cpyAlign, CallInst *C) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000721 // The general transformation to keep in mind is
722 //
723 // call @func(..., src, ...)
724 // memcpy(dest, src, ...)
725 //
726 // ->
727 //
728 // memcpy(dest, src, ...)
729 // call @func(..., dest, ...)
730 //
731 // Since moving the memcpy is technically awkward, we additionally check that
732 // src only holds uninitialized values at the moment of the call, meaning that
733 // the memcpy can be discarded rather than moved.
734
Tim Shen7aa0ad62016-06-08 19:42:32 +0000735 // Lifetime marks shouldn't be operated on.
736 if (Function *F = C->getCalledFunction())
737 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
738 return false;
739
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000740 // Deliberately get the source and destination with bitcasts stripped away,
741 // because we'll need to do type comparisons based on the underlying type.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000742 CallSite CS(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000743
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000744 // Require that src be an alloca. This simplifies the reasoning considerably.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000745 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000746 if (!srcAlloca)
747 return false;
748
Chris Lattnerb5557a72009-09-01 17:09:55 +0000749 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000750 if (!srcArraySize)
751 return false;
752
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000753 const DataLayout &DL = cpy->getModule()->getDataLayout();
754 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
755 srcArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000756
Owen Anderson18e4fed2010-10-15 22:52:12 +0000757 if (cpyLen < srcSize)
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000758 return false;
759
760 // Check that accessing the first srcSize bytes of dest will not cause a
761 // trap. Otherwise the transform is invalid since it might cause a trap
762 // to occur earlier than it otherwise would.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000763 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000764 // The destination is an alloca. Check it is larger than srcSize.
Chris Lattnerb5557a72009-09-01 17:09:55 +0000765 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000766 if (!destArraySize)
767 return false;
768
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000769 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
770 destArraySize->getZExtValue();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000771
772 if (destSize < srcSize)
773 return false;
Chris Lattnerb5557a72009-09-01 17:09:55 +0000774 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
David Majnemerd99068d2016-05-26 19:24:24 +0000775 // The store to dest may never happen if the call can throw.
776 if (C->mayThrow())
777 return false;
778
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000779 if (A->getDereferenceableBytes() < srcSize) {
780 // If the destination is an sret parameter then only accesses that are
781 // outside of the returned struct type can trap.
782 if (!A->hasStructRetAttr())
783 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000784
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000785 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
786 if (!StructTy->isSized()) {
787 // The call may never return and hence the copy-instruction may never
788 // be executed, and therefore it's not safe to say "the destination
789 // has at least <cpyLen> bytes, as implied by the copy-instruction",
790 return false;
791 }
792
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000793 uint64_t destSize = DL.getTypeAllocSize(StructTy);
Bjorn Steinbrinkd20816f2014-10-16 19:43:08 +0000794 if (destSize < srcSize)
795 return false;
Shuxin Yang140d5922013-06-08 04:56:05 +0000796 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000797 } else {
798 return false;
799 }
800
Duncan Sands933db772012-10-05 07:29:46 +0000801 // Check that dest points to memory that is at least as aligned as src.
802 unsigned srcAlign = srcAlloca->getAlignment();
803 if (!srcAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000804 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
Duncan Sands933db772012-10-05 07:29:46 +0000805 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
806 // If dest is not aligned enough and we can't increase its alignment then
807 // bail out.
808 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
809 return false;
810
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000811 // Check that src is not accessed except via the call and the memcpy. This
812 // guarantees that it holds only undefined values when passed in (so the final
813 // memcpy can be dropped), that it is not read or written between the call and
814 // the memcpy, and that writing beyond the end of it is undefined.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000815 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
816 srcAlloca->user_end());
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000817 while (!srcUseList.empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000818 User *U = srcUseList.pop_back_val();
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000819
Chandler Carruthcdf47882014-03-09 03:16:01 +0000820 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
821 for (User *UU : U->users())
822 srcUseList.push_back(UU);
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000823 continue;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000824 }
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000825 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
826 if (!G->hasAllZeroIndices())
827 return false;
828
829 for (User *UU : U->users())
830 srcUseList.push_back(UU);
831 continue;
832 }
833 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
Vedant Kumarb264d692018-12-21 21:49:40 +0000834 if (IT->isLifetimeStartOrEnd())
Chandler Carruth18cee1d2014-09-01 10:09:18 +0000835 continue;
836
837 if (U != C && U != cpy)
838 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000839 }
840
Nick Lewycky703e4882014-07-14 18:52:02 +0000841 // Check that src isn't captured by the called function since the
842 // transformation can cause aliasing issues in that case.
843 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
844 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
845 return false;
846
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000847 // Since we're changing the parameter to the callsite, we need to make sure
848 // that what would be the new parameter dominates the callsite.
Sean Silva6347df02016-06-14 02:44:55 +0000849 DominatorTree &DT = LookupDomTree();
Chris Lattnerb5557a72009-09-01 17:09:55 +0000850 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000851 if (!DT.dominates(cpyDestInst, C))
852 return false;
853
854 // In addition to knowing that the call does not access src in some
855 // unexpected manner, for example via a global, which we deduce from
856 // the use analysis, we also need to know that it does not sneakily
857 // access dest. We rely on AA to figure this out for us.
Sean Silva6347df02016-06-14 02:44:55 +0000858 AliasAnalysis &AA = LookupAliasAnalysis();
George Burgess IV5e4a03a2018-12-23 06:40:39 +0000859 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
Chad Rosiera968caf2012-05-14 20:35:04 +0000860 // If necessary, perform additional analysis.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000861 if (isModOrRefSet(MR))
George Burgess IV5e4a03a2018-12-23 06:40:39 +0000862 MR = AA.callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), &DT);
Alina Sbirlea63d22502017-12-05 20:12:23 +0000863 if (isModOrRefSet(MR))
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000864 return false;
865
Fiona Glasera9bd5722017-03-14 22:37:38 +0000866 // We can't create address space casts here because we don't know if they're
867 // safe for the target.
868 if (cpySrc->getType()->getPointerAddressSpace() !=
869 cpyDest->getType()->getPointerAddressSpace())
870 return false;
871 for (unsigned i = 0; i < CS.arg_size(); ++i)
872 if (CS.getArgument(i)->stripPointerCasts() == cpySrc &&
873 cpySrc->getType()->getPointerAddressSpace() !=
874 CS.getArgument(i)->getType()->getPointerAddressSpace())
875 return false;
876
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000877 // All the checks have passed, so do the transformation.
Owen Andersond071a872008-06-01 21:52:16 +0000878 bool changedArgument = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000879 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson38099c12008-06-01 22:26:26 +0000880 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
Duncan Sandsa6d20012012-10-04 13:53:21 +0000881 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
882 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
883 cpyDest->getName(), C);
Owen Andersond071a872008-06-01 21:52:16 +0000884 changedArgument = true;
Duncan Sandsa6d20012012-10-04 13:53:21 +0000885 if (CS.getArgument(i)->getType() == Dest->getType())
886 CS.setArgument(i, Dest);
Chris Lattnerb5557a72009-09-01 17:09:55 +0000887 else
Duncan Sandsa6d20012012-10-04 13:53:21 +0000888 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
889 CS.getArgument(i)->getType(), Dest->getName(), C));
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000890 }
891
Owen Andersond071a872008-06-01 21:52:16 +0000892 if (!changedArgument)
893 return false;
894
Duncan Sandsc6ada692012-10-04 10:54:40 +0000895 // If the destination wasn't sufficiently aligned then increase its alignment.
896 if (!isDestSufficientlyAligned) {
897 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
898 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
899 }
900
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000901 // Drop any cached information about the call, because we may have changed
902 // its dependence information by changing its parameter.
Chris Lattner58f9f582010-11-21 00:28:59 +0000903 MD->removeInstruction(C);
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000904
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000905 // Update AA metadata
906 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
907 // handled here, but combineMetadata doesn't support them yet
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +0000908 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
909 LLVMContext::MD_noalias,
Michael Kruse978ba612018-12-20 04:58:07 +0000910 LLVMContext::MD_invariant_group,
911 LLVMContext::MD_access_group};
Florian Hahn406f1ff2018-08-24 11:40:04 +0000912 combineMetadata(C, cpy, KnownIDs, true);
Bjorn Steinbrink71bf3b82015-02-07 17:54:36 +0000913
Chris Lattner58f9f582010-11-21 00:28:59 +0000914 // Remove the memcpy.
915 MD->removeInstruction(cpy);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000916 ++NumMemCpyInstr;
Owen Andersonef9a6fd2008-04-09 08:23:16 +0000917
918 return true;
919}
920
Sanjay Patela75c41e2015-08-13 22:53:20 +0000921/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
922/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
Sean Silva6347df02016-06-14 02:44:55 +0000923bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
924 MemCpyInst *MDep) {
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000925 // We can only transforms memcpy's where the dest of one is the source of the
926 // other.
Chris Lattner58f9f582010-11-21 00:28:59 +0000927 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000928 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000929
Chris Lattnerfd51c522010-12-09 07:39:50 +0000930 // If dep instruction is reading from our current input, then it is a noop
931 // transfer and substituting the input won't change this instruction. Just
932 // ignore the input and let someone else zap MDep. This handles cases like:
933 // memcpy(a <- a)
934 // memcpy(b <- a)
935 if (M->getSource() == MDep->getSource())
936 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000937
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000938 // Second, the length of the memcpy's must be the same, or the preceding one
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000939 // must be larger than the following one.
Dan Gohman19e30d52011-01-21 22:07:57 +0000940 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
941 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
942 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
943 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000944
Sean Silva6347df02016-06-14 02:44:55 +0000945 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner59572292010-11-21 08:06:10 +0000946
947 // Verify that the copied-from memory doesn't change in between the two
948 // transfers. For example, in:
949 // memcpy(a <- b)
950 // *b = 42;
951 // memcpy(c <- a)
952 // It would be invalid to transform the second memcpy into memcpy(c <- b).
953 //
954 // TODO: If the code between M and MDep is transparent to the destination "c",
955 // then we could still perform the xform by moving M up to the first memcpy.
956 //
957 // NOTE: This is conservative, it will stop on any read from the source loc,
958 // not just the defining memcpy.
Reid Kleckner6d310012017-12-28 05:10:33 +0000959 MemDepResult SourceDep =
960 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
961 M->getIterator(), M->getParent());
Chris Lattner59572292010-11-21 08:06:10 +0000962 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
963 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000964
Chris Lattner731caac2010-11-18 08:00:57 +0000965 // If the dest of the second might alias the source of the first, then the
966 // source and dest might overlap. We still want to eliminate the intermediate
967 // value, but we have to generate a memmove instead of memcpy.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000968 bool UseMemMove = false;
Chandler Carruth70c61c12015-06-04 02:03:15 +0000969 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
970 MemoryLocation::getForSource(MDep)))
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000971 UseMemMove = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000972
Chris Lattner58f9f582010-11-21 00:28:59 +0000973 // If all checks passed, then we can transform M.
Reid Klecknerb894ecf2018-12-21 01:41:20 +0000974 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
975 << *MDep << '\n' << *M << '\n');
Nadav Rotem465834c2012-07-24 10:51:42 +0000976
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000977 // TODO: Is this worth it if we're creating a less aligned memcpy? For
978 // example we could be moving from movaps -> movq on x86.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000979 IRBuilder<> Builder(M);
980 if (UseMemMove)
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000981 Builder.CreateMemMove(M->getRawDest(), M->getDestAlignment(),
982 MDep->getRawSource(), MDep->getSourceAlignment(),
983 M->getLength(), M->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000984 else
Daniel Neilson6f1eb582018-03-21 14:14:55 +0000985 Builder.CreateMemCpy(M->getRawDest(), M->getDestAlignment(),
986 MDep->getRawSource(), MDep->getSourceAlignment(),
987 M->getLength(), M->isVolatile());
Chris Lattner1385dff2010-11-18 08:07:09 +0000988
Chris Lattner59572292010-11-21 08:06:10 +0000989 // Remove the instruction we're replacing.
Chris Lattner58f9f582010-11-21 00:28:59 +0000990 MD->removeInstruction(M);
Chris Lattner1385dff2010-11-18 08:07:09 +0000991 M->eraseFromParent();
992 ++NumMemCpyInstr;
993 return true;
Chris Lattner7e9b2ea2010-11-18 07:02:37 +0000994}
995
Ahmed Bougacha83f78a42015-04-17 22:20:57 +0000996/// We've found that the (upward scanning) memory dependence of \p MemCpy is
997/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
998/// weren't copied over by \p MemCpy.
999///
1000/// In other words, transform:
1001/// \code
1002/// memset(dst, c, dst_size);
1003/// memcpy(dst, src, src_size);
1004/// \endcode
1005/// into:
1006/// \code
1007/// memcpy(dst, src, src_size);
1008/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1009/// \endcode
Sean Silva6347df02016-06-14 02:44:55 +00001010bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1011 MemSetInst *MemSet) {
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001012 // We can only transform memset/memcpy with the same destination.
1013 if (MemSet->getDest() != MemCpy->getDest())
1014 return false;
1015
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001016 // Check that there are no other dependencies on the memset destination.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001017 MemDepResult DstDepInfo =
1018 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1019 MemCpy->getIterator(), MemCpy->getParent());
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001020 if (DstDepInfo.getInst() != MemSet)
1021 return false;
1022
Ahmed Bougacha9692e302015-04-21 21:28:33 +00001023 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1024 Value *Dest = MemCpy->getRawDest();
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001025 Value *DestSize = MemSet->getLength();
1026 Value *SrcSize = MemCpy->getLength();
1027
1028 // By default, create an unaligned memset.
1029 unsigned Align = 1;
1030 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1031 // of the sum.
1032 const unsigned DestAlign =
Daniel Neilson6f1eb582018-03-21 14:14:55 +00001033 std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001034 if (DestAlign > 1)
1035 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1036 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1037
Ahmed Bougacha97876fa2015-05-21 01:43:39 +00001038 IRBuilder<> Builder(MemCpy);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001039
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001040 // If the sizes have different types, zext the smaller one.
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001041 if (DestSize->getType() != SrcSize->getType()) {
Ahmed Bougacha05b72c12015-04-18 23:06:04 +00001042 if (DestSize->getType()->getIntegerBitWidth() >
1043 SrcSize->getType()->getIntegerBitWidth())
1044 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1045 else
1046 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
Ahmed Bougacha7216ccc2015-04-18 17:57:41 +00001047 }
1048
Benjamin Kramer1697d392016-11-07 17:47:28 +00001049 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1050 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1051 Value *MemsetLen = Builder.CreateSelect(
1052 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
James Y Knight77160752019-02-01 20:44:47 +00001053 Builder.CreateMemSet(
1054 Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest,
1055 SrcSize),
1056 MemSet->getOperand(1), MemsetLen, Align);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001057
1058 MD->removeInstruction(MemSet);
1059 MemSet->eraseFromParent();
1060 return true;
1061}
Chris Lattner7e9b2ea2010-11-18 07:02:37 +00001062
Nikita Popovdc73a6e2018-12-13 20:04:27 +00001063/// Determine whether the instruction has undefined content for the given Size,
1064/// either because it was freshly alloca'd or started its lifetime.
1065static bool hasUndefContents(Instruction *I, ConstantInt *Size) {
1066 if (isa<AllocaInst>(I))
1067 return true;
1068
1069 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1070 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1071 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1072 if (LTSize->getZExtValue() >= Size->getZExtValue())
1073 return true;
1074
1075 return false;
1076}
1077
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001078/// Transform memcpy to memset when its source was just memset.
1079/// In other words, turn:
1080/// \code
1081/// memset(dst1, c, dst1_size);
1082/// memcpy(dst2, dst1, dst2_size);
1083/// \endcode
1084/// into:
1085/// \code
1086/// memset(dst1, c, dst1_size);
1087/// memset(dst2, c, dst2_size);
1088/// \endcode
1089/// When dst2_size <= dst1_size.
1090///
1091/// The \p MemCpy must have a Constant length.
Sean Silva6347df02016-06-14 02:44:55 +00001092bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1093 MemSetInst *MemSet) {
Tim Shena3dbead2016-08-25 19:27:26 +00001094 AliasAnalysis &AA = LookupAliasAnalysis();
1095
Tim Shen3ad8b432016-08-25 21:03:46 +00001096 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1097 // memcpying from the same address. Otherwise it is hard to reason about.
Tim Shena3dbead2016-08-25 19:27:26 +00001098 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001099 return false;
1100
Nikita Popovdc73a6e2018-12-13 20:04:27 +00001101 // A known memset size is required.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001102 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
Nikita Popovdc73a6e2018-12-13 20:04:27 +00001103 if (!MemSetSize)
1104 return false;
1105
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001106 // Make sure the memcpy doesn't read any more than what the memset wrote.
1107 // Don't worry about sizes larger than i64.
Nikita Popovdc73a6e2018-12-13 20:04:27 +00001108 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1109 if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) {
1110 // If the memcpy is larger than the memset, but the memory was undef prior
1111 // to the memset, we can just ignore the tail. Technically we're only
1112 // interested in the bytes from MemSetSize..CopySize here, but as we can't
1113 // easily represent this location, we use the full 0..CopySize range.
1114 MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1115 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1116 MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1117 if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1118 CopySize = MemSetSize;
1119 else
1120 return false;
1121 }
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001122
Ahmed Bougacha0541c672015-05-21 00:08:35 +00001123 IRBuilder<> Builder(MemCpy);
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001124 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
Daniel Neilson6f1eb582018-03-21 14:14:55 +00001125 CopySize, MemCpy->getDestAlignment());
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001126 return true;
1127}
1128
Sanjay Patela75c41e2015-08-13 22:53:20 +00001129/// Perform simplification of memcpy's. If we have memcpy A
Gabor Greif62f0aac2010-07-28 22:50:26 +00001130/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1131/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1132/// circumstances). This allows later passes to remove the first memcpy
1133/// altogether.
Sean Silva6347df02016-06-14 02:44:55 +00001134bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
Nick Lewycky00703e72014-02-04 00:18:54 +00001135 // We can only optimize non-volatile memcpy's.
1136 if (M->isVolatile()) return false;
Owen Anderson18e4fed2010-10-15 22:52:12 +00001137
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001138 // If the source and destination of the memcpy are the same, then zap it.
1139 if (M->getSource() == M->getDest()) {
1140 MD->removeInstruction(M);
1141 M->eraseFromParent();
1142 return false;
1143 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001144
1145 // If copying from a constant, try to turn the memcpy into a memset.
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
Benjamin Kramer30342fb2010-12-26 15:23:45 +00001147 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00001148 if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1149 M->getModule()->getDataLayout())) {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00001150 IRBuilder<> Builder(M);
Nick Lewycky00703e72014-02-04 00:18:54 +00001151 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
Daniel Neilson6f1eb582018-03-21 14:14:55 +00001152 M->getDestAlignment(), false);
Benjamin Kramerb90b2f02010-12-24 22:23:59 +00001153 MD->removeInstruction(M);
1154 M->eraseFromParent();
1155 ++NumCpyToSet;
1156 return true;
1157 }
Benjamin Kramerea9152e2010-12-24 21:17:12 +00001158
Ahmed Bougachab6169662015-05-11 23:09:46 +00001159 MemDepResult DepInfo = MD->getDependency(M);
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001160
1161 // Try to turn a partially redundant memset + memcpy into
1162 // memcpy + smaller memset. We don't need the memcpy size for this.
Ahmed Bougachab6169662015-05-11 23:09:46 +00001163 if (DepInfo.isClobber())
1164 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
Ahmed Bougacha83f78a42015-04-17 22:20:57 +00001165 if (processMemSetMemCpyDependence(M, MDep))
1166 return true;
1167
Nick Lewycky00703e72014-02-04 00:18:54 +00001168 // The optimizations after this point require the memcpy size.
1169 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001170 if (!CopySize) return false;
Nick Lewycky00703e72014-02-04 00:18:54 +00001171
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001172 // There are four possible optimizations we can do for memcpy:
Chris Lattnerb5557a72009-09-01 17:09:55 +00001173 // a) memcpy-memcpy xform which exposes redundance for DSE.
1174 // b) call-memcpy xform for return slot optimization.
Nick Lewycky77d5fb42014-03-26 23:45:15 +00001175 // c) memcpy from freshly alloca'd space or space that has just started its
1176 // lifetime copies undefined data, and we can therefore eliminate the
1177 // memcpy in favor of the data that was already at the destination.
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001178 // d) memcpy from a just-memset'd source can be turned into memset.
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001179 if (DepInfo.isClobber()) {
1180 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
Daniel Neilson6f1eb582018-03-21 14:14:55 +00001181 // FIXME: Can we pass in either of dest/src alignment here instead
1182 // of conservatively taking the minimum?
1183 unsigned Align = MinAlign(M->getDestAlignment(), M->getSourceAlignment());
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001184 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
Daniel Neilson6f1eb582018-03-21 14:14:55 +00001185 CopySize->getZExtValue(), Align,
Duncan Sandsc6ada692012-10-04 10:54:40 +00001186 C)) {
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001187 MD->removeInstruction(M);
1188 M->eraseFromParent();
1189 return true;
1190 }
Chris Lattnerbc4457e2010-12-09 07:45:45 +00001191 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001192 }
Ahmed Charles32e983e2012-02-13 06:30:56 +00001193
Chandler Carruthac80dc72015-06-17 07:18:54 +00001194 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001195 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1196 SrcLoc, true, M->getIterator(), M->getParent());
Ahmed Bougachab6169662015-05-11 23:09:46 +00001197
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001198 if (SrcDepInfo.isClobber()) {
1199 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
Ahmed Bougacha15a31f62015-05-16 01:23:47 +00001200 return processMemCpyMemCpyDependence(M, MDep);
Nick Lewycky99384942014-02-06 06:29:19 +00001201 } else if (SrcDepInfo.isDef()) {
Nikita Popovdc73a6e2018-12-13 20:04:27 +00001202 if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) {
Nick Lewycky99384942014-02-06 06:29:19 +00001203 MD->removeInstruction(M);
1204 M->eraseFromParent();
1205 ++NumMemCpyInstr;
1206 return true;
1207 }
Nick Lewycky0a7e9cc2011-10-16 20:13:32 +00001208 }
1209
Ahmed Bougachaf8fa3b82015-05-16 01:32:26 +00001210 if (SrcDepInfo.isClobber())
1211 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1212 if (performMemCpyToMemSetOptzn(M, MDep)) {
1213 MD->removeInstruction(M);
1214 M->eraseFromParent();
1215 ++NumCpyToSet;
1216 return true;
1217 }
1218
Owen Andersonad5367f2008-04-29 21:51:00 +00001219 return false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001220}
1221
Sanjay Patela75c41e2015-08-13 22:53:20 +00001222/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1223/// not to alias.
Sean Silva6347df02016-06-14 02:44:55 +00001224bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1225 AliasAnalysis &AA = LookupAliasAnalysis();
Chris Lattner1145e332009-09-01 17:56:32 +00001226
David L. Jonesd21529f2017-01-23 23:16:46 +00001227 if (!TLI->has(LibFunc_memmove))
Chris Lattner23f61a02011-05-01 18:27:11 +00001228 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001229
Chris Lattner1145e332009-09-01 17:56:32 +00001230 // See if the pointers alias.
Chandler Carruth70c61c12015-06-04 02:03:15 +00001231 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1232 MemoryLocation::getForSource(M)))
Chris Lattner1145e332009-09-01 17:56:32 +00001233 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001234
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001235 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1236 << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001237
Chris Lattner1145e332009-09-01 17:56:32 +00001238 // If not, then we know we can transform this.
Jay Foadb804a2b2011-07-12 14:06:48 +00001239 Type *ArgTys[3] = { M->getRawDest()->getType(),
1240 M->getRawSource()->getType(),
1241 M->getLength()->getType() };
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001242 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1243 Intrinsic::memcpy, ArgTys));
Duncan Sands0edc7102009-09-03 13:37:16 +00001244
Chris Lattner1145e332009-09-01 17:56:32 +00001245 // MemDep may have over conservative information about this instruction, just
1246 // conservatively flush it from the cache.
Chris Lattner58f9f582010-11-21 00:28:59 +00001247 MD->removeInstruction(M);
Duncan Sands0edc7102009-09-03 13:37:16 +00001248
1249 ++NumMoveToCpy;
Chris Lattner1145e332009-09-01 17:56:32 +00001250 return true;
1251}
Nadav Rotem465834c2012-07-24 10:51:42 +00001252
Sanjay Patela75c41e2015-08-13 22:53:20 +00001253/// This is called on every byval argument in call sites.
Sean Silva6347df02016-06-14 02:44:55 +00001254bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001255 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
Chris Lattner59572292010-11-21 08:06:10 +00001256 // Find out what feeds this byval argument.
Chris Lattner58f9f582010-11-21 00:28:59 +00001257 Value *ByValArg = CS.getArgument(ArgNo);
Nick Lewyckyc585de62011-10-12 00:14:31 +00001258 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001259 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
Chandler Carruthac80dc72015-06-17 07:18:54 +00001260 MemDepResult DepInfo = MD->getPointerDependencyFrom(
George Burgess IV5e4a03a2018-12-23 06:40:39 +00001261 MemoryLocation(ByValArg, LocationSize::precise(ByValSize)), true,
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001262 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
Chris Lattner58f9f582010-11-21 00:28:59 +00001263 if (!DepInfo.isClobber())
1264 return false;
1265
1266 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1267 // a memcpy, see if we can byval from the source of the memcpy instead of the
1268 // result.
1269 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
Craig Topperf40110f2014-04-25 05:29:35 +00001270 if (!MDep || MDep->isVolatile() ||
Chris Lattner58f9f582010-11-21 00:28:59 +00001271 ByValArg->stripPointerCasts() != MDep->getDest())
1272 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001273
Chris Lattner58f9f582010-11-21 00:28:59 +00001274 // The length of the memcpy must be larger or equal to the size of the byval.
Chris Lattner58f9f582010-11-21 00:28:59 +00001275 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001276 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
Chris Lattner58f9f582010-11-21 00:28:59 +00001277 return false;
1278
Chris Lattner83791ce2011-05-23 00:03:39 +00001279 // Get the alignment of the byval. If the call doesn't specify the alignment,
1280 // then it is some target specific value that we can't know.
Reid Kleckner859f8b52017-04-28 20:34:27 +00001281 unsigned ByValAlign = CS.getParamAlignment(ArgNo);
Chris Lattner83791ce2011-05-23 00:03:39 +00001282 if (ByValAlign == 0) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001283
Chris Lattner83791ce2011-05-23 00:03:39 +00001284 // If it is greater than the memcpy, then we check to see if we can force the
1285 // source of the memcpy to the alignment we need. If we fail, we bail out.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001286 AssumptionCache &AC = LookupAssumptionCache();
Sean Silva6347df02016-06-14 02:44:55 +00001287 DominatorTree &DT = LookupDomTree();
Daniel Neilson6f1eb582018-03-21 14:14:55 +00001288 if (MDep->getSourceAlignment() < ByValAlign &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001289 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001290 CS.getInstruction(), &AC, &DT) < ByValAlign)
Chris Lattner83791ce2011-05-23 00:03:39 +00001291 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001292
Matt Arsenaultdaa08872017-04-10 19:00:25 +00001293 // The address space of the memcpy source must match the byval argument
1294 if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1295 ByValArg->getType()->getPointerAddressSpace())
1296 return false;
1297
Chris Lattner58f9f582010-11-21 00:28:59 +00001298 // Verify that the copied-from memory doesn't change in between the memcpy and
1299 // the byval call.
1300 // memcpy(a <- b)
1301 // *b = 42;
1302 // foo(*a)
1303 // It would be invalid to transform the second memcpy into foo(*b).
Chris Lattner59572292010-11-21 08:06:10 +00001304 //
1305 // NOTE: This is conservative, it will stop on any read from the source loc,
1306 // not just the defining memcpy.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001307 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1308 MemoryLocation::getForSource(MDep), false,
1309 CS.getInstruction()->getIterator(), MDep->getParent());
Chris Lattner59572292010-11-21 08:06:10 +00001310 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1311 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001312
Chris Lattner58f9f582010-11-21 00:28:59 +00001313 Value *TmpCast = MDep->getSource();
1314 if (MDep->getSource()->getType() != ByValArg->getType())
1315 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1316 "tmpcast", CS.getInstruction());
Nadav Rotem465834c2012-07-24 10:51:42 +00001317
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001318 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1319 << " " << *MDep << "\n"
1320 << " " << *CS.getInstruction() << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001321
Chris Lattner58f9f582010-11-21 00:28:59 +00001322 // Otherwise we're good! Update the byval argument.
1323 CS.setArgument(ArgNo, TmpCast);
1324 ++NumMemCpyInstr;
1325 return true;
1326}
1327
Sean Silva6347df02016-06-14 02:44:55 +00001328/// Executes one iteration of MemCpyOptPass.
1329bool MemCpyOptPass::iterateOnFunction(Function &F) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001330 bool MadeChange = false;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001331
Bjorn Pettersson8e484dc2018-04-23 19:55:04 +00001332 DominatorTree &DT = LookupDomTree();
1333
Chris Lattnerb5557a72009-09-01 17:09:55 +00001334 // Walk all instruction in the function.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001335 for (BasicBlock &BB : F) {
Bjorn Pettersson8e484dc2018-04-23 19:55:04 +00001336 // Skip unreachable blocks. For example processStore assumes that an
1337 // instruction in a BB can't be dominated by a later instruction in the
1338 // same BB (which is a scenario that can happen for an unreachable BB that
1339 // has itself as a predecessor).
1340 if (!DT.isReachableFromEntry(&BB))
1341 continue;
1342
Benjamin Kramer135f7352016-06-26 12:28:59 +00001343 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Bjorn Pettersson8e484dc2018-04-23 19:55:04 +00001344 // Avoid invalidating the iterator.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001345 Instruction *I = &*BI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001346
Chris Lattner58f9f582010-11-21 00:28:59 +00001347 bool RepeatInstruction = false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001348
Owen Anderson6a7355c2008-04-21 07:45:10 +00001349 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Chris Lattnerb5557a72009-09-01 17:09:55 +00001350 MadeChange |= processStore(SI, BI);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001351 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1352 RepeatInstruction = processMemSet(M, BI);
1353 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
Tim Northover39617352016-05-10 21:49:40 +00001354 RepeatInstruction = processMemCpy(M);
Chris Lattner9a1d63b2011-01-08 21:19:19 +00001355 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
Chris Lattner58f9f582010-11-21 00:28:59 +00001356 RepeatInstruction = processMemMove(M);
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00001357 else if (auto CS = CallSite(I)) {
Chris Lattner58f9f582010-11-21 00:28:59 +00001358 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
Nick Lewycky612d70b2011-11-20 19:09:04 +00001359 if (CS.isByValArgument(i))
Chris Lattner58f9f582010-11-21 00:28:59 +00001360 MadeChange |= processByValArgument(CS, i);
1361 }
1362
1363 // Reprocess the instruction if desired.
1364 if (RepeatInstruction) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001365 if (BI != BB.begin())
1366 --BI;
Chris Lattner58f9f582010-11-21 00:28:59 +00001367 MadeChange = true;
Chris Lattner1145e332009-09-01 17:56:32 +00001368 }
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001369 }
1370 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001371
Chris Lattnerb5557a72009-09-01 17:09:55 +00001372 return MadeChange;
Owen Andersonef9a6fd2008-04-09 08:23:16 +00001373}
Chris Lattnerb5557a72009-09-01 17:09:55 +00001374
Sean Silva6347df02016-06-14 02:44:55 +00001375PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
Sean Silva6347df02016-06-14 02:44:55 +00001376 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1377 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1378
1379 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1380 return AM.getResult<AAManager>(F);
1381 };
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001382 auto LookupAssumptionCache = [&]() -> AssumptionCache & {
1383 return AM.getResult<AssumptionAnalysis>(F);
1384 };
Sean Silva6347df02016-06-14 02:44:55 +00001385 auto LookupDomTree = [&]() -> DominatorTree & {
1386 return AM.getResult<DominatorTreeAnalysis>(F);
1387 };
1388
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001389 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
1390 LookupAssumptionCache, LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001391 if (!MadeChange)
1392 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001393
Sean Silva6347df02016-06-14 02:44:55 +00001394 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001395 PA.preserveSet<CFGAnalyses>();
Sean Silva6347df02016-06-14 02:44:55 +00001396 PA.preserve<GlobalsAA>();
1397 PA.preserve<MemoryDependenceAnalysis>();
1398 return PA;
1399}
1400
1401bool MemCpyOptPass::runImpl(
1402 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
1403 std::function<AliasAnalysis &()> LookupAliasAnalysis_,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001404 std::function<AssumptionCache &()> LookupAssumptionCache_,
Sean Silva6347df02016-06-14 02:44:55 +00001405 std::function<DominatorTree &()> LookupDomTree_) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001406 bool MadeChange = false;
Sean Silva6347df02016-06-14 02:44:55 +00001407 MD = MD_;
1408 TLI = TLI_;
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001409 LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001410 LookupAssumptionCache = std::move(LookupAssumptionCache_);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00001411 LookupDomTree = std::move(LookupDomTree_);
Nadav Rotem465834c2012-07-24 10:51:42 +00001412
Chris Lattner23f61a02011-05-01 18:27:11 +00001413 // If we don't have at least memset and memcpy, there is little point of doing
1414 // anything here. These are required by a freestanding implementation, so if
1415 // even they are disabled, there is no point in trying hard.
David L. Jonesd21529f2017-01-23 23:16:46 +00001416 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
Chris Lattner23f61a02011-05-01 18:27:11 +00001417 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001418
Eugene Zelenko34c23272017-01-18 00:57:48 +00001419 while (true) {
Chris Lattnerb5557a72009-09-01 17:09:55 +00001420 if (!iterateOnFunction(F))
1421 break;
1422 MadeChange = true;
1423 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001424
Craig Topperf40110f2014-04-25 05:29:35 +00001425 MD = nullptr;
Chris Lattnerb5557a72009-09-01 17:09:55 +00001426 return MadeChange;
1427}
Sean Silva6347df02016-06-14 02:44:55 +00001428
1429/// This is the main transformation entry point for a function.
1430bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1431 if (skipFunction(F))
1432 return false;
1433
1434 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001435 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Sean Silva6347df02016-06-14 02:44:55 +00001436
1437 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1438 return getAnalysis<AAResultsWrapperPass>().getAAResults();
1439 };
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001440 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
1441 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1442 };
Sean Silva6347df02016-06-14 02:44:55 +00001443 auto LookupDomTree = [this]() -> DominatorTree & {
1444 return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1445 };
1446
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001447 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,
1448 LookupDomTree);
Sean Silva6347df02016-06-14 02:44:55 +00001449}