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