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/MemCpyOptimizer.h"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/Local.h"
31 #define DEBUG_TYPE "memcpyopt"
33 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
34 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
35 STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
36 STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
38 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
39 bool &VariableIdxFound,
40 const DataLayout &DL) {
41 // Skip over the first indices.
42 gep_type_iterator GTI = gep_type_begin(GEP);
43 for (unsigned i = 1; i != Idx; ++i, ++GTI)
46 // Compute the offset implied by the rest of the indices.
48 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
49 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
51 return VariableIdxFound = true;
52 if (OpC->isZero()) continue; // No offset.
54 // Handle struct indices, which add their field offset to the pointer.
55 if (StructType *STy = GTI.getStructTypeOrNull()) {
56 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
60 // Otherwise, we have a sequential type like an array or vector. Multiply
61 // the index by the ElementSize.
62 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
63 Offset += Size*OpC->getSExtValue();
69 /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
70 /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
71 /// might be &A[40]. In this case offset would be -8.
72 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
73 const DataLayout &DL) {
74 Ptr1 = Ptr1->stripPointerCasts();
75 Ptr2 = Ptr2->stripPointerCasts();
77 // Handle the trivial case first.
83 GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
84 GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
86 bool VariableIdxFound = false;
88 // If one pointer is a GEP and the other isn't, then see if the GEP is a
89 // constant offset from the base, as in "P" and "gep P, 1".
90 if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
91 Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
92 return !VariableIdxFound;
95 if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
96 Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
97 return !VariableIdxFound;
100 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
101 // base. After that base, they may have some number of common (and
102 // potentially variable) indices. After that they handle some constant
103 // offset, which determines their offset from each other. At this point, we
104 // handle no other case.
105 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
108 // Skip any common indices and track the GEP types.
110 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
111 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
114 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
115 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
116 if (VariableIdxFound) return false;
118 Offset = Offset2-Offset1;
123 /// Represents a range of memset'd bytes with the ByteVal value.
124 /// This allows us to analyze stores like:
129 /// which sometimes happens with stores to arrays of structs etc. When we see
130 /// the first store, we make a range [1, 2). The second store extends the range
131 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
132 /// two ranges into [0, 3) which is memset'able.
135 // Start/End - A semi range that describes the span that this range covers.
136 // The range is closed at the start and open at the end: [Start, End).
139 /// StartPtr - The getelementptr instruction that points to the start of the
143 /// Alignment - The known alignment of the first store.
146 /// TheStores - The actual stores that make up this range.
147 SmallVector<Instruction*, 16> TheStores;
149 bool isProfitableToUseMemset(const DataLayout &DL) const;
151 } // end anon namespace
153 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
154 // If we found more than 4 stores to merge or 16 bytes, use memset.
155 if (TheStores.size() >= 4 || End-Start >= 16) return true;
157 // If there is nothing to merge, don't do anything.
158 if (TheStores.size() < 2) return false;
160 // If any of the stores are a memset, then it is always good to extend the
162 for (Instruction *SI : TheStores)
163 if (!isa<StoreInst>(SI))
166 // Assume that the code generator is capable of merging pairs of stores
167 // together if it wants to.
168 if (TheStores.size() == 2) return false;
170 // If we have fewer than 8 stores, it can still be worthwhile to do this.
171 // For example, merging 4 i8 stores into an i32 store is useful almost always.
172 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
173 // memset will be split into 2 32-bit stores anyway) and doing so can
174 // pessimize the llvm optimizer.
176 // Since we don't have perfect knowledge here, make some assumptions: assume
177 // the maximum GPR width is the same size as the largest legal integer
178 // size. If so, check to see whether we will end up actually reducing the
179 // number of stores used.
180 unsigned Bytes = unsigned(End-Start);
181 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
184 unsigned NumPointerStores = Bytes / MaxIntSize;
186 // Assume the remaining bytes if any are done a byte at a time.
187 unsigned NumByteStores = Bytes % MaxIntSize;
189 // If we will reduce the # stores (according to this heuristic), do the
190 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
192 return TheStores.size() > NumPointerStores+NumByteStores;
198 /// A sorted list of the memset ranges.
199 SmallVector<MemsetRange, 8> Ranges;
200 typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
201 const DataLayout &DL;
203 MemsetRanges(const DataLayout &DL) : DL(DL) {}
205 typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
206 const_iterator begin() const { return Ranges.begin(); }
207 const_iterator end() const { return Ranges.end(); }
208 bool empty() const { return Ranges.empty(); }
210 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
211 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
212 addStore(OffsetFromFirst, SI);
214 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
217 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
218 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
220 addRange(OffsetFromFirst, StoreSize,
221 SI->getPointerOperand(), SI->getAlignment(), SI);
224 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
225 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
226 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
229 void addRange(int64_t Start, int64_t Size, Value *Ptr,
230 unsigned Alignment, Instruction *Inst);
234 } // end anon namespace
237 /// Add a new store to the MemsetRanges data structure. This adds a
238 /// new range for the specified store at the specified offset, merging into
239 /// existing ranges as appropriate.
240 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
241 unsigned Alignment, Instruction *Inst) {
242 int64_t End = Start+Size;
244 range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
245 [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
247 // We now know that I == E, in which case we didn't find anything to merge
248 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
249 // to insert a new range. Handle this now.
250 if (I == Ranges.end() || End < I->Start) {
251 MemsetRange &R = *Ranges.insert(I, MemsetRange());
255 R.Alignment = Alignment;
256 R.TheStores.push_back(Inst);
260 // This store overlaps with I, add it.
261 I->TheStores.push_back(Inst);
263 // At this point, we may have an interval that completely contains our store.
264 // If so, just add it to the interval and return.
265 if (I->Start <= Start && I->End >= End)
268 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
269 // but is not entirely contained within the range.
271 // See if the range extends the start of the range. In this case, it couldn't
272 // possibly cause it to join the prior range, because otherwise we would have
274 if (Start < I->Start) {
277 I->Alignment = Alignment;
280 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
281 // is in or right at the end of I), and that End >= I->Start. Extend I out to
285 range_iterator NextI = I;
286 while (++NextI != Ranges.end() && End >= NextI->Start) {
287 // Merge the range in.
288 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
289 if (NextI->End > I->End)
297 //===----------------------------------------------------------------------===//
298 // MemCpyOptLegacyPass Pass
299 //===----------------------------------------------------------------------===//
302 class MemCpyOptLegacyPass : public FunctionPass {
305 static char ID; // Pass identification, replacement for typeid
306 MemCpyOptLegacyPass() : FunctionPass(ID) {
307 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
310 bool runOnFunction(Function &F) override;
313 // This transformation requires dominator postdominator info
314 void getAnalysisUsage(AnalysisUsage &AU) const override {
315 AU.setPreservesCFG();
316 AU.addRequired<AssumptionCacheTracker>();
317 AU.addRequired<DominatorTreeWrapperPass>();
318 AU.addRequired<MemoryDependenceWrapperPass>();
319 AU.addRequired<AAResultsWrapperPass>();
320 AU.addRequired<TargetLibraryInfoWrapperPass>();
321 AU.addPreserved<GlobalsAAWrapperPass>();
322 AU.addPreserved<MemoryDependenceWrapperPass>();
326 bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
327 bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
328 bool processMemCpy(MemCpyInst *M);
329 bool processMemMove(MemMoveInst *M);
330 bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
331 uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
332 bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
333 bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
334 bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
335 bool processByValArgument(CallSite CS, unsigned ArgNo);
336 Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
339 bool iterateOnFunction(Function &F);
342 char MemCpyOptLegacyPass::ID = 0;
345 /// The public interface to this file...
346 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
348 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
350 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
351 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
352 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
353 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
354 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
355 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
356 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
359 /// When scanning forward over instructions, we look for some other patterns to
360 /// fold away. In particular, this looks for stores to neighboring locations of
361 /// memory. If it sees enough consecutive ones, it attempts to merge them
362 /// together into a memcpy/memset.
363 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
366 const DataLayout &DL = StartInst->getModule()->getDataLayout();
368 // Okay, so we now have a single store that can be splatable. Scan to find
369 // all subsequent stores of the same value to offset from the same pointer.
370 // Join these together into ranges, so we can decide whether contiguous blocks
372 MemsetRanges Ranges(DL);
374 BasicBlock::iterator BI(StartInst);
375 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
376 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
377 // If the instruction is readnone, ignore it, otherwise bail out. We
378 // don't even allow readonly here because we don't want something like:
379 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
380 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
385 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
386 // If this is a store, see if we can merge it in.
387 if (!NextStore->isSimple()) break;
389 // Check to see if this stored value is of the same byte-splattable value.
390 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
393 // Check to see if this store is to a constant offset from the start ptr.
395 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
399 Ranges.addStore(Offset, NextStore);
401 MemSetInst *MSI = cast<MemSetInst>(BI);
403 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
404 !isa<ConstantInt>(MSI->getLength()))
407 // Check to see if this store is to a constant offset from the start ptr.
409 if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
412 Ranges.addMemSet(Offset, MSI);
416 // If we have no ranges, then we just had a single store with nothing that
417 // could be merged in. This is a very common case of course.
421 // If we had at least one store that could be merged in, add the starting
422 // store as well. We try to avoid this unless there is at least something
423 // interesting as a small compile-time optimization.
424 Ranges.addInst(0, StartInst);
426 // If we create any memsets, we put it right before the first instruction that
427 // isn't part of the memset block. This ensure that the memset is dominated
428 // by any addressing instruction needed by the start of the block.
429 IRBuilder<> Builder(&*BI);
431 // Now that we have full information about ranges, loop over the ranges and
432 // emit memset's for anything big enough to be worthwhile.
433 Instruction *AMemSet = nullptr;
434 for (const MemsetRange &Range : Ranges) {
436 if (Range.TheStores.size() == 1) continue;
438 // If it is profitable to lower this range to memset, do so now.
439 if (!Range.isProfitableToUseMemset(DL))
442 // Otherwise, we do want to transform this! Create a new memset.
443 // Get the starting pointer of the block.
444 StartPtr = Range.StartPtr;
446 // Determine alignment
447 unsigned Alignment = Range.Alignment;
448 if (Alignment == 0) {
450 cast<PointerType>(StartPtr->getType())->getElementType();
451 Alignment = DL.getABITypeAlignment(EltType);
455 Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
457 DEBUG(dbgs() << "Replace stores:\n";
458 for (Instruction *SI : Range.TheStores)
459 dbgs() << *SI << '\n';
460 dbgs() << "With: " << *AMemSet << '\n');
462 if (!Range.TheStores.empty())
463 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
465 // Zap all the stores.
466 for (Instruction *SI : Range.TheStores) {
467 MD->removeInstruction(SI);
468 SI->eraseFromParent();
476 static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
477 const LoadInst *LI) {
478 unsigned StoreAlign = SI->getAlignment();
480 StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
481 unsigned LoadAlign = LI->getAlignment();
483 LoadAlign = DL.getABITypeAlignment(LI->getType());
485 return std::min(StoreAlign, LoadAlign);
488 // This method try to lift a store instruction before position P.
489 // It will lift the store and its argument + that anything that
490 // may alias with these.
491 // The method returns true if it was successful.
492 static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P,
493 const LoadInst *LI) {
494 // If the store alias this position, early bail out.
495 MemoryLocation StoreLoc = MemoryLocation::get(SI);
496 if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef)
499 // Keep track of the arguments of all instruction we plan to lift
500 // so we can make sure to lift them as well if apropriate.
501 DenseSet<Instruction*> Args;
502 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
503 if (Ptr->getParent() == SI->getParent())
506 // Instruction to lift before P.
507 SmallVector<Instruction*, 8> ToLift;
509 // Memory locations of lifted instructions.
510 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
513 SmallVector<ImmutableCallSite, 8> CallSites;
515 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
517 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
520 bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef;
522 bool NeedLift = false;
526 NeedLift = any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
527 return AA.getModRefInfo(C, ML);
531 NeedLift = any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) {
532 return AA.getModRefInfo(C, CS);
540 // Since LI is implicitly moved downwards past the lifted instructions,
541 // none of them may modify its source.
542 if (AA.getModRefInfo(C, LoadLoc) & MRI_Mod)
544 else if (auto CS = ImmutableCallSite(C)) {
545 // If we can't lift this before P, it's game over.
546 if (AA.getModRefInfo(P, CS) != MRI_NoModRef)
549 CallSites.push_back(CS);
550 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
551 // If we can't lift this before P, it's game over.
552 auto ML = MemoryLocation::get(C);
553 if (AA.getModRefInfo(P, ML) != MRI_NoModRef)
556 MemLocs.push_back(ML);
558 // We don't know how to lift this instruction.
563 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
564 if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
565 if (A->getParent() == SI->getParent())
569 // We made it, we need to lift
570 for (auto *I : reverse(ToLift)) {
571 DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
578 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
579 if (!SI->isSimple()) return false;
581 // Avoid merging nontemporal stores since the resulting
582 // memcpy/memset would not be able to preserve the nontemporal hint.
583 // In theory we could teach how to propagate the !nontemporal metadata to
584 // memset calls. However, that change would force the backend to
585 // conservatively expand !nontemporal memset calls back to sequences of
586 // store instructions (effectively undoing the merging).
587 if (SI->getMetadata(LLVMContext::MD_nontemporal))
590 const DataLayout &DL = SI->getModule()->getDataLayout();
592 // Load to store forwarding can be interpreted as memcpy.
593 if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
594 if (LI->isSimple() && LI->hasOneUse() &&
595 LI->getParent() == SI->getParent()) {
597 auto *T = LI->getType();
598 if (T->isAggregateType()) {
599 AliasAnalysis &AA = LookupAliasAnalysis();
600 MemoryLocation LoadLoc = MemoryLocation::get(LI);
602 // We use alias analysis to check if an instruction may store to
603 // the memory we load from in between the load and the store. If
604 // such an instruction is found, we try to promote there instead
605 // of at the store position.
607 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
608 if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) {
614 // We found an instruction that may write to the loaded memory.
615 // We can try to promote at this position instead of the store
616 // position if nothing alias the store memory after this and the store
617 // destination is not in the range.
619 if (!moveUp(AA, SI, P, LI))
623 // If a valid insertion position is found, then we can promote
624 // the load/store pair to a memcpy.
626 // If we load from memory that may alias the memory we store to,
627 // memmove must be used to preserve semantic. If not, memcpy can
629 bool UseMemMove = false;
630 if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
633 unsigned Align = findCommonAlignment(DL, SI, LI);
634 uint64_t Size = DL.getTypeStoreSize(T);
636 IRBuilder<> Builder(P);
639 M = Builder.CreateMemMove(SI->getPointerOperand(),
640 LI->getPointerOperand(), Size,
641 Align, SI->isVolatile());
643 M = Builder.CreateMemCpy(SI->getPointerOperand(),
644 LI->getPointerOperand(), Size,
645 Align, SI->isVolatile());
647 DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
648 << " => " << *M << "\n");
650 MD->removeInstruction(SI);
651 SI->eraseFromParent();
652 MD->removeInstruction(LI);
653 LI->eraseFromParent();
656 // Make sure we do not invalidate the iterator.
657 BBI = M->getIterator();
662 // Detect cases where we're performing call slot forwarding, but
663 // happen to be using a load-store pair to implement it, rather than
665 MemDepResult ldep = MD->getDependency(LI);
666 CallInst *C = nullptr;
667 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
668 C = dyn_cast<CallInst>(ldep.getInst());
671 // Check that nothing touches the dest of the "copy" between
672 // the call and the store.
673 Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
674 bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
675 AliasAnalysis &AA = LookupAliasAnalysis();
676 MemoryLocation StoreLoc = MemoryLocation::get(SI);
677 for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
679 if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
683 // The store to dest may never happen if an exception can be thrown
684 // between the load and the store.
685 if (I->mayThrow() && !CpyDestIsLocal) {
693 bool changed = performCallSlotOptzn(
694 LI, SI->getPointerOperand()->stripPointerCasts(),
695 LI->getPointerOperand()->stripPointerCasts(),
696 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
697 findCommonAlignment(DL, SI, LI), C);
699 MD->removeInstruction(SI);
700 SI->eraseFromParent();
701 MD->removeInstruction(LI);
702 LI->eraseFromParent();
710 // There are two cases that are interesting for this code to handle: memcpy
711 // and memset. Right now we only handle memset.
713 // Ensure that the value being stored is something that can be memset'able a
714 // byte at a time like "0" or "-1" or any width, as well as things like
715 // 0xA0A0A0A0 and 0.0.
716 auto *V = SI->getOperand(0);
717 if (Value *ByteVal = isBytewiseValue(V)) {
718 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
720 BBI = I->getIterator(); // Don't invalidate iterator.
724 // If we have an aggregate, we try to promote it to memset regardless
725 // of opportunity for merging as it can expose optimization opportunities
726 // in subsequent passes.
727 auto *T = V->getType();
728 if (T->isAggregateType()) {
729 uint64_t Size = DL.getTypeStoreSize(T);
730 unsigned Align = SI->getAlignment();
732 Align = DL.getABITypeAlignment(T);
733 IRBuilder<> Builder(SI);
734 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
735 Size, Align, SI->isVolatile());
737 DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
739 MD->removeInstruction(SI);
740 SI->eraseFromParent();
743 // Make sure we do not invalidate the iterator.
744 BBI = M->getIterator();
752 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
753 // See if there is another memset or store neighboring this memset which
754 // allows us to widen out the memset to do a single larger store.
755 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
756 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
758 BBI = I->getIterator(); // Don't invalidate iterator.
765 /// Takes a memcpy and a call that it depends on,
766 /// and checks for the possibility of a call slot optimization by having
767 /// the call write its result directly into the destination of the memcpy.
768 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
769 Value *cpySrc, uint64_t cpyLen,
770 unsigned cpyAlign, CallInst *C) {
771 // The general transformation to keep in mind is
773 // call @func(..., src, ...)
774 // memcpy(dest, src, ...)
778 // memcpy(dest, src, ...)
779 // call @func(..., dest, ...)
781 // Since moving the memcpy is technically awkward, we additionally check that
782 // src only holds uninitialized values at the moment of the call, meaning that
783 // the memcpy can be discarded rather than moved.
785 // Lifetime marks shouldn't be operated on.
786 if (Function *F = C->getCalledFunction())
787 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
790 // Deliberately get the source and destination with bitcasts stripped away,
791 // because we'll need to do type comparisons based on the underlying type.
794 // Require that src be an alloca. This simplifies the reasoning considerably.
795 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
799 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
803 const DataLayout &DL = cpy->getModule()->getDataLayout();
804 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
805 srcArraySize->getZExtValue();
807 if (cpyLen < srcSize)
810 // Check that accessing the first srcSize bytes of dest will not cause a
811 // trap. Otherwise the transform is invalid since it might cause a trap
812 // to occur earlier than it otherwise would.
813 if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
814 // The destination is an alloca. Check it is larger than srcSize.
815 ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
819 uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
820 destArraySize->getZExtValue();
822 if (destSize < srcSize)
824 } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
825 // The store to dest may never happen if the call can throw.
829 if (A->getDereferenceableBytes() < srcSize) {
830 // If the destination is an sret parameter then only accesses that are
831 // outside of the returned struct type can trap.
832 if (!A->hasStructRetAttr())
835 Type *StructTy = cast<PointerType>(A->getType())->getElementType();
836 if (!StructTy->isSized()) {
837 // The call may never return and hence the copy-instruction may never
838 // be executed, and therefore it's not safe to say "the destination
839 // has at least <cpyLen> bytes, as implied by the copy-instruction",
843 uint64_t destSize = DL.getTypeAllocSize(StructTy);
844 if (destSize < srcSize)
851 // Check that dest points to memory that is at least as aligned as src.
852 unsigned srcAlign = srcAlloca->getAlignment();
854 srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
855 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
856 // If dest is not aligned enough and we can't increase its alignment then
858 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
861 // Check that src is not accessed except via the call and the memcpy. This
862 // guarantees that it holds only undefined values when passed in (so the final
863 // memcpy can be dropped), that it is not read or written between the call and
864 // the memcpy, and that writing beyond the end of it is undefined.
865 SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
866 srcAlloca->user_end());
867 while (!srcUseList.empty()) {
868 User *U = srcUseList.pop_back_val();
870 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
871 for (User *UU : U->users())
872 srcUseList.push_back(UU);
875 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
876 if (!G->hasAllZeroIndices())
879 for (User *UU : U->users())
880 srcUseList.push_back(UU);
883 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
884 if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
885 IT->getIntrinsicID() == Intrinsic::lifetime_end)
888 if (U != C && U != cpy)
892 // Check that src isn't captured by the called function since the
893 // transformation can cause aliasing issues in that case.
894 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
895 if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
898 // Since we're changing the parameter to the callsite, we need to make sure
899 // that what would be the new parameter dominates the callsite.
900 DominatorTree &DT = LookupDomTree();
901 if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
902 if (!DT.dominates(cpyDestInst, C))
905 // In addition to knowing that the call does not access src in some
906 // unexpected manner, for example via a global, which we deduce from
907 // the use analysis, we also need to know that it does not sneakily
908 // access dest. We rely on AA to figure this out for us.
909 AliasAnalysis &AA = LookupAliasAnalysis();
910 ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
911 // If necessary, perform additional analysis.
912 if (MR != MRI_NoModRef)
913 MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
914 if (MR != MRI_NoModRef)
917 // All the checks have passed, so do the transformation.
918 bool changedArgument = false;
919 for (unsigned i = 0; i < CS.arg_size(); ++i)
920 if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
921 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
922 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
923 cpyDest->getName(), C);
924 changedArgument = true;
925 if (CS.getArgument(i)->getType() == Dest->getType())
926 CS.setArgument(i, Dest);
928 CS.setArgument(i, CastInst::CreatePointerCast(Dest,
929 CS.getArgument(i)->getType(), Dest->getName(), C));
932 if (!changedArgument)
935 // If the destination wasn't sufficiently aligned then increase its alignment.
936 if (!isDestSufficientlyAligned) {
937 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
938 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
941 // Drop any cached information about the call, because we may have changed
942 // its dependence information by changing its parameter.
943 MD->removeInstruction(C);
945 // Update AA metadata
946 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
947 // handled here, but combineMetadata doesn't support them yet
948 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
949 LLVMContext::MD_noalias,
950 LLVMContext::MD_invariant_group};
951 combineMetadata(C, cpy, KnownIDs);
953 // Remove the memcpy.
954 MD->removeInstruction(cpy);
960 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
961 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
962 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
964 // We can only transforms memcpy's where the dest of one is the source of the
966 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
969 // If dep instruction is reading from our current input, then it is a noop
970 // transfer and substituting the input won't change this instruction. Just
971 // ignore the input and let someone else zap MDep. This handles cases like:
974 if (M->getSource() == MDep->getSource())
977 // Second, the length of the memcpy's must be the same, or the preceding one
978 // must be larger than the following one.
979 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
980 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
981 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
984 AliasAnalysis &AA = LookupAliasAnalysis();
986 // Verify that the copied-from memory doesn't change in between the two
987 // transfers. For example, in:
991 // It would be invalid to transform the second memcpy into memcpy(c <- b).
993 // TODO: If the code between M and MDep is transparent to the destination "c",
994 // then we could still perform the xform by moving M up to the first memcpy.
996 // NOTE: This is conservative, it will stop on any read from the source loc,
997 // not just the defining memcpy.
998 MemDepResult SourceDep =
999 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1000 M->getIterator(), M->getParent());
1001 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1004 // If the dest of the second might alias the source of the first, then the
1005 // source and dest might overlap. We still want to eliminate the intermediate
1006 // value, but we have to generate a memmove instead of memcpy.
1007 bool UseMemMove = false;
1008 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1009 MemoryLocation::getForSource(MDep)))
1012 // If all checks passed, then we can transform M.
1014 // Make sure to use the lesser of the alignment of the source and the dest
1015 // since we're changing where we're reading from, but don't want to increase
1016 // the alignment past what can be read from or written to.
1017 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1018 // example we could be moving from movaps -> movq on x86.
1019 unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
1021 IRBuilder<> Builder(M);
1023 Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
1024 Align, M->isVolatile());
1026 Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
1027 Align, M->isVolatile());
1029 // Remove the instruction we're replacing.
1030 MD->removeInstruction(M);
1031 M->eraseFromParent();
1036 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
1037 /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1038 /// weren't copied over by \p MemCpy.
1040 /// In other words, transform:
1042 /// memset(dst, c, dst_size);
1043 /// memcpy(dst, src, src_size);
1047 /// memcpy(dst, src, src_size);
1048 /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1050 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1051 MemSetInst *MemSet) {
1052 // We can only transform memset/memcpy with the same destination.
1053 if (MemSet->getDest() != MemCpy->getDest())
1056 // Check that there are no other dependencies on the memset destination.
1057 MemDepResult DstDepInfo =
1058 MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1059 MemCpy->getIterator(), MemCpy->getParent());
1060 if (DstDepInfo.getInst() != MemSet)
1063 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1064 Value *Dest = MemCpy->getRawDest();
1065 Value *DestSize = MemSet->getLength();
1066 Value *SrcSize = MemCpy->getLength();
1068 // By default, create an unaligned memset.
1070 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1072 const unsigned DestAlign =
1073 std::max(MemSet->getAlignment(), MemCpy->getAlignment());
1075 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1076 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1078 IRBuilder<> Builder(MemCpy);
1080 // If the sizes have different types, zext the smaller one.
1081 if (DestSize->getType() != SrcSize->getType()) {
1082 if (DestSize->getType()->getIntegerBitWidth() >
1083 SrcSize->getType()->getIntegerBitWidth())
1084 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1086 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1089 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1090 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1091 Value *MemsetLen = Builder.CreateSelect(
1092 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1093 Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1096 MD->removeInstruction(MemSet);
1097 MemSet->eraseFromParent();
1101 /// Transform memcpy to memset when its source was just memset.
1102 /// In other words, turn:
1104 /// memset(dst1, c, dst1_size);
1105 /// memcpy(dst2, dst1, dst2_size);
1109 /// memset(dst1, c, dst1_size);
1110 /// memset(dst2, c, dst2_size);
1112 /// When dst2_size <= dst1_size.
1114 /// The \p MemCpy must have a Constant length.
1115 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1116 MemSetInst *MemSet) {
1117 AliasAnalysis &AA = LookupAliasAnalysis();
1119 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1120 // memcpying from the same address. Otherwise it is hard to reason about.
1121 if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1124 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1125 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1126 // Make sure the memcpy doesn't read any more than what the memset wrote.
1127 // Don't worry about sizes larger than i64.
1128 if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
1131 IRBuilder<> Builder(MemCpy);
1132 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1133 CopySize, MemCpy->getAlignment());
1137 /// Perform simplification of memcpy's. If we have memcpy A
1138 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1139 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1140 /// circumstances). This allows later passes to remove the first memcpy
1142 bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
1143 // We can only optimize non-volatile memcpy's.
1144 if (M->isVolatile()) return false;
1146 // If the source and destination of the memcpy are the same, then zap it.
1147 if (M->getSource() == M->getDest()) {
1148 MD->removeInstruction(M);
1149 M->eraseFromParent();
1153 // If copying from a constant, try to turn the memcpy into a memset.
1154 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
1155 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1156 if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
1157 IRBuilder<> Builder(M);
1158 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1159 M->getAlignment(), false);
1160 MD->removeInstruction(M);
1161 M->eraseFromParent();
1166 MemDepResult DepInfo = MD->getDependency(M);
1168 // Try to turn a partially redundant memset + memcpy into
1169 // memcpy + smaller memset. We don't need the memcpy size for this.
1170 if (DepInfo.isClobber())
1171 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1172 if (processMemSetMemCpyDependence(M, MDep))
1175 // The optimizations after this point require the memcpy size.
1176 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1177 if (!CopySize) return false;
1179 // There are four possible optimizations we can do for memcpy:
1180 // a) memcpy-memcpy xform which exposes redundance for DSE.
1181 // b) call-memcpy xform for return slot optimization.
1182 // c) memcpy from freshly alloca'd space or space that has just started its
1183 // lifetime copies undefined data, and we can therefore eliminate the
1184 // memcpy in favor of the data that was already at the destination.
1185 // d) memcpy from a just-memset'd source can be turned into memset.
1186 if (DepInfo.isClobber()) {
1187 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1188 if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
1189 CopySize->getZExtValue(), M->getAlignment(),
1191 MD->removeInstruction(M);
1192 M->eraseFromParent();
1198 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1199 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1200 SrcLoc, true, M->getIterator(), M->getParent());
1202 if (SrcDepInfo.isClobber()) {
1203 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1204 return processMemCpyMemCpyDependence(M, MDep);
1205 } else if (SrcDepInfo.isDef()) {
1206 Instruction *I = SrcDepInfo.getInst();
1207 bool hasUndefContents = false;
1209 if (isa<AllocaInst>(I)) {
1210 hasUndefContents = true;
1211 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1212 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1213 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1214 if (LTSize->getZExtValue() >= CopySize->getZExtValue())
1215 hasUndefContents = true;
1218 if (hasUndefContents) {
1219 MD->removeInstruction(M);
1220 M->eraseFromParent();
1226 if (SrcDepInfo.isClobber())
1227 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1228 if (performMemCpyToMemSetOptzn(M, MDep)) {
1229 MD->removeInstruction(M);
1230 M->eraseFromParent();
1238 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1240 bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1241 AliasAnalysis &AA = LookupAliasAnalysis();
1243 if (!TLI->has(LibFunc::memmove))
1246 // See if the pointers alias.
1247 if (!AA.isNoAlias(MemoryLocation::getForDest(M),
1248 MemoryLocation::getForSource(M)))
1251 DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1254 // If not, then we know we can transform this.
1255 Type *ArgTys[3] = { M->getRawDest()->getType(),
1256 M->getRawSource()->getType(),
1257 M->getLength()->getType() };
1258 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1259 Intrinsic::memcpy, ArgTys));
1261 // MemDep may have over conservative information about this instruction, just
1262 // conservatively flush it from the cache.
1263 MD->removeInstruction(M);
1269 /// This is called on every byval argument in call sites.
1270 bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
1271 const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
1272 // Find out what feeds this byval argument.
1273 Value *ByValArg = CS.getArgument(ArgNo);
1274 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1275 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1276 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1277 MemoryLocation(ByValArg, ByValSize), true,
1278 CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
1279 if (!DepInfo.isClobber())
1282 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1283 // a memcpy, see if we can byval from the source of the memcpy instead of the
1285 MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1286 if (!MDep || MDep->isVolatile() ||
1287 ByValArg->stripPointerCasts() != MDep->getDest())
1290 // The length of the memcpy must be larger or equal to the size of the byval.
1291 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1292 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1295 // Get the alignment of the byval. If the call doesn't specify the alignment,
1296 // then it is some target specific value that we can't know.
1297 unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
1298 if (ByValAlign == 0) return false;
1300 // If it is greater than the memcpy, then we check to see if we can force the
1301 // source of the memcpy to the alignment we need. If we fail, we bail out.
1302 AssumptionCache &AC = LookupAssumptionCache();
1303 DominatorTree &DT = LookupDomTree();
1304 if (MDep->getAlignment() < ByValAlign &&
1305 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1306 CS.getInstruction(), &AC, &DT) < ByValAlign)
1309 // Verify that the copied-from memory doesn't change in between the memcpy and
1314 // It would be invalid to transform the second memcpy into foo(*b).
1316 // NOTE: This is conservative, it will stop on any read from the source loc,
1317 // not just the defining memcpy.
1318 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1319 MemoryLocation::getForSource(MDep), false,
1320 CS.getInstruction()->getIterator(), MDep->getParent());
1321 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1324 Value *TmpCast = MDep->getSource();
1325 if (MDep->getSource()->getType() != ByValArg->getType())
1326 TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1327 "tmpcast", CS.getInstruction());
1329 DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1330 << " " << *MDep << "\n"
1331 << " " << *CS.getInstruction() << "\n");
1333 // Otherwise we're good! Update the byval argument.
1334 CS.setArgument(ArgNo, TmpCast);
1339 /// Executes one iteration of MemCpyOptPass.
1340 bool MemCpyOptPass::iterateOnFunction(Function &F) {
1341 bool MadeChange = false;
1343 // Walk all instruction in the function.
1344 for (BasicBlock &BB : F) {
1345 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
1346 // Avoid invalidating the iterator.
1347 Instruction *I = &*BI++;
1349 bool RepeatInstruction = false;
1351 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1352 MadeChange |= processStore(SI, BI);
1353 else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1354 RepeatInstruction = processMemSet(M, BI);
1355 else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1356 RepeatInstruction = processMemCpy(M);
1357 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1358 RepeatInstruction = processMemMove(M);
1359 else if (auto CS = CallSite(I)) {
1360 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
1361 if (CS.isByValArgument(i))
1362 MadeChange |= processByValArgument(CS, i);
1365 // Reprocess the instruction if desired.
1366 if (RepeatInstruction) {
1367 if (BI != BB.begin())
1377 PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1379 auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1380 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1382 auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1383 return AM.getResult<AAManager>(F);
1385 auto LookupAssumptionCache = [&]() -> AssumptionCache & {
1386 return AM.getResult<AssumptionAnalysis>(F);
1388 auto LookupDomTree = [&]() -> DominatorTree & {
1389 return AM.getResult<DominatorTreeAnalysis>(F);
1392 bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
1393 LookupAssumptionCache, LookupDomTree);
1395 return PreservedAnalyses::all();
1396 PreservedAnalyses PA;
1397 PA.preserve<GlobalsAA>();
1398 PA.preserve<MemoryDependenceAnalysis>();
1402 bool MemCpyOptPass::runImpl(
1403 Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
1404 std::function<AliasAnalysis &()> LookupAliasAnalysis_,
1405 std::function<AssumptionCache &()> LookupAssumptionCache_,
1406 std::function<DominatorTree &()> LookupDomTree_) {
1407 bool MadeChange = false;
1410 LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
1411 LookupAssumptionCache = std::move(LookupAssumptionCache_);
1412 LookupDomTree = std::move(LookupDomTree_);
1414 // If we don't have at least memset and memcpy, there is little point of doing
1415 // anything here. These are required by a freestanding implementation, so if
1416 // even they are disabled, there is no point in trying hard.
1417 if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
1421 if (!iterateOnFunction(F))
1430 /// This is the main transformation entry point for a function.
1431 bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1432 if (skipFunction(F))
1435 auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1436 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1438 auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1439 return getAnalysis<AAResultsWrapperPass>().getAAResults();
1441 auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
1442 return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1444 auto LookupDomTree = [this]() -> DominatorTree & {
1445 return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1448 return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,