LLVM  mainline
MemCpyOptimizer.cpp
Go to the documentation of this file.
00001 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs various transformations related to eliminating memcpy
00011 // calls, or transforming sets of stores into memset's.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Scalar.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/Analysis/AliasAnalysis.h"
00019 #include "llvm/Analysis/AssumptionCache.h"
00020 #include "llvm/Analysis/GlobalsModRef.h"
00021 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00022 #include "llvm/Analysis/TargetLibraryInfo.h"
00023 #include "llvm/Analysis/ValueTracking.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/Dominators.h"
00026 #include "llvm/IR/GetElementPtrTypeIterator.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/IRBuilder.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include "llvm/Transforms/Utils/Local.h"
00034 #include <algorithm>
00035 using namespace llvm;
00036 
00037 #define DEBUG_TYPE "memcpyopt"
00038 
00039 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
00040 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
00041 STATISTIC(NumMoveToCpy,   "Number of memmoves converted to memcpy");
00042 STATISTIC(NumCpyToSet,    "Number of memcpys converted to memset");
00043 
00044 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
00045                                   bool &VariableIdxFound,
00046                                   const DataLayout &DL) {
00047   // Skip over the first indices.
00048   gep_type_iterator GTI = gep_type_begin(GEP);
00049   for (unsigned i = 1; i != Idx; ++i, ++GTI)
00050     /*skip along*/;
00051 
00052   // Compute the offset implied by the rest of the indices.
00053   int64_t Offset = 0;
00054   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
00055     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
00056     if (!OpC)
00057       return VariableIdxFound = true;
00058     if (OpC->isZero()) continue;  // No offset.
00059 
00060     // Handle struct indices, which add their field offset to the pointer.
00061     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00062       Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
00063       continue;
00064     }
00065 
00066     // Otherwise, we have a sequential type like an array or vector.  Multiply
00067     // the index by the ElementSize.
00068     uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
00069     Offset += Size*OpC->getSExtValue();
00070   }
00071 
00072   return Offset;
00073 }
00074 
00075 /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
00076 /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
00077 /// might be &A[40]. In this case offset would be -8.
00078 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
00079                             const DataLayout &DL) {
00080   Ptr1 = Ptr1->stripPointerCasts();
00081   Ptr2 = Ptr2->stripPointerCasts();
00082 
00083   // Handle the trivial case first.
00084   if (Ptr1 == Ptr2) {
00085     Offset = 0;
00086     return true;
00087   }
00088 
00089   GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
00090   GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
00091 
00092   bool VariableIdxFound = false;
00093 
00094   // If one pointer is a GEP and the other isn't, then see if the GEP is a
00095   // constant offset from the base, as in "P" and "gep P, 1".
00096   if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
00097     Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
00098     return !VariableIdxFound;
00099   }
00100 
00101   if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
00102     Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
00103     return !VariableIdxFound;
00104   }
00105 
00106   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
00107   // base.  After that base, they may have some number of common (and
00108   // potentially variable) indices.  After that they handle some constant
00109   // offset, which determines their offset from each other.  At this point, we
00110   // handle no other case.
00111   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
00112     return false;
00113 
00114   // Skip any common indices and track the GEP types.
00115   unsigned Idx = 1;
00116   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
00117     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
00118       break;
00119 
00120   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
00121   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
00122   if (VariableIdxFound) return false;
00123 
00124   Offset = Offset2-Offset1;
00125   return true;
00126 }
00127 
00128 
00129 /// Represents a range of memset'd bytes with the ByteVal value.
00130 /// This allows us to analyze stores like:
00131 ///   store 0 -> P+1
00132 ///   store 0 -> P+0
00133 ///   store 0 -> P+3
00134 ///   store 0 -> P+2
00135 /// which sometimes happens with stores to arrays of structs etc.  When we see
00136 /// the first store, we make a range [1, 2).  The second store extends the range
00137 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
00138 /// two ranges into [0, 3) which is memset'able.
00139 namespace {
00140 struct MemsetRange {
00141   // Start/End - A semi range that describes the span that this range covers.
00142   // The range is closed at the start and open at the end: [Start, End).
00143   int64_t Start, End;
00144 
00145   /// StartPtr - The getelementptr instruction that points to the start of the
00146   /// range.
00147   Value *StartPtr;
00148 
00149   /// Alignment - The known alignment of the first store.
00150   unsigned Alignment;
00151 
00152   /// TheStores - The actual stores that make up this range.
00153   SmallVector<Instruction*, 16> TheStores;
00154 
00155   bool isProfitableToUseMemset(const DataLayout &DL) const;
00156 };
00157 } // end anon namespace
00158 
00159 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
00160   // If we found more than 4 stores to merge or 16 bytes, use memset.
00161   if (TheStores.size() >= 4 || End-Start >= 16) return true;
00162 
00163   // If there is nothing to merge, don't do anything.
00164   if (TheStores.size() < 2) return false;
00165 
00166   // If any of the stores are a memset, then it is always good to extend the
00167   // memset.
00168   for (Instruction *SI : TheStores)
00169     if (!isa<StoreInst>(SI))
00170       return true;
00171 
00172   // Assume that the code generator is capable of merging pairs of stores
00173   // together if it wants to.
00174   if (TheStores.size() == 2) return false;
00175 
00176   // If we have fewer than 8 stores, it can still be worthwhile to do this.
00177   // For example, merging 4 i8 stores into an i32 store is useful almost always.
00178   // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
00179   // memset will be split into 2 32-bit stores anyway) and doing so can
00180   // pessimize the llvm optimizer.
00181   //
00182   // Since we don't have perfect knowledge here, make some assumptions: assume
00183   // the maximum GPR width is the same size as the largest legal integer
00184   // size. If so, check to see whether we will end up actually reducing the
00185   // number of stores used.
00186   unsigned Bytes = unsigned(End-Start);
00187   unsigned MaxIntSize = DL.getLargestLegalIntTypeSize();
00188   if (MaxIntSize == 0)
00189     MaxIntSize = 1;
00190   unsigned NumPointerStores = Bytes / MaxIntSize;
00191 
00192   // Assume the remaining bytes if any are done a byte at a time.
00193   unsigned NumByteStores = Bytes % MaxIntSize;
00194 
00195   // If we will reduce the # stores (according to this heuristic), do the
00196   // transformation.  This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
00197   // etc.
00198   return TheStores.size() > NumPointerStores+NumByteStores;
00199 }
00200 
00201 
00202 namespace {
00203 class MemsetRanges {
00204   /// A sorted list of the memset ranges.
00205   SmallVector<MemsetRange, 8> Ranges;
00206   typedef SmallVectorImpl<MemsetRange>::iterator range_iterator;
00207   const DataLayout &DL;
00208 public:
00209   MemsetRanges(const DataLayout &DL) : DL(DL) {}
00210 
00211   typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator;
00212   const_iterator begin() const { return Ranges.begin(); }
00213   const_iterator end() const { return Ranges.end(); }
00214   bool empty() const { return Ranges.empty(); }
00215 
00216   void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
00217     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00218       addStore(OffsetFromFirst, SI);
00219     else
00220       addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
00221   }
00222 
00223   void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
00224     int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
00225 
00226     addRange(OffsetFromFirst, StoreSize,
00227              SI->getPointerOperand(), SI->getAlignment(), SI);
00228   }
00229 
00230   void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
00231     int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
00232     addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI);
00233   }
00234 
00235   void addRange(int64_t Start, int64_t Size, Value *Ptr,
00236                 unsigned Alignment, Instruction *Inst);
00237 
00238 };
00239 
00240 } // end anon namespace
00241 
00242 
00243 /// Add a new store to the MemsetRanges data structure.  This adds a
00244 /// new range for the specified store at the specified offset, merging into
00245 /// existing ranges as appropriate.
00246 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
00247                             unsigned Alignment, Instruction *Inst) {
00248   int64_t End = Start+Size;
00249 
00250   range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
00251     [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
00252 
00253   // We now know that I == E, in which case we didn't find anything to merge
00254   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
00255   // to insert a new range.  Handle this now.
00256   if (I == Ranges.end() || End < I->Start) {
00257     MemsetRange &R = *Ranges.insert(I, MemsetRange());
00258     R.Start        = Start;
00259     R.End          = End;
00260     R.StartPtr     = Ptr;
00261     R.Alignment    = Alignment;
00262     R.TheStores.push_back(Inst);
00263     return;
00264   }
00265 
00266   // This store overlaps with I, add it.
00267   I->TheStores.push_back(Inst);
00268 
00269   // At this point, we may have an interval that completely contains our store.
00270   // If so, just add it to the interval and return.
00271   if (I->Start <= Start && I->End >= End)
00272     return;
00273 
00274   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
00275   // but is not entirely contained within the range.
00276 
00277   // See if the range extends the start of the range.  In this case, it couldn't
00278   // possibly cause it to join the prior range, because otherwise we would have
00279   // stopped on *it*.
00280   if (Start < I->Start) {
00281     I->Start = Start;
00282     I->StartPtr = Ptr;
00283     I->Alignment = Alignment;
00284   }
00285 
00286   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
00287   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
00288   // End.
00289   if (End > I->End) {
00290     I->End = End;
00291     range_iterator NextI = I;
00292     while (++NextI != Ranges.end() && End >= NextI->Start) {
00293       // Merge the range in.
00294       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
00295       if (NextI->End > I->End)
00296         I->End = NextI->End;
00297       Ranges.erase(NextI);
00298       NextI = I;
00299     }
00300   }
00301 }
00302 
00303 //===----------------------------------------------------------------------===//
00304 //                         MemCpyOpt Pass
00305 //===----------------------------------------------------------------------===//
00306 
00307 namespace {
00308   class MemCpyOpt : public FunctionPass {
00309     MemoryDependenceAnalysis *MD;
00310     TargetLibraryInfo *TLI;
00311   public:
00312     static char ID; // Pass identification, replacement for typeid
00313     MemCpyOpt() : FunctionPass(ID) {
00314       initializeMemCpyOptPass(*PassRegistry::getPassRegistry());
00315       MD = nullptr;
00316       TLI = nullptr;
00317     }
00318 
00319     bool runOnFunction(Function &F) override;
00320 
00321   private:
00322     // This transformation requires dominator postdominator info
00323     void getAnalysisUsage(AnalysisUsage &AU) const override {
00324       AU.setPreservesCFG();
00325       AU.addRequired<AssumptionCacheTracker>();
00326       AU.addRequired<DominatorTreeWrapperPass>();
00327       AU.addRequired<MemoryDependenceAnalysis>();
00328       AU.addRequired<AAResultsWrapperPass>();
00329       AU.addRequired<TargetLibraryInfoWrapperPass>();
00330       AU.addPreserved<GlobalsAAWrapperPass>();
00331       AU.addPreserved<MemoryDependenceAnalysis>();
00332     }
00333 
00334     // Helper functions
00335     bool processStore(StoreInst *SI, BasicBlock::iterator &BBI);
00336     bool processMemSet(MemSetInst *SI, BasicBlock::iterator &BBI);
00337     bool processMemCpy(MemCpyInst *M);
00338     bool processMemMove(MemMoveInst *M);
00339     bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc,
00340                               uint64_t cpyLen, unsigned cpyAlign, CallInst *C);
00341     bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep);
00342     bool processMemSetMemCpyDependence(MemCpyInst *M, MemSetInst *MDep);
00343     bool performMemCpyToMemSetOptzn(MemCpyInst *M, MemSetInst *MDep);
00344     bool processByValArgument(CallSite CS, unsigned ArgNo);
00345     Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr,
00346                                       Value *ByteVal);
00347 
00348     bool iterateOnFunction(Function &F);
00349   };
00350 
00351   char MemCpyOpt::ID = 0;
00352 }
00353 
00354 /// The public interface to this file...
00355 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); }
00356 
00357 INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00358                       false, false)
00359 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00360 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00361 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00362 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00363 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
00364 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
00365 INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization",
00366                     false, false)
00367 
00368 /// When scanning forward over instructions, we look for some other patterns to
00369 /// fold away. In particular, this looks for stores to neighboring locations of
00370 /// memory. If it sees enough consecutive ones, it attempts to merge them
00371 /// together into a memcpy/memset.
00372 Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst,
00373                                              Value *StartPtr, Value *ByteVal) {
00374   const DataLayout &DL = StartInst->getModule()->getDataLayout();
00375 
00376   // Okay, so we now have a single store that can be splatable.  Scan to find
00377   // all subsequent stores of the same value to offset from the same pointer.
00378   // Join these together into ranges, so we can decide whether contiguous blocks
00379   // are stored.
00380   MemsetRanges Ranges(DL);
00381 
00382   BasicBlock::iterator BI(StartInst);
00383   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
00384     if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
00385       // If the instruction is readnone, ignore it, otherwise bail out.  We
00386       // don't even allow readonly here because we don't want something like:
00387       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
00388       if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
00389         break;
00390       continue;
00391     }
00392 
00393     if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
00394       // If this is a store, see if we can merge it in.
00395       if (!NextStore->isSimple()) break;
00396 
00397       // Check to see if this stored value is of the same byte-splattable value.
00398       if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
00399         break;
00400 
00401       // Check to see if this store is to a constant offset from the start ptr.
00402       int64_t Offset;
00403       if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
00404                            DL))
00405         break;
00406 
00407       Ranges.addStore(Offset, NextStore);
00408     } else {
00409       MemSetInst *MSI = cast<MemSetInst>(BI);
00410 
00411       if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
00412           !isa<ConstantInt>(MSI->getLength()))
00413         break;
00414 
00415       // Check to see if this store is to a constant offset from the start ptr.
00416       int64_t Offset;
00417       if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
00418         break;
00419 
00420       Ranges.addMemSet(Offset, MSI);
00421     }
00422   }
00423 
00424   // If we have no ranges, then we just had a single store with nothing that
00425   // could be merged in.  This is a very common case of course.
00426   if (Ranges.empty())
00427     return nullptr;
00428 
00429   // If we had at least one store that could be merged in, add the starting
00430   // store as well.  We try to avoid this unless there is at least something
00431   // interesting as a small compile-time optimization.
00432   Ranges.addInst(0, StartInst);
00433 
00434   // If we create any memsets, we put it right before the first instruction that
00435   // isn't part of the memset block.  This ensure that the memset is dominated
00436   // by any addressing instruction needed by the start of the block.
00437   IRBuilder<> Builder(&*BI);
00438 
00439   // Now that we have full information about ranges, loop over the ranges and
00440   // emit memset's for anything big enough to be worthwhile.
00441   Instruction *AMemSet = nullptr;
00442   for (const MemsetRange &Range : Ranges) {
00443 
00444     if (Range.TheStores.size() == 1) continue;
00445 
00446     // If it is profitable to lower this range to memset, do so now.
00447     if (!Range.isProfitableToUseMemset(DL))
00448       continue;
00449 
00450     // Otherwise, we do want to transform this!  Create a new memset.
00451     // Get the starting pointer of the block.
00452     StartPtr = Range.StartPtr;
00453 
00454     // Determine alignment
00455     unsigned Alignment = Range.Alignment;
00456     if (Alignment == 0) {
00457       Type *EltType =
00458         cast<PointerType>(StartPtr->getType())->getElementType();
00459       Alignment = DL.getABITypeAlignment(EltType);
00460     }
00461 
00462     AMemSet =
00463       Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
00464 
00465     DEBUG(dbgs() << "Replace stores:\n";
00466           for (Instruction *SI : Range.TheStores)
00467             dbgs() << *SI << '\n';
00468           dbgs() << "With: " << *AMemSet << '\n');
00469 
00470     if (!Range.TheStores.empty())
00471       AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
00472 
00473     // Zap all the stores.
00474     for (Instruction *SI : Range.TheStores) {
00475       MD->removeInstruction(SI);
00476       SI->eraseFromParent();
00477     }
00478     ++NumMemSetInfer;
00479   }
00480 
00481   return AMemSet;
00482 }
00483 
00484 static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
00485                                      const LoadInst *LI) {
00486   unsigned StoreAlign = SI->getAlignment();
00487   if (!StoreAlign)
00488     StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
00489   unsigned LoadAlign = LI->getAlignment();
00490   if (!LoadAlign)
00491     LoadAlign = DL.getABITypeAlignment(LI->getType());
00492 
00493   return std::min(StoreAlign, LoadAlign);
00494 }
00495 
00496 bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
00497   if (!SI->isSimple()) return false;
00498 
00499   // Avoid merging nontemporal stores since the resulting
00500   // memcpy/memset would not be able to preserve the nontemporal hint.
00501   // In theory we could teach how to propagate the !nontemporal metadata to
00502   // memset calls. However, that change would force the backend to
00503   // conservatively expand !nontemporal memset calls back to sequences of
00504   // store instructions (effectively undoing the merging).
00505   if (SI->getMetadata(LLVMContext::MD_nontemporal))
00506     return false;
00507 
00508   const DataLayout &DL = SI->getModule()->getDataLayout();
00509 
00510   // Load to store forwarding can be interpreted as memcpy.
00511   if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
00512     if (LI->isSimple() && LI->hasOneUse() &&
00513         LI->getParent() == SI->getParent()) {
00514 
00515       auto *T = LI->getType();
00516       if (T->isAggregateType()) {
00517         AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
00518         MemoryLocation LoadLoc = MemoryLocation::get(LI);
00519 
00520         // We use alias analysis to check if an instruction may store to
00521         // the memory we load from in between the load and the store. If
00522         // such an instruction is found, we try to promote there instead
00523         // of at the store position.
00524         Instruction *P = SI;
00525         for (BasicBlock::iterator I = ++LI->getIterator(), E = SI->getIterator();
00526              I != E; ++I) {
00527           if (!(AA.getModRefInfo(&*I, LoadLoc) & MRI_Mod))
00528             continue;
00529 
00530           // We found an instruction that may write to the loaded memory.
00531           // We can try to promote at this position instead of the store
00532           // position if nothing alias the store memory after this and the store
00533           // destination is not in the range.
00534           P = &*I;
00535           for (; I != E; ++I) {
00536             MemoryLocation StoreLoc = MemoryLocation::get(SI);
00537             if (&*I == SI->getOperand(1) ||
00538                 AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
00539               P = nullptr;
00540               break;
00541             }
00542           }
00543 
00544           break;
00545         }
00546 
00547         // If a valid insertion position is found, then we can promote
00548         // the load/store pair to a memcpy.
00549         if (P) {
00550           // If we load from memory that may alias the memory we store to,
00551           // memmove must be used to preserve semantic. If not, memcpy can
00552           // be used.
00553           bool UseMemMove = false;
00554           if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
00555             UseMemMove = true;
00556 
00557           unsigned Align = findCommonAlignment(DL, SI, LI);
00558           uint64_t Size = DL.getTypeStoreSize(T);
00559 
00560           IRBuilder<> Builder(P);
00561           Instruction *M;
00562           if (UseMemMove)
00563             M = Builder.CreateMemMove(SI->getPointerOperand(),
00564                                       LI->getPointerOperand(), Size,
00565                                       Align, SI->isVolatile());
00566           else
00567             M = Builder.CreateMemCpy(SI->getPointerOperand(),
00568                                      LI->getPointerOperand(), Size,
00569                                      Align, SI->isVolatile());
00570 
00571           DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI
00572                        << " => " << *M << "\n");
00573 
00574           MD->removeInstruction(SI);
00575           SI->eraseFromParent();
00576           MD->removeInstruction(LI);
00577           LI->eraseFromParent();
00578           ++NumMemCpyInstr;
00579 
00580           // Make sure we do not invalidate the iterator.
00581           BBI = M->getIterator();
00582           return true;
00583         }
00584       }
00585 
00586       // Detect cases where we're performing call slot forwarding, but
00587       // happen to be using a load-store pair to implement it, rather than
00588       // a memcpy.
00589       MemDepResult ldep = MD->getDependency(LI);
00590       CallInst *C = nullptr;
00591       if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
00592         C = dyn_cast<CallInst>(ldep.getInst());
00593 
00594       if (C) {
00595         // Check that nothing touches the dest of the "copy" between
00596         // the call and the store.
00597         AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
00598         MemoryLocation StoreLoc = MemoryLocation::get(SI);
00599         for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
00600              I != E; --I) {
00601           if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) {
00602             C = nullptr;
00603             break;
00604           }
00605         }
00606       }
00607 
00608       if (C) {
00609         bool changed = performCallSlotOptzn(
00610             LI, SI->getPointerOperand()->stripPointerCasts(),
00611             LI->getPointerOperand()->stripPointerCasts(),
00612             DL.getTypeStoreSize(SI->getOperand(0)->getType()),
00613             findCommonAlignment(DL, SI, LI), C);
00614         if (changed) {
00615           MD->removeInstruction(SI);
00616           SI->eraseFromParent();
00617           MD->removeInstruction(LI);
00618           LI->eraseFromParent();
00619           ++NumMemCpyInstr;
00620           return true;
00621         }
00622       }
00623     }
00624   }
00625 
00626   // There are two cases that are interesting for this code to handle: memcpy
00627   // and memset.  Right now we only handle memset.
00628 
00629   // Ensure that the value being stored is something that can be memset'able a
00630   // byte at a time like "0" or "-1" or any width, as well as things like
00631   // 0xA0A0A0A0 and 0.0.
00632   auto *V = SI->getOperand(0);
00633   if (Value *ByteVal = isBytewiseValue(V)) {
00634     if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
00635                                               ByteVal)) {
00636       BBI = I->getIterator(); // Don't invalidate iterator.
00637       return true;
00638     }
00639 
00640     // If we have an aggregate, we try to promote it to memset regardless
00641     // of opportunity for merging as it can expose optimization opportunities
00642     // in subsequent passes.
00643     auto *T = V->getType();
00644     if (T->isAggregateType()) {
00645       uint64_t Size = DL.getTypeStoreSize(T);
00646       unsigned Align = SI->getAlignment();
00647       if (!Align)
00648         Align = DL.getABITypeAlignment(T);
00649       IRBuilder<> Builder(SI);
00650       auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
00651                                      Size, Align, SI->isVolatile());
00652 
00653       DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
00654 
00655       MD->removeInstruction(SI);
00656       SI->eraseFromParent();
00657       NumMemSetInfer++;
00658 
00659       // Make sure we do not invalidate the iterator.
00660       BBI = M->getIterator();
00661       return true;
00662     }
00663   }
00664 
00665   return false;
00666 }
00667 
00668 bool MemCpyOpt::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
00669   // See if there is another memset or store neighboring this memset which
00670   // allows us to widen out the memset to do a single larger store.
00671   if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
00672     if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
00673                                               MSI->getValue())) {
00674       BBI = I->getIterator(); // Don't invalidate iterator.
00675       return true;
00676     }
00677   return false;
00678 }
00679 
00680 
00681 /// Takes a memcpy and a call that it depends on,
00682 /// and checks for the possibility of a call slot optimization by having
00683 /// the call write its result directly into the destination of the memcpy.
00684 bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
00685                                      Value *cpyDest, Value *cpySrc,
00686                                      uint64_t cpyLen, unsigned cpyAlign,
00687                                      CallInst *C) {
00688   // The general transformation to keep in mind is
00689   //
00690   //   call @func(..., src, ...)
00691   //   memcpy(dest, src, ...)
00692   //
00693   // ->
00694   //
00695   //   memcpy(dest, src, ...)
00696   //   call @func(..., dest, ...)
00697   //
00698   // Since moving the memcpy is technically awkward, we additionally check that
00699   // src only holds uninitialized values at the moment of the call, meaning that
00700   // the memcpy can be discarded rather than moved.
00701 
00702   // Deliberately get the source and destination with bitcasts stripped away,
00703   // because we'll need to do type comparisons based on the underlying type.
00704   CallSite CS(C);
00705 
00706   // Require that src be an alloca.  This simplifies the reasoning considerably.
00707   AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
00708   if (!srcAlloca)
00709     return false;
00710 
00711   ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
00712   if (!srcArraySize)
00713     return false;
00714 
00715   const DataLayout &DL = cpy->getModule()->getDataLayout();
00716   uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
00717                      srcArraySize->getZExtValue();
00718 
00719   if (cpyLen < srcSize)
00720     return false;
00721 
00722   // Check that accessing the first srcSize bytes of dest will not cause a
00723   // trap.  Otherwise the transform is invalid since it might cause a trap
00724   // to occur earlier than it otherwise would.
00725   if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
00726     // The destination is an alloca.  Check it is larger than srcSize.
00727     ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
00728     if (!destArraySize)
00729       return false;
00730 
00731     uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
00732                         destArraySize->getZExtValue();
00733 
00734     if (destSize < srcSize)
00735       return false;
00736   } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
00737     if (A->getDereferenceableBytes() < srcSize) {
00738       // If the destination is an sret parameter then only accesses that are
00739       // outside of the returned struct type can trap.
00740       if (!A->hasStructRetAttr())
00741         return false;
00742 
00743       Type *StructTy = cast<PointerType>(A->getType())->getElementType();
00744       if (!StructTy->isSized()) {
00745         // The call may never return and hence the copy-instruction may never
00746         // be executed, and therefore it's not safe to say "the destination
00747         // has at least <cpyLen> bytes, as implied by the copy-instruction",
00748         return false;
00749       }
00750 
00751       uint64_t destSize = DL.getTypeAllocSize(StructTy);
00752       if (destSize < srcSize)
00753         return false;
00754     }
00755   } else {
00756     return false;
00757   }
00758 
00759   // Check that dest points to memory that is at least as aligned as src.
00760   unsigned srcAlign = srcAlloca->getAlignment();
00761   if (!srcAlign)
00762     srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
00763   bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
00764   // If dest is not aligned enough and we can't increase its alignment then
00765   // bail out.
00766   if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
00767     return false;
00768 
00769   // Check that src is not accessed except via the call and the memcpy.  This
00770   // guarantees that it holds only undefined values when passed in (so the final
00771   // memcpy can be dropped), that it is not read or written between the call and
00772   // the memcpy, and that writing beyond the end of it is undefined.
00773   SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
00774                                    srcAlloca->user_end());
00775   while (!srcUseList.empty()) {
00776     User *U = srcUseList.pop_back_val();
00777 
00778     if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
00779       for (User *UU : U->users())
00780         srcUseList.push_back(UU);
00781       continue;
00782     }
00783     if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
00784       if (!G->hasAllZeroIndices())
00785         return false;
00786 
00787       for (User *UU : U->users())
00788         srcUseList.push_back(UU);
00789       continue;
00790     }
00791     if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
00792       if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
00793           IT->getIntrinsicID() == Intrinsic::lifetime_end)
00794         continue;
00795 
00796     if (U != C && U != cpy)
00797       return false;
00798   }
00799 
00800   // Check that src isn't captured by the called function since the
00801   // transformation can cause aliasing issues in that case.
00802   for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
00803     if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
00804       return false;
00805 
00806   // Since we're changing the parameter to the callsite, we need to make sure
00807   // that what would be the new parameter dominates the callsite.
00808   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00809   if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
00810     if (!DT.dominates(cpyDestInst, C))
00811       return false;
00812 
00813   // In addition to knowing that the call does not access src in some
00814   // unexpected manner, for example via a global, which we deduce from
00815   // the use analysis, we also need to know that it does not sneakily
00816   // access dest.  We rely on AA to figure this out for us.
00817   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
00818   ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
00819   // If necessary, perform additional analysis.
00820   if (MR != MRI_NoModRef)
00821     MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
00822   if (MR != MRI_NoModRef)
00823     return false;
00824 
00825   // All the checks have passed, so do the transformation.
00826   bool changedArgument = false;
00827   for (unsigned i = 0; i < CS.arg_size(); ++i)
00828     if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
00829       Value *Dest = cpySrc->getType() == cpyDest->getType() ?  cpyDest
00830         : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
00831                                       cpyDest->getName(), C);
00832       changedArgument = true;
00833       if (CS.getArgument(i)->getType() == Dest->getType())
00834         CS.setArgument(i, Dest);
00835       else
00836         CS.setArgument(i, CastInst::CreatePointerCast(Dest,
00837                           CS.getArgument(i)->getType(), Dest->getName(), C));
00838     }
00839 
00840   if (!changedArgument)
00841     return false;
00842 
00843   // If the destination wasn't sufficiently aligned then increase its alignment.
00844   if (!isDestSufficientlyAligned) {
00845     assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
00846     cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
00847   }
00848 
00849   // Drop any cached information about the call, because we may have changed
00850   // its dependence information by changing its parameter.
00851   MD->removeInstruction(C);
00852 
00853   // Update AA metadata
00854   // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
00855   // handled here, but combineMetadata doesn't support them yet
00856   unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
00857                          LLVMContext::MD_noalias,
00858                          LLVMContext::MD_invariant_group};
00859   combineMetadata(C, cpy, KnownIDs);
00860 
00861   // Remove the memcpy.
00862   MD->removeInstruction(cpy);
00863   ++NumMemCpyInstr;
00864 
00865   return true;
00866 }
00867 
00868 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
00869 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
00870 bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep) {
00871   // We can only transforms memcpy's where the dest of one is the source of the
00872   // other.
00873   if (M->getSource() != MDep->getDest() || MDep->isVolatile())
00874     return false;
00875 
00876   // If dep instruction is reading from our current input, then it is a noop
00877   // transfer and substituting the input won't change this instruction.  Just
00878   // ignore the input and let someone else zap MDep.  This handles cases like:
00879   //    memcpy(a <- a)
00880   //    memcpy(b <- a)
00881   if (M->getSource() == MDep->getSource())
00882     return false;
00883 
00884   // Second, the length of the memcpy's must be the same, or the preceding one
00885   // must be larger than the following one.
00886   ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
00887   ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
00888   if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
00889     return false;
00890 
00891   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
00892 
00893   // Verify that the copied-from memory doesn't change in between the two
00894   // transfers.  For example, in:
00895   //    memcpy(a <- b)
00896   //    *b = 42;
00897   //    memcpy(c <- a)
00898   // It would be invalid to transform the second memcpy into memcpy(c <- b).
00899   //
00900   // TODO: If the code between M and MDep is transparent to the destination "c",
00901   // then we could still perform the xform by moving M up to the first memcpy.
00902   //
00903   // NOTE: This is conservative, it will stop on any read from the source loc,
00904   // not just the defining memcpy.
00905   MemDepResult SourceDep =
00906       MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
00907                                    M->getIterator(), M->getParent());
00908   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
00909     return false;
00910 
00911   // If the dest of the second might alias the source of the first, then the
00912   // source and dest might overlap.  We still want to eliminate the intermediate
00913   // value, but we have to generate a memmove instead of memcpy.
00914   bool UseMemMove = false;
00915   if (!AA.isNoAlias(MemoryLocation::getForDest(M),
00916                     MemoryLocation::getForSource(MDep)))
00917     UseMemMove = true;
00918 
00919   // If all checks passed, then we can transform M.
00920 
00921   // Make sure to use the lesser of the alignment of the source and the dest
00922   // since we're changing where we're reading from, but don't want to increase
00923   // the alignment past what can be read from or written to.
00924   // TODO: Is this worth it if we're creating a less aligned memcpy? For
00925   // example we could be moving from movaps -> movq on x86.
00926   unsigned Align = std::min(MDep->getAlignment(), M->getAlignment());
00927 
00928   IRBuilder<> Builder(M);
00929   if (UseMemMove)
00930     Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00931                           Align, M->isVolatile());
00932   else
00933     Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(),
00934                          Align, M->isVolatile());
00935 
00936   // Remove the instruction we're replacing.
00937   MD->removeInstruction(M);
00938   M->eraseFromParent();
00939   ++NumMemCpyInstr;
00940   return true;
00941 }
00942 
00943 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
00944 /// \p MemSet.  Try to simplify \p MemSet to only set the trailing bytes that
00945 /// weren't copied over by \p MemCpy.
00946 ///
00947 /// In other words, transform:
00948 /// \code
00949 ///   memset(dst, c, dst_size);
00950 ///   memcpy(dst, src, src_size);
00951 /// \endcode
00952 /// into:
00953 /// \code
00954 ///   memcpy(dst, src, src_size);
00955 ///   memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
00956 /// \endcode
00957 bool MemCpyOpt::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
00958                                               MemSetInst *MemSet) {
00959   // We can only transform memset/memcpy with the same destination.
00960   if (MemSet->getDest() != MemCpy->getDest())
00961     return false;
00962 
00963   // Check that there are no other dependencies on the memset destination.
00964   MemDepResult DstDepInfo =
00965       MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
00966                                    MemCpy->getIterator(), MemCpy->getParent());
00967   if (DstDepInfo.getInst() != MemSet)
00968     return false;
00969 
00970   // Use the same i8* dest as the memcpy, killing the memset dest if different.
00971   Value *Dest = MemCpy->getRawDest();
00972   Value *DestSize = MemSet->getLength();
00973   Value *SrcSize = MemCpy->getLength();
00974 
00975   // By default, create an unaligned memset.
00976   unsigned Align = 1;
00977   // If Dest is aligned, and SrcSize is constant, use the minimum alignment
00978   // of the sum.
00979   const unsigned DestAlign =
00980       std::max(MemSet->getAlignment(), MemCpy->getAlignment());
00981   if (DestAlign > 1)
00982     if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
00983       Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
00984 
00985   IRBuilder<> Builder(MemCpy);
00986 
00987   // If the sizes have different types, zext the smaller one.
00988   if (DestSize->getType() != SrcSize->getType()) {
00989     if (DestSize->getType()->getIntegerBitWidth() >
00990         SrcSize->getType()->getIntegerBitWidth())
00991       SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
00992     else
00993       DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
00994   }
00995 
00996   Value *MemsetLen =
00997       Builder.CreateSelect(Builder.CreateICmpULE(DestSize, SrcSize),
00998                            ConstantInt::getNullValue(DestSize->getType()),
00999                            Builder.CreateSub(DestSize, SrcSize));
01000   Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
01001                        MemsetLen, Align);
01002 
01003   MD->removeInstruction(MemSet);
01004   MemSet->eraseFromParent();
01005   return true;
01006 }
01007 
01008 /// Transform memcpy to memset when its source was just memset.
01009 /// In other words, turn:
01010 /// \code
01011 ///   memset(dst1, c, dst1_size);
01012 ///   memcpy(dst2, dst1, dst2_size);
01013 /// \endcode
01014 /// into:
01015 /// \code
01016 ///   memset(dst1, c, dst1_size);
01017 ///   memset(dst2, c, dst2_size);
01018 /// \endcode
01019 /// When dst2_size <= dst1_size.
01020 ///
01021 /// The \p MemCpy must have a Constant length.
01022 bool MemCpyOpt::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
01023                                            MemSetInst *MemSet) {
01024   // This only makes sense on memcpy(..., memset(...), ...).
01025   if (MemSet->getRawDest() != MemCpy->getRawSource())
01026     return false;
01027 
01028   ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
01029   ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
01030   // Make sure the memcpy doesn't read any more than what the memset wrote.
01031   // Don't worry about sizes larger than i64.
01032   if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue())
01033     return false;
01034 
01035   IRBuilder<> Builder(MemCpy);
01036   Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
01037                        CopySize, MemCpy->getAlignment());
01038   return true;
01039 }
01040 
01041 /// Perform simplification of memcpy's.  If we have memcpy A
01042 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
01043 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
01044 /// circumstances). This allows later passes to remove the first memcpy
01045 /// altogether.
01046 bool MemCpyOpt::processMemCpy(MemCpyInst *M) {
01047   // We can only optimize non-volatile memcpy's.
01048   if (M->isVolatile()) return false;
01049 
01050   // If the source and destination of the memcpy are the same, then zap it.
01051   if (M->getSource() == M->getDest()) {
01052     MD->removeInstruction(M);
01053     M->eraseFromParent();
01054     return false;
01055   }
01056 
01057   // If copying from a constant, try to turn the memcpy into a memset.
01058   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
01059     if (GV->isConstant() && GV->hasDefinitiveInitializer())
01060       if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
01061         IRBuilder<> Builder(M);
01062         Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
01063                              M->getAlignment(), false);
01064         MD->removeInstruction(M);
01065         M->eraseFromParent();
01066         ++NumCpyToSet;
01067         return true;
01068       }
01069 
01070   MemDepResult DepInfo = MD->getDependency(M);
01071 
01072   // Try to turn a partially redundant memset + memcpy into
01073   // memcpy + smaller memset.  We don't need the memcpy size for this.
01074   if (DepInfo.isClobber())
01075     if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
01076       if (processMemSetMemCpyDependence(M, MDep))
01077         return true;
01078 
01079   // The optimizations after this point require the memcpy size.
01080   ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
01081   if (!CopySize) return false;
01082 
01083   // There are four possible optimizations we can do for memcpy:
01084   //   a) memcpy-memcpy xform which exposes redundance for DSE.
01085   //   b) call-memcpy xform for return slot optimization.
01086   //   c) memcpy from freshly alloca'd space or space that has just started its
01087   //      lifetime copies undefined data, and we can therefore eliminate the
01088   //      memcpy in favor of the data that was already at the destination.
01089   //   d) memcpy from a just-memset'd source can be turned into memset.
01090   if (DepInfo.isClobber()) {
01091     if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
01092       if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
01093                                CopySize->getZExtValue(), M->getAlignment(),
01094                                C)) {
01095         MD->removeInstruction(M);
01096         M->eraseFromParent();
01097         return true;
01098       }
01099     }
01100   }
01101 
01102   MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
01103   MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
01104       SrcLoc, true, M->getIterator(), M->getParent());
01105 
01106   if (SrcDepInfo.isClobber()) {
01107     if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
01108       return processMemCpyMemCpyDependence(M, MDep);
01109   } else if (SrcDepInfo.isDef()) {
01110     Instruction *I = SrcDepInfo.getInst();
01111     bool hasUndefContents = false;
01112 
01113     if (isa<AllocaInst>(I)) {
01114       hasUndefContents = true;
01115     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01116       if (II->getIntrinsicID() == Intrinsic::lifetime_start)
01117         if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
01118           if (LTSize->getZExtValue() >= CopySize->getZExtValue())
01119             hasUndefContents = true;
01120     }
01121 
01122     if (hasUndefContents) {
01123       MD->removeInstruction(M);
01124       M->eraseFromParent();
01125       ++NumMemCpyInstr;
01126       return true;
01127     }
01128   }
01129 
01130   if (SrcDepInfo.isClobber())
01131     if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
01132       if (performMemCpyToMemSetOptzn(M, MDep)) {
01133         MD->removeInstruction(M);
01134         M->eraseFromParent();
01135         ++NumCpyToSet;
01136         return true;
01137       }
01138 
01139   return false;
01140 }
01141 
01142 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
01143 /// not to alias.
01144 bool MemCpyOpt::processMemMove(MemMoveInst *M) {
01145   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
01146 
01147   if (!TLI->has(LibFunc::memmove))
01148     return false;
01149 
01150   // See if the pointers alias.
01151   if (!AA.isNoAlias(MemoryLocation::getForDest(M),
01152                     MemoryLocation::getForSource(M)))
01153     return false;
01154 
01155   DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n");
01156 
01157   // If not, then we know we can transform this.
01158   Type *ArgTys[3] = { M->getRawDest()->getType(),
01159                       M->getRawSource()->getType(),
01160                       M->getLength()->getType() };
01161   M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
01162                                                  Intrinsic::memcpy, ArgTys));
01163 
01164   // MemDep may have over conservative information about this instruction, just
01165   // conservatively flush it from the cache.
01166   MD->removeInstruction(M);
01167 
01168   ++NumMoveToCpy;
01169   return true;
01170 }
01171 
01172 /// This is called on every byval argument in call sites.
01173 bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
01174   const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
01175   // Find out what feeds this byval argument.
01176   Value *ByValArg = CS.getArgument(ArgNo);
01177   Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
01178   uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
01179   MemDepResult DepInfo = MD->getPointerDependencyFrom(
01180       MemoryLocation(ByValArg, ByValSize), true,
01181       CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
01182   if (!DepInfo.isClobber())
01183     return false;
01184 
01185   // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
01186   // a memcpy, see if we can byval from the source of the memcpy instead of the
01187   // result.
01188   MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
01189   if (!MDep || MDep->isVolatile() ||
01190       ByValArg->stripPointerCasts() != MDep->getDest())
01191     return false;
01192 
01193   // The length of the memcpy must be larger or equal to the size of the byval.
01194   ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
01195   if (!C1 || C1->getValue().getZExtValue() < ByValSize)
01196     return false;
01197 
01198   // Get the alignment of the byval.  If the call doesn't specify the alignment,
01199   // then it is some target specific value that we can't know.
01200   unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
01201   if (ByValAlign == 0) return false;
01202 
01203   // If it is greater than the memcpy, then we check to see if we can force the
01204   // source of the memcpy to the alignment we need.  If we fail, we bail out.
01205   AssumptionCache &AC =
01206       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
01207           *CS->getParent()->getParent());
01208   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01209   if (MDep->getAlignment() < ByValAlign &&
01210       getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
01211                                  CS.getInstruction(), &AC, &DT) < ByValAlign)
01212     return false;
01213 
01214   // Verify that the copied-from memory doesn't change in between the memcpy and
01215   // the byval call.
01216   //    memcpy(a <- b)
01217   //    *b = 42;
01218   //    foo(*a)
01219   // It would be invalid to transform the second memcpy into foo(*b).
01220   //
01221   // NOTE: This is conservative, it will stop on any read from the source loc,
01222   // not just the defining memcpy.
01223   MemDepResult SourceDep = MD->getPointerDependencyFrom(
01224       MemoryLocation::getForSource(MDep), false,
01225       CS.getInstruction()->getIterator(), MDep->getParent());
01226   if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
01227     return false;
01228 
01229   Value *TmpCast = MDep->getSource();
01230   if (MDep->getSource()->getType() != ByValArg->getType())
01231     TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
01232                               "tmpcast", CS.getInstruction());
01233 
01234   DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
01235                << "  " << *MDep << "\n"
01236                << "  " << *CS.getInstruction() << "\n");
01237 
01238   // Otherwise we're good!  Update the byval argument.
01239   CS.setArgument(ArgNo, TmpCast);
01240   ++NumMemCpyInstr;
01241   return true;
01242 }
01243 
01244 /// Executes one iteration of MemCpyOpt.
01245 bool MemCpyOpt::iterateOnFunction(Function &F) {
01246   bool MadeChange = false;
01247 
01248   // Walk all instruction in the function.
01249   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
01250     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
01251       // Avoid invalidating the iterator.
01252       Instruction *I = &*BI++;
01253 
01254       bool RepeatInstruction = false;
01255 
01256       if (StoreInst *SI = dyn_cast<StoreInst>(I))
01257         MadeChange |= processStore(SI, BI);
01258       else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
01259         RepeatInstruction = processMemSet(M, BI);
01260       else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
01261         RepeatInstruction = processMemCpy(M);
01262       else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
01263         RepeatInstruction = processMemMove(M);
01264       else if (auto CS = CallSite(I)) {
01265         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
01266           if (CS.isByValArgument(i))
01267             MadeChange |= processByValArgument(CS, i);
01268       }
01269 
01270       // Reprocess the instruction if desired.
01271       if (RepeatInstruction) {
01272         if (BI != BB->begin()) --BI;
01273         MadeChange = true;
01274       }
01275     }
01276   }
01277 
01278   return MadeChange;
01279 }
01280 
01281 /// This is the main transformation entry point for a function.
01282 bool MemCpyOpt::runOnFunction(Function &F) {
01283   if (skipOptnoneFunction(F))
01284     return false;
01285 
01286   bool MadeChange = false;
01287   MD = &getAnalysis<MemoryDependenceAnalysis>();
01288   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
01289 
01290   // If we don't have at least memset and memcpy, there is little point of doing
01291   // anything here.  These are required by a freestanding implementation, so if
01292   // even they are disabled, there is no point in trying hard.
01293   if (!TLI->has(LibFunc::memset) || !TLI->has(LibFunc::memcpy))
01294     return false;
01295 
01296   while (1) {
01297     if (!iterateOnFunction(F))
01298       break;
01299     MadeChange = true;
01300   }
01301 
01302   MD = nullptr;
01303   return MadeChange;
01304 }