1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs various transformations related to eliminating memcpy
11 // calls, or transforming sets of stores into memset's.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/Local.h"
36 #define DEBUG_TYPE "memcpyopt"
38 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
39 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
40 STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
41 STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
43 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
44 bool &VariableIdxFound,
45 const DataLayout &DL) {
46 // Skip over the first indices.
47 gep_type_iterator GTI = gep_type_begin(GEP);
48 for (unsigned i = 1; i != Idx; ++i, ++GTI)
51 // Compute the offset implied by the rest of the indices.
53 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
54 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
56 return VariableIdxFound = true;
57 if (OpC->isZero()) continue; // No offset.
59 // Handle struct indices, which add their field offset to the pointer.
60 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
61 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
65 // Otherwise, we have a sequential type like an array or vector. Multiply
66 // the index by the ElementSize.
67 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
68 Offset += Size*OpC->getSExtValue();
74 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
75 /// constant offset, and return that constant offset. For example, Ptr1 might
76 /// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
77 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
78 const DataLayout &DL) {
79 Ptr1 = Ptr1->stripPointerCasts();
80 Ptr2 = Ptr2->stripPointerCasts();
82 // Handle the trivial case first.
88 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
89 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
91 bool VariableIdxFound = false;
93 // If one pointer is a GEP and the other isn't, then see if the GEP is a
94 // constant offset from the base, as in "P" and "gep P, 1".
95 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
96 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
97 return !VariableIdxFound;
100 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
101 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
102 return !VariableIdxFound;
105 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
106 // base. After that base, they may have some number of common (and
107 // potentially variable) indices. After that they handle some constant
108 // offset, which determines their offset from each other. At this point, we
109 // handle no other case.
110 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
113 // Skip any common indices and track the GEP types.
115 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
116 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
119 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
120 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
121 if (VariableIdxFound) return false;
123 Offset = Offset2-Offset1;
128 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
129 /// This allows us to analyze stores like:
134 /// which sometimes happens with stores to arrays of structs etc. When we see
135 /// the first store, we make a range [1, 2). The second store extends the range
136 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
137 /// two ranges into [0, 3) which is memset'able.
140 // Start/End - A semi range that describes the span that this range covers.
141 // The range is closed at the start and open at the end: [Start, End).
144 /// StartPtr - The getelementptr instruction that points to the start of the
148 /// Alignment - The known alignment of the first store.
151 /// TheStores - The actual stores that make up this range.
152 SmallVector<Instruction*, 16> TheStores;
154 bool isProfitableToUseMemset(const DataLayout &DL) const;
156 } // end anon namespace
158 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
159 // If we found more than 4 stores to merge or 16 bytes, use memset.
160 if (TheStores.size() >= 4 || End-Start >= 16) return true;
162 // If there is nothing to merge, don't do anything.
163 if (TheStores.size() < 2) return false;
165 // If any of the stores are a memset, then it is always good to extend the
167 for (unsigned i = 0, e = TheStores.size(); i != e; ++i)
168 if (!isa<StoreInst>(TheStores[i]))
171 // Assume that the code generator is capable of merging pairs of stores
172 // together if it wants to.
173 if (TheStores.size() == 2) return false;
175 // If we have fewer than 8 stores, it can still be worthwhile to do this.
176 // For example, merging 4 i8 stores into an i32 store is useful almost always.
177 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
178 // memset will be split into 2 32-bit stores anyway) and doing so can
179 // pessimize the llvm optimizer.
181 // Since we don't have perfect knowledge here, make some assumptions: assume
182 // the maximum GPR width is the same size as the largest legal integer
183 // size. If so, check to see whether we will end up actually reducing the
184 // number of stores used.
185 unsigned Bytes = unsigned(End-Start);
186 unsigned MaxIntSize = DL.getLargestLegalIntTypeSize();
189 unsigned NumPointerStores = Bytes / MaxIntSize;
191 // Assume the remaining bytes if any are done a byte at a time.
192 unsigned NumByteStores = Bytes - NumPointerStores * MaxIntSize;
194 // If we will reduce the # stores (according to this heuristic), do the
195 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
197 return TheStores.size() > NumPointerStores+NumByteStores;
203 /// Ranges - A sorted list of the memset ranges. We use std::list here
204 /// because each element is relatively large and expensive to copy.
205 std::list<MemsetRange> Ranges;
206 typedef std::list<MemsetRange>::iterator range_iterator;
207 const DataLayout &DL;
209 MemsetRanges(const DataLayout &DL) : DL(DL) {}
211 typedef std::list<MemsetRange>::const_iterator const_iterator;
212 const_iterator begin() const { return Ranges.begin(); }
213 const_iterator end() const { return Ranges.end(); }
214 bool empty() const { return Ranges.empty(); }
216 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
217 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
218 addStore(OffsetFromFirst, SI);
220 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
223 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
224 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
226 addRange(OffsetFromFirst, StoreSize,
227 SI->getPointerOperand(), SI->getAlignment(), SI);
230 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
231 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
232 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
235 void addRange(int64_t Start, int64_t Size, Value *Ptr,
236 unsigned Alignment, Instruction *Inst);
240 } // end anon namespace
243 /// addRange - Add a new store to the MemsetRanges data structure. This adds a
244 /// new range for the specified store at the specified offset, merging into
245 /// existing ranges as appropriate.
247 /// Do a linear search of the ranges to see if this can be joined and/or to
248 /// find the insertion point in the list. We keep the ranges sorted for
249 /// simplicity here. This is a linear search of a linked list, which is ugly,
250 /// however the number of ranges is limited, so this won't get crazy slow.
251 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
252 unsigned Alignment, Instruction *Inst) {
253 int64_t End = Start+Size;
254 range_iterator I = Ranges.begin(), E = Ranges.end();
256 while (I != E && Start > I->End)
259 // We now know that I == E, in which case we didn't find anything to merge
260 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
261 // to insert a new range. Handle this now.
262 if (I == E || End < I->Start) {
263 MemsetRange &R = *Ranges.insert(I, MemsetRange());
267 R.Alignment = Alignment;
268 R.TheStores.push_back(Inst);
272 // This store overlaps with I, add it.
273 I->TheStores.push_back(Inst);
275 // At this point, we may have an interval that completely contains our store.
276 // If so, just add it to the interval and return.
277 if (I->Start <= Start && I->End >= End)
280 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
281 // but is not entirely contained within the range.
283 // See if the range extends the start of the range. In this case, it couldn't
284 // possibly cause it to join the prior range, because otherwise we would have
286 if (Start < I->Start) {
289 I->Alignment = Alignment;
292 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
293 // is in or right at the end of I), and that End >= I->Start. Extend I out to
297 range_iterator NextI = I;
298 while (++NextI != E && End >= NextI->Start) {
299 // Merge the range in.
300 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
301 if (NextI->End > I->End)
309 //===----------------------------------------------------------------------===//
311 //===----------------------------------------------------------------------===//
314 class MemCpyOpt : public FunctionPass {
315 MemoryDependenceAnalysis *MD;
316 TargetLibraryInfo *TLI;
318 static char ID; // Pass identification, replacement for typeid
319 MemCpyOpt() : FunctionPass(ID) {
320 initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
325 bool runOnFunction(Function &F) override;
328 // This transformation requires dominator postdominator info
329 void getAnalysisUsage(AnalysisUsage &AU) const override {
330 AU.setPreservesCFG();
331 AU.addRequired<AssumptionCacheTracker>();
332 AU.addRequired<DominatorTreeWrapperPass>();
333 AU.addRequired<MemoryDependenceAnalysis>();
334 AU.addRequired<AliasAnalysis>();
335 AU.addRequired<TargetLibraryInfoWrapperPass>();
336 AU.addPreserved<AliasAnalysis>();
337 AU.addPreserved<MemoryDependenceAnalysis>();
341 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
342 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
343 bool processMemCpy(MemCpyInst *M);
344 bool processMemMove(MemMoveInst *M);
345 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
346 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
347 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
349 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
350 bool processByValArgument(CallSite CS, unsigned ArgNo);
351 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
354 bool iterateOnFunction(Function &F);
357 char MemCpyOpt::ID = 0;
360 // createMemCpyOptPass - The public interface to this file...
361 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
363 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
365 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
366 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
367 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
368 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
369 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
370 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
373 /// tryMergingIntoMemset - When scanning forward over instructions, we look for
374 /// some other patterns to fold away. In particular, this looks for stores to
375 /// neighboring locations of memory. If it sees enough consecutive ones, it
376 /// attempts to merge them together into a memcpy/memset.
377 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
378 Value *StartPtr, Value *ByteVal) {
379 const DataLayout &DL = StartInst->getModule()->getDataLayout();
381 // Okay, so we now have a single store that can be splatable. Scan to find
382 // all subsequent stores of the same value to offset from the same pointer.
383 // Join these together into ranges, so we can decide whether contiguous blocks
385 MemsetRanges Ranges(DL);
387 BasicBlock::iterator BI = StartInst;
388 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
389 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
390 // If the instruction is readnone, ignore it, otherwise bail out. We
391 // don't even allow readonly here because we don't want something like:
392 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
393 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
398 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
399 // If this is a store, see if we can merge it in.
400 if (!NextStore->isSimple()) break;
402 // Check to see if this stored value is of the same byte-splattable value.
403 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
406 // Check to see if this store is to a constant offset from the start ptr.
408 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
412 Ranges.addStore(Offset, NextStore);
414 MemSetInst *MSI = cast<MemSetInst>(BI);
416 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
417 !isa<ConstantInt>(MSI->getLength()))
420 // Check to see if this store is to a constant offset from the start ptr.
422 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
425 Ranges.addMemSet(Offset, MSI);
429 // If we have no ranges, then we just had a single store with nothing that
430 // could be merged in. This is a very common case of course.
434 // If we had at least one store that could be merged in, add the starting
435 // store as well. We try to avoid this unless there is at least something
436 // interesting as a small compile-time optimization.
437 Ranges.addInst(0, StartInst);
439 // If we create any memsets, we put it right before the first instruction that
440 // isn't part of the memset block. This ensure that the memset is dominated
441 // by any addressing instruction needed by the start of the block.
442 IRBuilder<> Builder(BI);
444 // Now that we have full information about ranges, loop over the ranges and
445 // emit memset's for anything big enough to be worthwhile.
446 Instruction *AMemSet = nullptr;
447 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
449 const MemsetRange &Range = *I;
451 if (Range.TheStores.size() == 1) continue;
453 // If it is profitable to lower this range to memset, do so now.
454 if (!Range.isProfitableToUseMemset(DL))
457 // Otherwise, we do want to transform this! Create a new memset.
458 // Get the starting pointer of the block.
459 StartPtr = Range.StartPtr;
461 // Determine alignment
462 unsigned Alignment = Range.Alignment;
463 if (Alignment == 0) {
465 cast<PointerType>(StartPtr->getType())->getElementType();
466 Alignment = DL.getABITypeAlignment(EltType);
470 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
472 DEBUG(dbgs() << "Replace stores:\n";
473 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
474 dbgs() << *Range.TheStores[i] << '\n';
475 dbgs() << "With: " << *AMemSet << '\n');
477 if (!Range.TheStores.empty())
478 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
480 // Zap all the stores.
481 for (SmallVectorImpl<Instruction *>::const_iterator
482 SI = Range.TheStores.begin(),
483 SE = Range.TheStores.end(); SI != SE; ++SI) {
484 MD->removeInstruction(*SI);
485 (*SI)->eraseFromParent();
494 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
495 if (!SI->isSimple()) return false;
496 const DataLayout &DL = SI->getModule()->getDataLayout();
498 // Detect cases where we're performing call slot forwarding, but
499 // happen to be using a load-store pair to implement it, rather than
501 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
502 if (LI->isSimple() && LI->hasOneUse() &&
503 LI->getParent() == SI->getParent()) {
504 MemDepResult ldep = MD->getDependency(LI);
505 CallInst *C = nullptr;
506 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
507 C = dyn_cast<CallInst>(ldep.getInst());
510 // Check that nothing touches the dest of the "copy" between
511 // the call and the store.
512 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
513 AliasAnalysis::Location StoreLoc = AA.getLocation(SI);
514 for (BasicBlock::iterator I = --BasicBlock::iterator(SI),
515 E = C; I != E; --I) {
516 if (AA.getModRefInfo(&*I, StoreLoc) != AliasAnalysis::NoModRef) {
524 unsigned storeAlign = SI->getAlignment();
526 storeAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
527 unsigned loadAlign = LI->getAlignment();
529 loadAlign = DL.getABITypeAlignment(LI->getType());
531 bool changed = performCallSlotOptzn(
532 LI, SI->getPointerOperand()->stripPointerCasts(),
533 LI->getPointerOperand()->stripPointerCasts(),
534 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
535 std::min(storeAlign, loadAlign), C);
537 MD->removeInstruction(SI);
538 SI->eraseFromParent();
539 MD->removeInstruction(LI);
540 LI->eraseFromParent();
548 // There are two cases that are interesting for this code to handle: memcpy
549 // and memset. Right now we only handle memset.
551 // Ensure that the value being stored is something that can be memset'able a
552 // byte at a time like "0" or "-1" or any width, as well as things like
553 // 0xA0A0A0A0 and 0.0.
554 if (Value *ByteVal = isBytewiseValue(SI->getOperand(0)))
555 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
557 BBI = I; // Don't invalidate iterator.
564 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
565 // See if there is another memset or store neighboring this memset which
566 // allows us to widen out the memset to do a single larger store.
567 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
568 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
570 BBI = I; // Don't invalidate iterator.
577 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
578 /// and checks for the possibility of a call slot optimization by having
579 /// the call write its result directly into the destination of the memcpy.
580 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
581 Value *cpyDest, Value *cpySrc,
582 uint64_t cpyLen, unsigned cpyAlign,
584 // The general transformation to keep in mind is
586 // call @func(..., src, ...)
587 // memcpy(dest, src, ...)
591 // memcpy(dest, src, ...)
592 // call @func(..., dest, ...)
594 // Since moving the memcpy is technically awkward, we additionally check that
595 // src only holds uninitialized values at the moment of the call, meaning that
596 // the memcpy can be discarded rather than moved.
598 // Deliberately get the source and destination with bitcasts stripped away,
599 // because we'll need to do type comparisons based on the underlying type.
602 // Require that src be an alloca. This simplifies the reasoning considerably.
603 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
607 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
611 const DataLayout &DL = cpy->getModule()->getDataLayout();
612 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
613 srcArraySize->getZExtValue();
615 if (cpyLen < srcSize)
618 // Check that accessing the first srcSize bytes of dest will not cause a
619 // trap. Otherwise the transform is invalid since it might cause a trap
620 // to occur earlier than it otherwise would.
621 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
622 // The destination is an alloca. Check it is larger than srcSize.
623 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
627 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
628 destArraySize->getZExtValue();
630 if (destSize < srcSize)
632 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
633 if (A->getDereferenceableBytes() < srcSize) {
634 // If the destination is an sret parameter then only accesses that are
635 // outside of the returned struct type can trap.
636 if (!A->hasStructRetAttr())
639 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
640 if (!StructTy->isSized()) {
641 // The call may never return and hence the copy-instruction may never
642 // be executed, and therefore it's not safe to say "the destination
643 // has at least <cpyLen> bytes, as implied by the copy-instruction",
647 uint64_t destSize = DL.getTypeAllocSize(StructTy);
648 if (destSize < srcSize)
655 // Check that dest points to memory that is at least as aligned as src.
656 unsigned srcAlign = srcAlloca->getAlignment();
658 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
659 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
660 // If dest is not aligned enough and we can't increase its alignment then
662 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
665 // Check that src is not accessed except via the call and the memcpy. This
666 // guarantees that it holds only undefined values when passed in (so the final
667 // memcpy can be dropped), that it is not read or written between the call and
668 // the memcpy, and that writing beyond the end of it is undefined.
669 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
670 srcAlloca->user_end());
671 while (!srcUseList.empty()) {
672 User *U = srcUseList.pop_back_val();
674 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
675 for (User *UU : U->users())
676 srcUseList.push_back(UU);
679 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
680 if (!G->hasAllZeroIndices())
683 for (User *UU : U->users())
684 srcUseList.push_back(UU);
687 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
688 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
689 IT->getIntrinsicID() == Intrinsic::lifetime_end)
692 if (U != C && U != cpy)
696 // Check that src isn't captured by the called function since the
697 // transformation can cause aliasing issues in that case.
698 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
699 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
702 // Since we're changing the parameter to the callsite, we need to make sure
703 // that what would be the new parameter dominates the callsite.
704 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
705 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
706 if (!DT.dominates(cpyDestInst, C))
709 // In addition to knowing that the call does not access src in some
710 // unexpected manner, for example via a global, which we deduce from
711 // the use analysis, we also need to know that it does not sneakily
712 // access dest. We rely on AA to figure this out for us.
713 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
714 AliasAnalysis::ModRefResult MR = AA.getModRefInfo(C, cpyDest, srcSize);
715 // If necessary, perform additional analysis.
716 if (MR != AliasAnalysis::NoModRef)
717 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
718 if (MR != AliasAnalysis::NoModRef)
721 // All the checks have passed, so do the transformation.
722 bool changedArgument = false;
723 for (unsigned i = 0; i < CS.arg_size(); ++i)
724 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
725 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
726 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
727 cpyDest->getName(), C);
728 changedArgument = true;
729 if (CS.getArgument(i)->getType() == Dest->getType())
730 CS.setArgument(i, Dest);
732 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
733 CS.getArgument(i)->getType(), Dest->getName(), C));
736 if (!changedArgument)
739 // If the destination wasn't sufficiently aligned then increase its alignment.
740 if (!isDestSufficientlyAligned) {
741 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
742 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
745 // Drop any cached information about the call, because we may have changed
746 // its dependence information by changing its parameter.
747 MD->removeInstruction(C);
749 // Update AA metadata
750 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
751 // handled here, but combineMetadata doesn't support them yet
752 unsigned KnownIDs[] = {
753 LLVMContext::MD_tbaa,
754 LLVMContext::MD_alias_scope,
755 LLVMContext::MD_noalias,
757 combineMetadata(C, cpy, KnownIDs);
759 // Remove the memcpy.
760 MD->removeInstruction(cpy);
766 /// processMemCpyMemCpyDependence - We've found that the (upward scanning)
767 /// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to
768 /// copy from MDep's input if we can. MSize is the size of M's copy.
770 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep,
772 // We can only transforms memcpy's where the dest of one is the source of the
774 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
777 // If dep instruction is reading from our current input, then it is a noop
778 // transfer and substituting the input won't change this instruction. Just
779 // ignore the input and let someone else zap MDep. This handles cases like:
782 if (M->getSource() == MDep->getSource())
785 // Second, the length of the memcpy's must be the same, or the preceding one
786 // must be larger than the following one.
787 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
788 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
789 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
792 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
794 // Verify that the copied-from memory doesn't change in between the two
795 // transfers. For example, in:
799 // It would be invalid to transform the second memcpy into memcpy(c <- b).
801 // TODO: If the code between M and MDep is transparent to the destination "c",
802 // then we could still perform the xform by moving M up to the first memcpy.
804 // NOTE: This is conservative, it will stop on any read from the source loc,
805 // not just the defining memcpy.
806 MemDepResult SourceDep =
807 MD->getPointerDependencyFrom(AA.getLocationForSource(MDep),
808 false, M, M->getParent());
809 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
812 // If the dest of the second might alias the source of the first, then the
813 // source and dest might overlap. We still want to eliminate the intermediate
814 // value, but we have to generate a memmove instead of memcpy.
815 bool UseMemMove = false;
816 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep)))
819 // If all checks passed, then we can transform M.
821 // Make sure to use the lesser of the alignment of the source and the dest
822 // since we're changing where we're reading from, but don't want to increase
823 // the alignment past what can be read from or written to.
824 // TODO: Is this worth it if we're creating a less aligned memcpy? For
825 // example we could be moving from movaps -> movq on x86.
826 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
828 IRBuilder<> Builder(M);
830 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
831 Align, M->isVolatile());
833 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
834 Align, M->isVolatile());
836 // Remove the instruction we're replacing.
837 MD->removeInstruction(M);
838 M->eraseFromParent();
843 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
844 /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
845 /// weren't copied over by \p MemCpy.
847 /// In other words, transform:
849 /// memset(dst, c, dst_size);
850 /// memcpy(dst, src, src_size);
854 /// memcpy(dst, src, src_size);
855 /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
857 bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
858 MemSetInst *MemSet) {
859 // We can only transform memset/memcpy with the same destination.
860 if (MemSet->getDest() != MemCpy->getDest())
863 // Use the same i8* dest as the memcpy, killing the memset dest if different.
864 Value *Dest = MemCpy->getRawDest();
865 Value *DestSize = MemSet->getLength();
866 Value *SrcSize = MemCpy->getLength();
868 // By default, create an unaligned memset.
870 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
872 const unsigned DestAlign =
873 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
875 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
876 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
878 IRBuilder<> Builder(MemCpy->getNextNode());
880 // If the sizes have different types, zext the smaller one.
881 if (DestSize->getType() != SrcSize->getType()) {
882 if (DestSize->getType()->getIntegerBitWidth() >
883 SrcSize->getType()->getIntegerBitWidth())
884 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
886 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
890 Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
891 ConstantInt::getNullValue(DestSize->getType()),
892 Builder.CreateSub(DestSize, SrcSize));
893 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
896 MD->removeInstruction(MemSet);
897 MemSet->eraseFromParent();
901 /// processMemCpy - perform simplification of memcpy's. If we have memcpy A
902 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
903 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
904 /// circumstances). This allows later passes to remove the first memcpy
906 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
907 // We can only optimize non-volatile memcpy's.
908 if (M->isVolatile()) return false;
910 // If the source and destination of the memcpy are the same, then zap it.
911 if (M->getSource() == M->getDest()) {
912 MD->removeInstruction(M);
913 M->eraseFromParent();
917 // If copying from a constant, try to turn the memcpy into a memset.
918 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
919 if (GV->isConstant() && GV->hasDefinitiveInitializer())
920 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
921 IRBuilder<> Builder(M);
922 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
923 M->getAlignment(), false);
924 MD->removeInstruction(M);
925 M->eraseFromParent();
930 AliasAnalysis::Location SrcLoc = AliasAnalysis::getLocationForSource(M);
931 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(SrcLoc, true,
934 // Try to turn a partially redundant memset + memcpy into
935 // memcpy + smaller memset. We don't need the memcpy size for this.
936 if (SrcDepInfo.isClobber())
937 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
938 if (processMemSetMemCpyDependence(M, MDep))
941 // The optimizations after this point require the memcpy size.
942 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
943 if (!CopySize) return false;
945 // The are three possible optimizations we can do for memcpy:
946 // a) memcpy-memcpy xform which exposes redundance for DSE.
947 // b) call-memcpy xform for return slot optimization.
948 // c) memcpy from freshly alloca'd space or space that has just started its
949 // lifetime copies undefined data, and we can therefore eliminate the
950 // memcpy in favor of the data that was already at the destination.
951 MemDepResult DepInfo = MD->getDependency(M);
952 if (DepInfo.isClobber()) {
953 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
954 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
955 CopySize->getZExtValue(), M->getAlignment(),
957 MD->removeInstruction(M);
958 M->eraseFromParent();
964 if (SrcDepInfo.isClobber()) {
965 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
966 return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue());
967 } else if (SrcDepInfo.isDef()) {
968 Instruction *I = SrcDepInfo.getInst();
969 bool hasUndefContents = false;
971 if (isa<AllocaInst>(I)) {
972 hasUndefContents = true;
973 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
974 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
975 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
976 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
977 hasUndefContents = true;
980 if (hasUndefContents) {
981 MD->removeInstruction(M);
982 M->eraseFromParent();
991 /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst
992 /// are guaranteed not to alias.
993 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
994 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
996 if (!TLI->has(LibFunc::memmove))
999 // See if the pointers alias.
1000 if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M)))
1003 DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
1005 // If not, then we know we can transform this.
1006 Module *Mod = M->getParent()->getParent()->getParent();
1007 Type *ArgTys[3] = { M->getRawDest()->getType(),
1008 M->getRawSource()->getType(),
1009 M->getLength()->getType() };
1010 M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy,
1013 // MemDep may have over conservative information about this instruction, just
1014 // conservatively flush it from the cache.
1015 MD->removeInstruction(M);
1021 /// processByValArgument - This is called on every byval argument in call sites.
1022 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
1023 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
1024 // Find out what feeds this byval argument.
1025 Value *ByValArg = CS.getArgument(ArgNo);
1026 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1027 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1028 MemDepResult DepInfo =
1029 MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize),
1030 true, CS.getInstruction(),
1031 CS.getInstruction()->getParent());
1032 if (!DepInfo.isClobber())
1035 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1036 // a memcpy, see if we can byval from the source of the memcpy instead of the
1038 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1039 if (!MDep || MDep->isVolatile() ||
1040 ByValArg->stripPointerCasts() != MDep->getDest())
1043 // The length of the memcpy must be larger or equal to the size of the byval.
1044 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1045 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1048 // Get the alignment of the byval. If the call doesn't specify the alignment,
1049 // then it is some target specific value that we can't know.
1050 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
1051 if (ByValAlign == 0) return false;
1053 // If it is greater than the memcpy, then we check to see if we can force the
1054 // source of the memcpy to the alignment we need. If we fail, we bail out.
1055 AssumptionCache &AC =
1056 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
1057 *CS->getParent()->getParent());
1058 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1059 if (MDep->getAlignment() < ByValAlign &&
1060 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1061 CS.getInstruction(), &AC, &DT) < ByValAlign)
1064 // Verify that the copied-from memory doesn't change in between the memcpy and
1069 // It would be invalid to transform the second memcpy into foo(*b).
1071 // NOTE: This is conservative, it will stop on any read from the source loc,
1072 // not just the defining memcpy.
1073 MemDepResult SourceDep =
1074 MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep),
1075 false, CS.getInstruction(), MDep->getParent());
1076 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1079 Value *TmpCast = MDep->getSource();
1080 if (MDep->getSource()->getType() != ByValArg->getType())
1081 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1082 "tmpcast", CS.getInstruction());
1084 DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
1085 << " " << *MDep << "\n"
1086 << " " << *CS.getInstruction() << "\n");
1088 // Otherwise we're good! Update the byval argument.
1089 CS.setArgument(ArgNo, TmpCast);
1094 /// iterateOnFunction - Executes one iteration of MemCpyOpt.
1095 bool MemCpyOpt::iterateOnFunction(Function &F) {
1096 bool MadeChange = false;
1098 // Walk all instruction in the function.
1099 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
1100 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
1101 // Avoid invalidating the iterator.
1102 Instruction *I = BI++;
1104 bool RepeatInstruction = false;
1106 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1107 MadeChange |= processStore(SI, BI);
1108 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1109 RepeatInstruction = processMemSet(M, BI);
1110 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1111 RepeatInstruction = processMemCpy(M);
1112 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1113 RepeatInstruction = processMemMove(M);
1114 else if (auto CS = CallSite(I)) {
1115 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
1116 if (CS.isByValArgument(i))
1117 MadeChange |= processByValArgument(CS, i);
1120 // Reprocess the instruction if desired.
1121 if (RepeatInstruction) {
1122 if (BI != BB->begin()) --BI;
1131 // MemCpyOpt::runOnFunction - This is the main transformation entry point for a
1134 bool MemCpyOpt::runOnFunction(Function &F) {
1135 if (skipOptnoneFunction(F))
1138 bool MadeChange = false;
1139 MD = &getAnalysis<MemoryDependenceAnalysis>();
1140 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1142 // If we don't have at least memset and memcpy, there is little point of doing
1143 // anything here. These are required by a freestanding implementation, so if
1144 // even they are disabled, there is no point in trying hard.
1145 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1149 if (!iterateOnFunction(F))