Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1 | //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass performs various transformations related to eliminating memcpy |
| 11 | // calls, or transforming sets of stores into memset's. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #define DEBUG_TYPE "memcpyopt" |
| 16 | #include "llvm/Transforms/Scalar.h" |
Benjamin Kramer | a112087 | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 17 | #include "llvm/GlobalVariable.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 18 | #include "llvm/IntrinsicInst.h" |
| 19 | #include "llvm/Instructions.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/SmallVector.h" |
| 21 | #include "llvm/ADT/Statistic.h" |
| 22 | #include "llvm/Analysis/Dominators.h" |
| 23 | #include "llvm/Analysis/AliasAnalysis.h" |
| 24 | #include "llvm/Analysis/MemoryDependenceAnalysis.h" |
Chris Lattner | bb89710 | 2010-12-26 20:15:01 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ValueTracking.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 26 | #include "llvm/Support/Debug.h" |
| 27 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
Chris Lattner | 61db1f5 | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 28 | #include "llvm/Support/IRBuilder.h" |
Chris Lattner | bdff548 | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 29 | #include "llvm/Support/raw_ostream.h" |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 30 | #include "llvm/Target/TargetData.h" |
| 31 | #include <list> |
| 32 | using namespace llvm; |
| 33 | |
| 34 | STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted"); |
| 35 | STATISTIC(NumMemSetInfer, "Number of memsets inferred"); |
Duncan Sands | 05cd03b | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 36 | STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy"); |
Benjamin Kramer | a112087 | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 37 | STATISTIC(NumCpyToSet, "Number of memcpys converted to memset"); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 38 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 39 | static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx, |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 40 | bool &VariableIdxFound, const TargetData &TD){ |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 41 | // Skip over the first indices. |
| 42 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 43 | for (unsigned i = 1; i != Idx; ++i, ++GTI) |
| 44 | /*skip along*/; |
| 45 | |
| 46 | // Compute the offset implied by the rest of the indices. |
| 47 | int64_t Offset = 0; |
| 48 | for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) { |
| 49 | ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 50 | if (OpC == 0) |
| 51 | return VariableIdxFound = true; |
| 52 | if (OpC->isZero()) continue; // No offset. |
| 53 | |
| 54 | // Handle struct indices, which add their field offset to the pointer. |
| 55 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 56 | Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); |
| 57 | continue; |
| 58 | } |
| 59 | |
| 60 | // Otherwise, we have a sequential type like an array or vector. Multiply |
| 61 | // the index by the ElementSize. |
Duncan Sands | 777d230 | 2009-05-09 07:06:46 +0000 | [diff] [blame] | 62 | uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 63 | Offset += Size*OpC->getSExtValue(); |
| 64 | } |
| 65 | |
| 66 | return Offset; |
| 67 | } |
| 68 | |
| 69 | /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a |
| 70 | /// constant offset, and return that constant offset. For example, Ptr1 might |
| 71 | /// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8. |
| 72 | static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset, |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 73 | const TargetData &TD) { |
Chris Lattner | 9fa11e9 | 2011-01-08 21:07:56 +0000 | [diff] [blame^] | 74 | Ptr1 = Ptr1->stripPointerCasts(); |
| 75 | Ptr2 = Ptr2->stripPointerCasts(); |
| 76 | GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1); |
| 77 | GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2); |
| 78 | |
| 79 | bool VariableIdxFound = false; |
| 80 | |
| 81 | // If one pointer is a GEP and the other isn't, then see if the GEP is a |
| 82 | // constant offset from the base, as in "P" and "gep P, 1". |
| 83 | if (GEP1 && GEP2 == 0 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) { |
| 84 | Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, TD); |
| 85 | return !VariableIdxFound; |
| 86 | } |
| 87 | |
| 88 | if (GEP2 && GEP1 == 0 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) { |
| 89 | Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, TD); |
| 90 | return !VariableIdxFound; |
| 91 | } |
| 92 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 93 | // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical |
| 94 | // base. After that base, they may have some number of common (and |
| 95 | // potentially variable) indices. After that they handle some constant |
| 96 | // offset, which determines their offset from each other. At this point, we |
| 97 | // handle no other case. |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 98 | if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0)) |
| 99 | return false; |
| 100 | |
| 101 | // Skip any common indices and track the GEP types. |
| 102 | unsigned Idx = 1; |
| 103 | for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx) |
| 104 | if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx)) |
| 105 | break; |
| 106 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 107 | int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD); |
| 108 | int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD); |
| 109 | if (VariableIdxFound) return false; |
| 110 | |
| 111 | Offset = Offset2-Offset1; |
| 112 | return true; |
| 113 | } |
| 114 | |
| 115 | |
| 116 | /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value. |
| 117 | /// This allows us to analyze stores like: |
| 118 | /// store 0 -> P+1 |
| 119 | /// store 0 -> P+0 |
| 120 | /// store 0 -> P+3 |
| 121 | /// store 0 -> P+2 |
| 122 | /// which sometimes happens with stores to arrays of structs etc. When we see |
| 123 | /// the first store, we make a range [1, 2). The second store extends the range |
| 124 | /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the |
| 125 | /// two ranges into [0, 3) which is memset'able. |
| 126 | namespace { |
| 127 | struct MemsetRange { |
| 128 | // Start/End - A semi range that describes the span that this range covers. |
| 129 | // The range is closed at the start and open at the end: [Start, End). |
| 130 | int64_t Start, End; |
| 131 | |
| 132 | /// StartPtr - The getelementptr instruction that points to the start of the |
| 133 | /// range. |
| 134 | Value *StartPtr; |
| 135 | |
| 136 | /// Alignment - The known alignment of the first store. |
| 137 | unsigned Alignment; |
| 138 | |
| 139 | /// TheStores - The actual stores that make up this range. |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 140 | SmallVector<Instruction*, 16> TheStores; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 141 | |
| 142 | bool isProfitableToUseMemset(const TargetData &TD) const; |
| 143 | |
| 144 | }; |
| 145 | } // end anon namespace |
| 146 | |
| 147 | bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const { |
| 148 | // If we found more than 8 stores to merge or 64 bytes, use memset. |
| 149 | if (TheStores.size() >= 8 || End-Start >= 64) return true; |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 150 | |
| 151 | // If there is nothing to merge, don't do anything. |
| 152 | if (TheStores.size() < 2) return false; |
| 153 | |
| 154 | // If any of the stores are a memset, then it is always good to extend the |
| 155 | // memset. |
| 156 | for (unsigned i = 0, e = TheStores.size(); i != e; ++i) |
| 157 | if (!isa<StoreInst>(TheStores[i])) |
| 158 | return true; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 159 | |
| 160 | // Assume that the code generator is capable of merging pairs of stores |
| 161 | // together if it wants to. |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 162 | if (TheStores.size() == 2) return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 163 | |
| 164 | // If we have fewer than 8 stores, it can still be worthwhile to do this. |
| 165 | // For example, merging 4 i8 stores into an i32 store is useful almost always. |
| 166 | // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the |
| 167 | // memset will be split into 2 32-bit stores anyway) and doing so can |
| 168 | // pessimize the llvm optimizer. |
| 169 | // |
| 170 | // Since we don't have perfect knowledge here, make some assumptions: assume |
| 171 | // the maximum GPR width is the same size as the pointer size and assume that |
| 172 | // this width can be stored. If so, check to see whether we will end up |
| 173 | // actually reducing the number of stores used. |
| 174 | unsigned Bytes = unsigned(End-Start); |
| 175 | unsigned NumPointerStores = Bytes/TD.getPointerSize(); |
| 176 | |
| 177 | // Assume the remaining bytes if any are done a byte at a time. |
| 178 | unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize(); |
| 179 | |
| 180 | // If we will reduce the # stores (according to this heuristic), do the |
| 181 | // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32 |
| 182 | // etc. |
| 183 | return TheStores.size() > NumPointerStores+NumByteStores; |
| 184 | } |
| 185 | |
| 186 | |
| 187 | namespace { |
| 188 | class MemsetRanges { |
| 189 | /// Ranges - A sorted list of the memset ranges. We use std::list here |
| 190 | /// because each element is relatively large and expensive to copy. |
| 191 | std::list<MemsetRange> Ranges; |
| 192 | typedef std::list<MemsetRange>::iterator range_iterator; |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 193 | const TargetData &TD; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 194 | public: |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 195 | MemsetRanges(const TargetData &td) : TD(td) {} |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 196 | |
| 197 | typedef std::list<MemsetRange>::const_iterator const_iterator; |
| 198 | const_iterator begin() const { return Ranges.begin(); } |
| 199 | const_iterator end() const { return Ranges.end(); } |
| 200 | bool empty() const { return Ranges.empty(); } |
| 201 | |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 202 | void addInst(int64_t OffsetFromFirst, Instruction *Inst) { |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 203 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) |
| 204 | addStore(OffsetFromFirst, SI); |
| 205 | else |
| 206 | addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst)); |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 207 | } |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 208 | |
| 209 | void addStore(int64_t OffsetFromFirst, StoreInst *SI) { |
| 210 | int64_t StoreSize = TD.getTypeStoreSize(SI->getOperand(0)->getType()); |
| 211 | |
| 212 | addRange(OffsetFromFirst, StoreSize, |
| 213 | SI->getPointerOperand(), SI->getAlignment(), SI); |
| 214 | } |
| 215 | |
| 216 | void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) { |
| 217 | int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
| 218 | addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI); |
| 219 | } |
| 220 | |
| 221 | void addRange(int64_t Start, int64_t Size, Value *Ptr, |
| 222 | unsigned Alignment, Instruction *Inst); |
| 223 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 224 | }; |
| 225 | |
| 226 | } // end anon namespace |
| 227 | |
| 228 | |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 229 | /// addRange - Add a new store to the MemsetRanges data structure. This adds a |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 230 | /// new range for the specified store at the specified offset, merging into |
| 231 | /// existing ranges as appropriate. |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 232 | /// |
| 233 | /// Do a linear search of the ranges to see if this can be joined and/or to |
| 234 | /// find the insertion point in the list. We keep the ranges sorted for |
| 235 | /// simplicity here. This is a linear search of a linked list, which is ugly, |
| 236 | /// however the number of ranges is limited, so this won't get crazy slow. |
| 237 | void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr, |
| 238 | unsigned Alignment, Instruction *Inst) { |
| 239 | int64_t End = Start+Size; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 240 | range_iterator I = Ranges.begin(), E = Ranges.end(); |
| 241 | |
| 242 | while (I != E && Start > I->End) |
| 243 | ++I; |
| 244 | |
| 245 | // We now know that I == E, in which case we didn't find anything to merge |
| 246 | // with, or that Start <= I->End. If End < I->Start or I == E, then we need |
| 247 | // to insert a new range. Handle this now. |
| 248 | if (I == E || End < I->Start) { |
| 249 | MemsetRange &R = *Ranges.insert(I, MemsetRange()); |
| 250 | R.Start = Start; |
| 251 | R.End = End; |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 252 | R.StartPtr = Ptr; |
| 253 | R.Alignment = Alignment; |
| 254 | R.TheStores.push_back(Inst); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 255 | return; |
| 256 | } |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 257 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 258 | // This store overlaps with I, add it. |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 259 | I->TheStores.push_back(Inst); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 260 | |
| 261 | // At this point, we may have an interval that completely contains our store. |
| 262 | // If so, just add it to the interval and return. |
| 263 | if (I->Start <= Start && I->End >= End) |
| 264 | return; |
| 265 | |
| 266 | // Now we know that Start <= I->End and End >= I->Start so the range overlaps |
| 267 | // but is not entirely contained within the range. |
| 268 | |
| 269 | // See if the range extends the start of the range. In this case, it couldn't |
| 270 | // possibly cause it to join the prior range, because otherwise we would have |
| 271 | // stopped on *it*. |
| 272 | if (Start < I->Start) { |
| 273 | I->Start = Start; |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 274 | I->StartPtr = Ptr; |
| 275 | I->Alignment = Alignment; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 276 | } |
| 277 | |
| 278 | // Now we know that Start <= I->End and Start >= I->Start (so the startpoint |
| 279 | // is in or right at the end of I), and that End >= I->Start. Extend I out to |
| 280 | // End. |
| 281 | if (End > I->End) { |
| 282 | I->End = End; |
Nick Lewycky | 9c0f146 | 2009-03-19 05:51:39 +0000 | [diff] [blame] | 283 | range_iterator NextI = I; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 284 | while (++NextI != E && End >= NextI->Start) { |
| 285 | // Merge the range in. |
| 286 | I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end()); |
| 287 | if (NextI->End > I->End) |
| 288 | I->End = NextI->End; |
| 289 | Ranges.erase(NextI); |
| 290 | NextI = I; |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | //===----------------------------------------------------------------------===// |
| 296 | // MemCpyOpt Pass |
| 297 | //===----------------------------------------------------------------------===// |
| 298 | |
| 299 | namespace { |
Chris Lattner | 3e8b663 | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 300 | class MemCpyOpt : public FunctionPass { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 301 | MemoryDependenceAnalysis *MD; |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 302 | const TargetData *TD; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 303 | public: |
| 304 | static char ID; // Pass identification, replacement for typeid |
Owen Anderson | 081c34b | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 305 | MemCpyOpt() : FunctionPass(ID) { |
| 306 | initializeMemCpyOptPass(*PassRegistry::getPassRegistry()); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 307 | MD = 0; |
Owen Anderson | 081c34b | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 308 | } |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 309 | |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 310 | bool runOnFunction(Function &F); |
| 311 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 312 | private: |
| 313 | // This transformation requires dominator postdominator info |
| 314 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 315 | AU.setPreservesCFG(); |
| 316 | AU.addRequired<DominatorTree>(); |
| 317 | AU.addRequired<MemoryDependenceAnalysis>(); |
| 318 | AU.addRequired<AliasAnalysis>(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 319 | AU.addPreserved<AliasAnalysis>(); |
| 320 | AU.addPreserved<MemoryDependenceAnalysis>(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 321 | } |
| 322 | |
| 323 | // Helper fuctions |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 324 | bool processStore(StoreInst *SI, BasicBlock::iterator &BBI); |
| 325 | bool processMemCpy(MemCpyInst *M); |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 326 | bool processMemMove(MemMoveInst *M); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 327 | bool performCallSlotOptzn(Instruction *cpy, Value *cpyDst, Value *cpySrc, |
| 328 | uint64_t cpyLen, CallInst *C); |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 329 | bool processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep, |
| 330 | uint64_t MSize); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 331 | bool processByValArgument(CallSite CS, unsigned ArgNo); |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 332 | Instruction *tryMergingIntoMemset(Instruction *I, Value *StartPtr, |
| 333 | Value *ByteVal); |
| 334 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 335 | bool iterateOnFunction(Function &F); |
| 336 | }; |
| 337 | |
| 338 | char MemCpyOpt::ID = 0; |
| 339 | } |
| 340 | |
| 341 | // createMemCpyOptPass - The public interface to this file... |
| 342 | FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOpt(); } |
| 343 | |
Owen Anderson | 2ab36d3 | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 344 | INITIALIZE_PASS_BEGIN(MemCpyOpt, "memcpyopt", "MemCpy Optimization", |
| 345 | false, false) |
| 346 | INITIALIZE_PASS_DEPENDENCY(DominatorTree) |
| 347 | INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis) |
| 348 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
| 349 | INITIALIZE_PASS_END(MemCpyOpt, "memcpyopt", "MemCpy Optimization", |
| 350 | false, false) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 351 | |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 352 | /// tryMergingIntoMemset - When scanning forward over instructions, we look for |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 353 | /// some other patterns to fold away. In particular, this looks for stores to |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 354 | /// neighboring locations of memory. If it sees enough consequtive ones, it |
| 355 | /// attempts to merge them together into a memcpy/memset. |
| 356 | Instruction *MemCpyOpt::tryMergingIntoMemset(Instruction *StartInst, |
| 357 | Value *StartPtr, Value *ByteVal) { |
| 358 | if (TD == 0) return 0; |
| 359 | |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 360 | // Okay, so we now have a single store that can be splatable. Scan to find |
| 361 | // all subsequent stores of the same value to offset from the same pointer. |
| 362 | // Join these together into ranges, so we can decide whether contiguous blocks |
| 363 | // are stored. |
| 364 | MemsetRanges Ranges(*TD); |
| 365 | |
| 366 | BasicBlock::iterator BI = StartInst; |
| 367 | for (++BI; !isa<TerminatorInst>(BI); ++BI) { |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 368 | if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) { |
| 369 | // If the instruction is readnone, ignore it, otherwise bail out. We |
| 370 | // don't even allow readonly here because we don't want something like: |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 371 | // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 372 | if (BI->mayWriteToMemory() || BI->mayReadFromMemory()) |
| 373 | break; |
| 374 | continue; |
| 375 | } |
| 376 | |
| 377 | if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) { |
| 378 | // If this is a store, see if we can merge it in. |
| 379 | if (NextStore->isVolatile()) break; |
| 380 | |
| 381 | // Check to see if this stored value is of the same byte-splattable value. |
| 382 | if (ByteVal != isBytewiseValue(NextStore->getOperand(0))) |
| 383 | break; |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 384 | |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 385 | // Check to see if this store is to a constant offset from the start ptr. |
| 386 | int64_t Offset; |
| 387 | if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, *TD)) |
| 388 | break; |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 389 | |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 390 | Ranges.addStore(Offset, NextStore); |
| 391 | } else { |
| 392 | MemSetInst *MSI = cast<MemSetInst>(BI); |
| 393 | |
| 394 | if (MSI->isVolatile() || ByteVal != MSI->getValue() || |
| 395 | !isa<ConstantInt>(MSI->getLength())) |
| 396 | break; |
| 397 | |
| 398 | // Check to see if this store is to a constant offset from the start ptr. |
| 399 | int64_t Offset; |
| 400 | if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, *TD)) |
| 401 | break; |
| 402 | |
| 403 | Ranges.addMemSet(Offset, MSI); |
| 404 | } |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 405 | } |
| 406 | |
| 407 | // If we have no ranges, then we just had a single store with nothing that |
| 408 | // could be merged in. This is a very common case of course. |
| 409 | if (Ranges.empty()) |
| 410 | return 0; |
| 411 | |
| 412 | // If we had at least one store that could be merged in, add the starting |
| 413 | // store as well. We try to avoid this unless there is at least something |
| 414 | // interesting as a small compile-time optimization. |
| 415 | Ranges.addInst(0, StartInst); |
| 416 | |
| 417 | // If we create any memsets, we put it right before the first instruction that |
| 418 | // isn't part of the memset block. This ensure that the memset is dominated |
| 419 | // by any addressing instruction needed by the start of the block. |
| 420 | IRBuilder<> Builder(BI); |
| 421 | |
| 422 | // Now that we have full information about ranges, loop over the ranges and |
| 423 | // emit memset's for anything big enough to be worthwhile. |
| 424 | Instruction *AMemSet = 0; |
| 425 | for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end(); |
| 426 | I != E; ++I) { |
| 427 | const MemsetRange &Range = *I; |
| 428 | |
| 429 | if (Range.TheStores.size() == 1) continue; |
| 430 | |
| 431 | // If it is profitable to lower this range to memset, do so now. |
| 432 | if (!Range.isProfitableToUseMemset(*TD)) |
| 433 | continue; |
| 434 | |
| 435 | // Otherwise, we do want to transform this! Create a new memset. |
| 436 | // Get the starting pointer of the block. |
| 437 | StartPtr = Range.StartPtr; |
| 438 | |
| 439 | // Determine alignment |
| 440 | unsigned Alignment = Range.Alignment; |
| 441 | if (Alignment == 0) { |
| 442 | const Type *EltType = |
| 443 | cast<PointerType>(StartPtr->getType())->getElementType(); |
| 444 | Alignment = TD->getABITypeAlignment(EltType); |
| 445 | } |
| 446 | |
| 447 | AMemSet = |
| 448 | Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment); |
| 449 | |
| 450 | DEBUG(dbgs() << "Replace stores:\n"; |
| 451 | for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i) |
| 452 | dbgs() << *Range.TheStores[i] << '\n'; |
| 453 | dbgs() << "With: " << *AMemSet << '\n'); |
| 454 | |
| 455 | // Zap all the stores. |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 456 | for (SmallVector<Instruction*, 16>::const_iterator |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 457 | SI = Range.TheStores.begin(), |
| 458 | SE = Range.TheStores.end(); SI != SE; ++SI) |
| 459 | (*SI)->eraseFromParent(); |
| 460 | ++NumMemSetInfer; |
| 461 | } |
| 462 | |
| 463 | return AMemSet; |
| 464 | } |
| 465 | |
| 466 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 467 | bool MemCpyOpt::processStore(StoreInst *SI, BasicBlock::iterator &BBI) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 468 | if (SI->isVolatile()) return false; |
| 469 | |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 470 | if (TD == 0) return false; |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 471 | |
| 472 | // Detect cases where we're performing call slot forwarding, but |
| 473 | // happen to be using a load-store pair to implement it, rather than |
| 474 | // a memcpy. |
| 475 | if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) { |
| 476 | if (!LI->isVolatile() && LI->hasOneUse()) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 477 | MemDepResult dep = MD->getDependency(LI); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 478 | CallInst *C = 0; |
| 479 | if (dep.isClobber() && !isa<MemCpyInst>(dep.getInst())) |
| 480 | C = dyn_cast<CallInst>(dep.getInst()); |
| 481 | |
| 482 | if (C) { |
| 483 | bool changed = performCallSlotOptzn(LI, |
| 484 | SI->getPointerOperand()->stripPointerCasts(), |
| 485 | LI->getPointerOperand()->stripPointerCasts(), |
| 486 | TD->getTypeStoreSize(SI->getOperand(0)->getType()), C); |
| 487 | if (changed) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 488 | MD->removeInstruction(SI); |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 489 | SI->eraseFromParent(); |
| 490 | LI->eraseFromParent(); |
| 491 | ++NumMemCpyInstr; |
| 492 | return true; |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 498 | // There are two cases that are interesting for this code to handle: memcpy |
| 499 | // and memset. Right now we only handle memset. |
| 500 | |
| 501 | // Ensure that the value being stored is something that can be memset'able a |
| 502 | // byte at a time like "0" or "-1" or any width, as well as things like |
| 503 | // 0xA0A0A0A0 and 0.0. |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 504 | if (Value *ByteVal = isBytewiseValue(SI->getOperand(0))) |
| 505 | if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(), |
| 506 | ByteVal)) { |
| 507 | BBI = I; // Don't invalidate iterator. |
| 508 | return true; |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 509 | } |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 510 | |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 511 | return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 512 | } |
| 513 | |
| 514 | |
| 515 | /// performCallSlotOptzn - takes a memcpy and a call that it depends on, |
| 516 | /// and checks for the possibility of a call slot optimization by having |
| 517 | /// the call write its result directly into the destination of the memcpy. |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 518 | bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy, |
| 519 | Value *cpyDest, Value *cpySrc, |
| 520 | uint64_t cpyLen, CallInst *C) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 521 | // The general transformation to keep in mind is |
| 522 | // |
| 523 | // call @func(..., src, ...) |
| 524 | // memcpy(dest, src, ...) |
| 525 | // |
| 526 | // -> |
| 527 | // |
| 528 | // memcpy(dest, src, ...) |
| 529 | // call @func(..., dest, ...) |
| 530 | // |
| 531 | // Since moving the memcpy is technically awkward, we additionally check that |
| 532 | // src only holds uninitialized values at the moment of the call, meaning that |
| 533 | // the memcpy can be discarded rather than moved. |
| 534 | |
| 535 | // Deliberately get the source and destination with bitcasts stripped away, |
| 536 | // because we'll need to do type comparisons based on the underlying type. |
Gabor Greif | 7d3056b | 2010-07-28 22:50:26 +0000 | [diff] [blame] | 537 | CallSite CS(C); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 538 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 539 | // Require that src be an alloca. This simplifies the reasoning considerably. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 540 | AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 541 | if (!srcAlloca) |
| 542 | return false; |
| 543 | |
| 544 | // Check that all of src is copied to dest. |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 545 | if (TD == 0) return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 546 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 547 | ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 548 | if (!srcArraySize) |
| 549 | return false; |
| 550 | |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 551 | uint64_t srcSize = TD->getTypeAllocSize(srcAlloca->getAllocatedType()) * |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 552 | srcArraySize->getZExtValue(); |
| 553 | |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 554 | if (cpyLen < srcSize) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 555 | return false; |
| 556 | |
| 557 | // Check that accessing the first srcSize bytes of dest will not cause a |
| 558 | // trap. Otherwise the transform is invalid since it might cause a trap |
| 559 | // to occur earlier than it otherwise would. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 560 | if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 561 | // The destination is an alloca. Check it is larger than srcSize. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 562 | ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 563 | if (!destArraySize) |
| 564 | return false; |
| 565 | |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 566 | uint64_t destSize = TD->getTypeAllocSize(A->getAllocatedType()) * |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 567 | destArraySize->getZExtValue(); |
| 568 | |
| 569 | if (destSize < srcSize) |
| 570 | return false; |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 571 | } else if (Argument *A = dyn_cast<Argument>(cpyDest)) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 572 | // If the destination is an sret parameter then only accesses that are |
| 573 | // outside of the returned struct type can trap. |
| 574 | if (!A->hasStructRetAttr()) |
| 575 | return false; |
| 576 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 577 | const Type *StructTy = cast<PointerType>(A->getType())->getElementType(); |
Dan Gohman | 8942f9bb | 2009-08-18 01:17:52 +0000 | [diff] [blame] | 578 | uint64_t destSize = TD->getTypeAllocSize(StructTy); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 579 | |
| 580 | if (destSize < srcSize) |
| 581 | return false; |
| 582 | } else { |
| 583 | return false; |
| 584 | } |
| 585 | |
| 586 | // Check that src is not accessed except via the call and the memcpy. This |
| 587 | // guarantees that it holds only undefined values when passed in (so the final |
| 588 | // memcpy can be dropped), that it is not read or written between the call and |
| 589 | // the memcpy, and that writing beyond the end of it is undefined. |
| 590 | SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(), |
| 591 | srcAlloca->use_end()); |
| 592 | while (!srcUseList.empty()) { |
Dan Gohman | 321a813 | 2010-01-05 16:27:25 +0000 | [diff] [blame] | 593 | User *UI = srcUseList.pop_back_val(); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 594 | |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 595 | if (isa<BitCastInst>(UI)) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 596 | for (User::use_iterator I = UI->use_begin(), E = UI->use_end(); |
| 597 | I != E; ++I) |
| 598 | srcUseList.push_back(*I); |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 599 | } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(UI)) { |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 600 | if (G->hasAllZeroIndices()) |
| 601 | for (User::use_iterator I = UI->use_begin(), E = UI->use_end(); |
| 602 | I != E; ++I) |
| 603 | srcUseList.push_back(*I); |
| 604 | else |
| 605 | return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 606 | } else if (UI != C && UI != cpy) { |
| 607 | return false; |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | // Since we're changing the parameter to the callsite, we need to make sure |
| 612 | // that what would be the new parameter dominates the callsite. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 613 | DominatorTree &DT = getAnalysis<DominatorTree>(); |
| 614 | if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest)) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 615 | if (!DT.dominates(cpyDestInst, C)) |
| 616 | return false; |
| 617 | |
| 618 | // In addition to knowing that the call does not access src in some |
| 619 | // unexpected manner, for example via a global, which we deduce from |
| 620 | // the use analysis, we also need to know that it does not sneakily |
| 621 | // access dest. We rely on AA to figure this out for us. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 622 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
Chris Lattner | 0651126 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 623 | if (AA.getModRefInfo(C, cpyDest, srcSize) != AliasAnalysis::NoModRef) |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 624 | return false; |
| 625 | |
| 626 | // All the checks have passed, so do the transformation. |
Owen Anderson | 12cb36c | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 627 | bool changedArgument = false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 628 | for (unsigned i = 0; i < CS.arg_size(); ++i) |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 629 | if (CS.getArgument(i)->stripPointerCasts() == cpySrc) { |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 630 | if (cpySrc->getType() != cpyDest->getType()) |
Gabor Greif | 7cbd8a3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 631 | cpyDest = CastInst::CreatePointerCast(cpyDest, cpySrc->getType(), |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 632 | cpyDest->getName(), C); |
Owen Anderson | 12cb36c | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 633 | changedArgument = true; |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 634 | if (CS.getArgument(i)->getType() == cpyDest->getType()) |
Owen Anderson | 009e4f7 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 635 | CS.setArgument(i, cpyDest); |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 636 | else |
| 637 | CS.setArgument(i, CastInst::CreatePointerCast(cpyDest, |
| 638 | CS.getArgument(i)->getType(), cpyDest->getName(), C)); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 639 | } |
| 640 | |
Owen Anderson | 12cb36c | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 641 | if (!changedArgument) |
| 642 | return false; |
| 643 | |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 644 | // Drop any cached information about the call, because we may have changed |
| 645 | // its dependence information by changing its parameter. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 646 | MD->removeInstruction(C); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 647 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 648 | // Remove the memcpy. |
| 649 | MD->removeInstruction(cpy); |
Dan Gohman | fe60104 | 2010-06-22 15:08:57 +0000 | [diff] [blame] | 650 | ++NumMemCpyInstr; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 651 | |
| 652 | return true; |
| 653 | } |
| 654 | |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 655 | /// processMemCpyMemCpyDependence - We've found that the (upward scanning) |
| 656 | /// memory dependence of memcpy 'M' is the memcpy 'MDep'. Try to simplify M to |
| 657 | /// copy from MDep's input if we can. MSize is the size of M's copy. |
| 658 | /// |
| 659 | bool MemCpyOpt::processMemCpyMemCpyDependence(MemCpyInst *M, MemCpyInst *MDep, |
| 660 | uint64_t MSize) { |
| 661 | // We can only transforms memcpy's where the dest of one is the source of the |
| 662 | // other. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 663 | if (M->getSource() != MDep->getDest() || MDep->isVolatile()) |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 664 | return false; |
| 665 | |
Chris Lattner | f7f3546 | 2010-12-09 07:39:50 +0000 | [diff] [blame] | 666 | // If dep instruction is reading from our current input, then it is a noop |
| 667 | // transfer and substituting the input won't change this instruction. Just |
| 668 | // ignore the input and let someone else zap MDep. This handles cases like: |
| 669 | // memcpy(a <- a) |
| 670 | // memcpy(b <- a) |
| 671 | if (M->getSource() == MDep->getSource()) |
| 672 | return false; |
| 673 | |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 674 | // Second, the length of the memcpy's must be the same, or the preceeding one |
| 675 | // must be larger than the following one. |
| 676 | ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); |
| 677 | if (!C1) return false; |
| 678 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 679 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 680 | |
| 681 | // Verify that the copied-from memory doesn't change in between the two |
| 682 | // transfers. For example, in: |
| 683 | // memcpy(a <- b) |
| 684 | // *b = 42; |
| 685 | // memcpy(c <- a) |
| 686 | // It would be invalid to transform the second memcpy into memcpy(c <- b). |
| 687 | // |
| 688 | // TODO: If the code between M and MDep is transparent to the destination "c", |
| 689 | // then we could still perform the xform by moving M up to the first memcpy. |
| 690 | // |
| 691 | // NOTE: This is conservative, it will stop on any read from the source loc, |
| 692 | // not just the defining memcpy. |
| 693 | MemDepResult SourceDep = |
| 694 | MD->getPointerDependencyFrom(AA.getLocationForSource(MDep), |
| 695 | false, M, M->getParent()); |
| 696 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) |
| 697 | return false; |
Chris Lattner | 5a7aeaa | 2010-11-18 08:00:57 +0000 | [diff] [blame] | 698 | |
| 699 | // If the dest of the second might alias the source of the first, then the |
| 700 | // source and dest might overlap. We still want to eliminate the intermediate |
| 701 | // value, but we have to generate a memmove instead of memcpy. |
Chris Lattner | 61db1f5 | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 702 | bool UseMemMove = false; |
| 703 | if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(MDep))) |
| 704 | UseMemMove = true; |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 705 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 706 | // If all checks passed, then we can transform M. |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 707 | |
| 708 | // Make sure to use the lesser of the alignment of the source and the dest |
| 709 | // since we're changing where we're reading from, but don't want to increase |
| 710 | // the alignment past what can be read from or written to. |
| 711 | // TODO: Is this worth it if we're creating a less aligned memcpy? For |
| 712 | // example we could be moving from movaps -> movq on x86. |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 713 | unsigned Align = std::min(MDep->getAlignment(), M->getAlignment()); |
Chris Lattner | 61db1f5 | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 714 | |
| 715 | IRBuilder<> Builder(M); |
| 716 | if (UseMemMove) |
| 717 | Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(), |
| 718 | Align, M->isVolatile()); |
| 719 | else |
| 720 | Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(), |
| 721 | Align, M->isVolatile()); |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 722 | |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 723 | // Remove the instruction we're replacing. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 724 | MD->removeInstruction(M); |
Chris Lattner | d528be6 | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 725 | M->eraseFromParent(); |
| 726 | ++NumMemCpyInstr; |
| 727 | return true; |
Chris Lattner | 43f8e43 | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 728 | } |
| 729 | |
| 730 | |
Gabor Greif | 7d3056b | 2010-07-28 22:50:26 +0000 | [diff] [blame] | 731 | /// processMemCpy - perform simplification of memcpy's. If we have memcpy A |
| 732 | /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite |
| 733 | /// B to be a memcpy from X to Z (or potentially a memmove, depending on |
| 734 | /// circumstances). This allows later passes to remove the first memcpy |
| 735 | /// altogether. |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 736 | bool MemCpyOpt::processMemCpy(MemCpyInst *M) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 737 | // We can only optimize statically-sized memcpy's that are non-volatile. |
| 738 | ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); |
| 739 | if (CopySize == 0 || M->isVolatile()) return false; |
Owen Anderson | 6549121 | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 740 | |
Chris Lattner | 8fdca6a | 2010-12-09 07:45:45 +0000 | [diff] [blame] | 741 | // If the source and destination of the memcpy are the same, then zap it. |
| 742 | if (M->getSource() == M->getDest()) { |
| 743 | MD->removeInstruction(M); |
| 744 | M->eraseFromParent(); |
| 745 | return false; |
| 746 | } |
Benjamin Kramer | a112087 | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 747 | |
| 748 | // If copying from a constant, try to turn the memcpy into a memset. |
Benjamin Kramer | 49c7e3e | 2010-12-24 22:23:59 +0000 | [diff] [blame] | 749 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource())) |
Benjamin Kramer | 3fed0d9 | 2010-12-26 15:23:45 +0000 | [diff] [blame] | 750 | if (GV->isConstant() && GV->hasDefinitiveInitializer()) |
Benjamin Kramer | 49c7e3e | 2010-12-24 22:23:59 +0000 | [diff] [blame] | 751 | if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) { |
Chris Lattner | 61db1f5 | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 752 | IRBuilder<> Builder(M); |
| 753 | Builder.CreateMemSet(M->getRawDest(), ByteVal, CopySize, |
| 754 | M->getAlignment(), false); |
Benjamin Kramer | 49c7e3e | 2010-12-24 22:23:59 +0000 | [diff] [blame] | 755 | MD->removeInstruction(M); |
| 756 | M->eraseFromParent(); |
| 757 | ++NumCpyToSet; |
| 758 | return true; |
| 759 | } |
Benjamin Kramer | a112087 | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 760 | |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 761 | // The are two possible optimizations we can do for memcpy: |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 762 | // a) memcpy-memcpy xform which exposes redundance for DSE. |
| 763 | // b) call-memcpy xform for return slot optimization. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 764 | MemDepResult DepInfo = MD->getDependency(M); |
| 765 | if (!DepInfo.isClobber()) |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 766 | return false; |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 767 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 768 | if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst())) |
| 769 | return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue()); |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 770 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 771 | if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) { |
Chris Lattner | 8fdca6a | 2010-12-09 07:45:45 +0000 | [diff] [blame] | 772 | if (performCallSlotOptzn(M, M->getDest(), M->getSource(), |
| 773 | CopySize->getZExtValue(), C)) { |
| 774 | M->eraseFromParent(); |
| 775 | return true; |
| 776 | } |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 777 | } |
Owen Anderson | 02e9988 | 2008-04-29 21:51:00 +0000 | [diff] [blame] | 778 | return false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 779 | } |
| 780 | |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 781 | /// processMemMove - Transforms memmove calls to memcpy calls when the src/dst |
| 782 | /// are guaranteed not to alias. |
| 783 | bool MemCpyOpt::processMemMove(MemMoveInst *M) { |
| 784 | AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); |
| 785 | |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 786 | // See if the pointers alias. |
Chris Lattner | 61db1f5 | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 787 | if (!AA.isNoAlias(AA.getLocationForDest(M), AA.getLocationForSource(M))) |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 788 | return false; |
| 789 | |
David Greene | cb33fd1 | 2010-01-05 01:27:47 +0000 | [diff] [blame] | 790 | DEBUG(dbgs() << "MemCpyOpt: Optimizing memmove -> memcpy: " << *M << "\n"); |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 791 | |
| 792 | // If not, then we know we can transform this. |
| 793 | Module *Mod = M->getParent()->getParent()->getParent(); |
Mon P Wang | 20adc9d | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 794 | const Type *ArgTys[3] = { M->getRawDest()->getType(), |
| 795 | M->getRawSource()->getType(), |
| 796 | M->getLength()->getType() }; |
Gabor Greif | a399781 | 2010-07-22 10:37:47 +0000 | [diff] [blame] | 797 | M->setCalledFunction(Intrinsic::getDeclaration(Mod, Intrinsic::memcpy, |
| 798 | ArgTys, 3)); |
Duncan Sands | 05cd03b | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 799 | |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 800 | // MemDep may have over conservative information about this instruction, just |
| 801 | // conservatively flush it from the cache. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 802 | MD->removeInstruction(M); |
Duncan Sands | 05cd03b | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 803 | |
| 804 | ++NumMoveToCpy; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 805 | return true; |
| 806 | } |
| 807 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 808 | /// processByValArgument - This is called on every byval argument in call sites. |
| 809 | bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) { |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 810 | if (TD == 0) return false; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 811 | |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 812 | // Find out what feeds this byval argument. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 813 | Value *ByValArg = CS.getArgument(ArgNo); |
Chris Lattner | b5a3196 | 2010-12-01 01:24:55 +0000 | [diff] [blame] | 814 | const Type *ByValTy =cast<PointerType>(ByValArg->getType())->getElementType(); |
| 815 | uint64_t ByValSize = TD->getTypeAllocSize(ByValTy); |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 816 | MemDepResult DepInfo = |
| 817 | MD->getPointerDependencyFrom(AliasAnalysis::Location(ByValArg, ByValSize), |
| 818 | true, CS.getInstruction(), |
| 819 | CS.getInstruction()->getParent()); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 820 | if (!DepInfo.isClobber()) |
| 821 | return false; |
| 822 | |
| 823 | // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by |
| 824 | // a memcpy, see if we can byval from the source of the memcpy instead of the |
| 825 | // result. |
| 826 | MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()); |
| 827 | if (MDep == 0 || MDep->isVolatile() || |
| 828 | ByValArg->stripPointerCasts() != MDep->getDest()) |
| 829 | return false; |
| 830 | |
| 831 | // The length of the memcpy must be larger or equal to the size of the byval. |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 832 | ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 833 | if (C1 == 0 || C1->getValue().getZExtValue() < ByValSize) |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 834 | return false; |
| 835 | |
| 836 | // Get the alignment of the byval. If it is greater than the memcpy, then we |
| 837 | // can't do the substitution. If the call doesn't specify the alignment, then |
| 838 | // it is some target specific value that we can't know. |
| 839 | unsigned ByValAlign = CS.getParamAlignment(ArgNo+1); |
| 840 | if (ByValAlign == 0 || MDep->getAlignment() < ByValAlign) |
| 841 | return false; |
| 842 | |
| 843 | // Verify that the copied-from memory doesn't change in between the memcpy and |
| 844 | // the byval call. |
| 845 | // memcpy(a <- b) |
| 846 | // *b = 42; |
| 847 | // foo(*a) |
| 848 | // It would be invalid to transform the second memcpy into foo(*b). |
Chris Lattner | 604f6fe | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 849 | // |
| 850 | // NOTE: This is conservative, it will stop on any read from the source loc, |
| 851 | // not just the defining memcpy. |
| 852 | MemDepResult SourceDep = |
| 853 | MD->getPointerDependencyFrom(AliasAnalysis::getLocationForSource(MDep), |
| 854 | false, CS.getInstruction(), MDep->getParent()); |
| 855 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) |
| 856 | return false; |
| 857 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 858 | Value *TmpCast = MDep->getSource(); |
| 859 | if (MDep->getSource()->getType() != ByValArg->getType()) |
| 860 | TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(), |
| 861 | "tmpcast", CS.getInstruction()); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 862 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 863 | DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n" |
| 864 | << " " << *MDep << "\n" |
| 865 | << " " << *CS.getInstruction() << "\n"); |
| 866 | |
| 867 | // Otherwise we're good! Update the byval argument. |
| 868 | CS.setArgument(ArgNo, TmpCast); |
| 869 | ++NumMemCpyInstr; |
| 870 | return true; |
| 871 | } |
| 872 | |
| 873 | /// iterateOnFunction - Executes one iteration of MemCpyOpt. |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 874 | bool MemCpyOpt::iterateOnFunction(Function &F) { |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 875 | bool MadeChange = false; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 876 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 877 | // Walk all instruction in the function. |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 878 | for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) { |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 879 | for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 880 | // Avoid invalidating the iterator. |
| 881 | Instruction *I = BI++; |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 882 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 883 | bool RepeatInstruction = false; |
| 884 | |
Owen Anderson | a8bd658 | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 885 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 886 | MadeChange |= processStore(SI, BI); |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 887 | else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) { |
| 888 | RepeatInstruction = processMemCpy(M); |
| 889 | } else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) { |
| 890 | RepeatInstruction = processMemMove(M); |
| 891 | } else if (CallSite CS = (Value*)I) { |
| 892 | for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) |
| 893 | if (CS.paramHasAttr(i+1, Attribute::ByVal)) |
| 894 | MadeChange |= processByValArgument(CS, i); |
| 895 | } |
| 896 | |
| 897 | // Reprocess the instruction if desired. |
| 898 | if (RepeatInstruction) { |
| 899 | --BI; |
| 900 | MadeChange = true; |
Chris Lattner | f41eaac | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 901 | } |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 902 | } |
| 903 | } |
| 904 | |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 905 | return MadeChange; |
Owen Anderson | a723d1e | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 906 | } |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 907 | |
| 908 | // MemCpyOpt::runOnFunction - This is the main transformation entry point for a |
| 909 | // function. |
| 910 | // |
| 911 | bool MemCpyOpt::runOnFunction(Function &F) { |
| 912 | bool MadeChange = false; |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 913 | MD = &getAnalysis<MemoryDependenceAnalysis>(); |
Chris Lattner | 67a716a | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 914 | TD = getAnalysisIfAvailable<TargetData>(); |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 915 | while (1) { |
| 916 | if (!iterateOnFunction(F)) |
| 917 | break; |
| 918 | MadeChange = true; |
| 919 | } |
| 920 | |
Chris Lattner | 2f5f90a | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 921 | MD = 0; |
Chris Lattner | 61c6ba8 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 922 | return MadeChange; |
| 923 | } |