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