1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===// 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 file implements a trivial dead store elimination that only considers 11 // basic-block local redundant stores. 12 // 13 // FIXME: This should eventually be extended to be a post-dominator tree 14 // traversal. Doing so would be pretty trivial. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Transforms/Scalar.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/Analysis/CaptureTracking.h" 24 #include "llvm/Analysis/MemoryBuiltins.h" 25 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 26 #include "llvm/Analysis/TargetLibraryInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GlobalVariable.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/Pass.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 using namespace llvm; 40 41 #define DEBUG_TYPE "dse" 42 43 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 44 STATISTIC(NumFastStores, "Number of stores deleted"); 45 STATISTIC(NumFastOther , "Number of other instrs removed"); 46 47 namespace { 48 struct DSE : public FunctionPass { 49 AliasAnalysis *AA; 50 MemoryDependenceAnalysis *MD; 51 DominatorTree *DT; 52 const TargetLibraryInfo *TLI; 53 54 static char ID; // Pass identification, replacement for typeid 55 DSE() : FunctionPass(ID), AA(nullptr), MD(nullptr), DT(nullptr) { 56 initializeDSEPass(*PassRegistry::getPassRegistry()); 57 } 58 59 bool runOnFunction(Function &F) override { 60 if (skipOptnoneFunction(F)) 61 return false; 62 63 AA = &getAnalysis<AliasAnalysis>(); 64 MD = &getAnalysis<MemoryDependenceAnalysis>(); 65 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 66 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 67 68 bool Changed = false; 69 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) 70 // Only check non-dead blocks. Dead blocks may have strange pointer 71 // cycles that will confuse alias analysis. 72 if (DT->isReachableFromEntry(I)) 73 Changed |= runOnBasicBlock(*I); 74 75 AA = nullptr; MD = nullptr; DT = nullptr; 76 return Changed; 77 } 78 79 bool runOnBasicBlock(BasicBlock &BB); 80 bool MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI); 81 bool HandleFree(CallInst *F); 82 bool handleEndBlock(BasicBlock &BB); 83 void RemoveAccessedObjects(const MemoryLocation &LoadedLoc, 84 SmallSetVector<Value *, 16> &DeadStackObjects, 85 const DataLayout &DL); 86 87 void getAnalysisUsage(AnalysisUsage &AU) const override { 88 AU.setPreservesCFG(); 89 AU.addRequired<DominatorTreeWrapperPass>(); 90 AU.addRequired<AliasAnalysis>(); 91 AU.addRequired<MemoryDependenceAnalysis>(); 92 AU.addRequired<TargetLibraryInfoWrapperPass>(); 93 AU.addPreserved<AliasAnalysis>(); 94 AU.addPreserved<DominatorTreeWrapperPass>(); 95 AU.addPreserved<MemoryDependenceAnalysis>(); 96 } 97 }; 98 } 99 100 char DSE::ID = 0; 101 INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false) 102 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 103 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 104 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis) 105 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 106 INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false) 107 108 FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); } 109 110 //===----------------------------------------------------------------------===// 111 // Helper functions 112 //===----------------------------------------------------------------------===// 113 114 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through 115 /// and zero out all the operands of this instruction. If any of them become 116 /// dead, delete them and the computation tree that feeds them. 117 /// 118 /// If ValueSet is non-null, remove any deleted instructions from it as well. 119 /// 120 static void DeleteDeadInstruction(Instruction *I, 121 MemoryDependenceAnalysis &MD, 122 const TargetLibraryInfo &TLI, 123 SmallSetVector<Value*, 16> *ValueSet = nullptr) { 124 SmallVector<Instruction*, 32> NowDeadInsts; 125 126 NowDeadInsts.push_back(I); 127 --NumFastOther; 128 129 // Before we touch this instruction, remove it from memdep! 130 do { 131 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 132 ++NumFastOther; 133 134 // This instruction is dead, zap it, in stages. Start by removing it from 135 // MemDep, which needs to know the operands and needs it to be in the 136 // function. 137 MD.removeInstruction(DeadInst); 138 139 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 140 Value *Op = DeadInst->getOperand(op); 141 DeadInst->setOperand(op, nullptr); 142 143 // If this operand just became dead, add it to the NowDeadInsts list. 144 if (!Op->use_empty()) continue; 145 146 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 147 if (isInstructionTriviallyDead(OpI, &TLI)) 148 NowDeadInsts.push_back(OpI); 149 } 150 151 DeadInst->eraseFromParent(); 152 153 if (ValueSet) ValueSet->remove(DeadInst); 154 } while (!NowDeadInsts.empty()); 155 } 156 157 158 /// hasMemoryWrite - Does this instruction write some memory? This only returns 159 /// true for things that we can analyze with other helpers below. 160 static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) { 161 if (isa<StoreInst>(I)) 162 return true; 163 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 164 switch (II->getIntrinsicID()) { 165 default: 166 return false; 167 case Intrinsic::memset: 168 case Intrinsic::memmove: 169 case Intrinsic::memcpy: 170 case Intrinsic::init_trampoline: 171 case Intrinsic::lifetime_end: 172 return true; 173 } 174 } 175 if (auto CS = CallSite(I)) { 176 if (Function *F = CS.getCalledFunction()) { 177 if (TLI.has(LibFunc::strcpy) && 178 F->getName() == TLI.getName(LibFunc::strcpy)) { 179 return true; 180 } 181 if (TLI.has(LibFunc::strncpy) && 182 F->getName() == TLI.getName(LibFunc::strncpy)) { 183 return true; 184 } 185 if (TLI.has(LibFunc::strcat) && 186 F->getName() == TLI.getName(LibFunc::strcat)) { 187 return true; 188 } 189 if (TLI.has(LibFunc::strncat) && 190 F->getName() == TLI.getName(LibFunc::strncat)) { 191 return true; 192 } 193 } 194 } 195 return false; 196 } 197 198 /// getLocForWrite - Return a Location stored to by the specified instruction. 199 /// If isRemovable returns true, this function and getLocForRead completely 200 /// describe the memory operations for this instruction. 201 static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) { 202 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 203 return MemoryLocation::get(SI); 204 205 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) { 206 // memcpy/memmove/memset. 207 MemoryLocation Loc = MemoryLocation::getForDest(MI); 208 return Loc; 209 } 210 211 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst); 212 if (!II) 213 return MemoryLocation(); 214 215 switch (II->getIntrinsicID()) { 216 default: 217 return MemoryLocation(); // Unhandled intrinsic. 218 case Intrinsic::init_trampoline: 219 // FIXME: We don't know the size of the trampoline, so we can't really 220 // handle it here. 221 return MemoryLocation(II->getArgOperand(0)); 222 case Intrinsic::lifetime_end: { 223 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 224 return MemoryLocation(II->getArgOperand(1), Len); 225 } 226 } 227 } 228 229 /// getLocForRead - Return the location read by the specified "hasMemoryWrite" 230 /// instruction if any. 231 static MemoryLocation getLocForRead(Instruction *Inst, 232 const TargetLibraryInfo &TLI) { 233 assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case"); 234 235 // The only instructions that both read and write are the mem transfer 236 // instructions (memcpy/memmove). 237 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst)) 238 return MemoryLocation::getForSource(MTI); 239 return MemoryLocation(); 240 } 241 242 243 /// isRemovable - If the value of this instruction and the memory it writes to 244 /// is unused, may we delete this instruction? 245 static bool isRemovable(Instruction *I) { 246 // Don't remove volatile/atomic stores. 247 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 248 return SI->isUnordered(); 249 250 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 251 switch (II->getIntrinsicID()) { 252 default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate"); 253 case Intrinsic::lifetime_end: 254 // Never remove dead lifetime_end's, e.g. because it is followed by a 255 // free. 256 return false; 257 case Intrinsic::init_trampoline: 258 // Always safe to remove init_trampoline. 259 return true; 260 261 case Intrinsic::memset: 262 case Intrinsic::memmove: 263 case Intrinsic::memcpy: 264 // Don't remove volatile memory intrinsics. 265 return !cast<MemIntrinsic>(II)->isVolatile(); 266 } 267 } 268 269 if (auto CS = CallSite(I)) 270 return CS.getInstruction()->use_empty(); 271 272 return false; 273 } 274 275 276 /// isShortenable - Returns true if this instruction can be safely shortened in 277 /// length. 278 static bool isShortenable(Instruction *I) { 279 // Don't shorten stores for now 280 if (isa<StoreInst>(I)) 281 return false; 282 283 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 284 switch (II->getIntrinsicID()) { 285 default: return false; 286 case Intrinsic::memset: 287 case Intrinsic::memcpy: 288 // Do shorten memory intrinsics. 289 return true; 290 } 291 } 292 293 // Don't shorten libcalls calls for now. 294 295 return false; 296 } 297 298 /// getStoredPointerOperand - Return the pointer that is being written to. 299 static Value *getStoredPointerOperand(Instruction *I) { 300 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 301 return SI->getPointerOperand(); 302 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 303 return MI->getDest(); 304 305 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 306 switch (II->getIntrinsicID()) { 307 default: llvm_unreachable("Unexpected intrinsic!"); 308 case Intrinsic::init_trampoline: 309 return II->getArgOperand(0); 310 } 311 } 312 313 CallSite CS(I); 314 // All the supported functions so far happen to have dest as their first 315 // argument. 316 return CS.getArgument(0); 317 } 318 319 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 320 const TargetLibraryInfo &TLI) { 321 uint64_t Size; 322 if (getObjectSize(V, Size, DL, &TLI)) 323 return Size; 324 return MemoryLocation::UnknownSize; 325 } 326 327 namespace { 328 enum OverwriteResult 329 { 330 OverwriteComplete, 331 OverwriteEnd, 332 OverwriteUnknown 333 }; 334 } 335 336 /// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location 337 /// completely overwrites a store to the 'Earlier' location. 338 /// 'OverwriteEnd' if the end of the 'Earlier' location is completely 339 /// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determined 340 static OverwriteResult isOverwrite(const MemoryLocation &Later, 341 const MemoryLocation &Earlier, 342 const DataLayout &DL, 343 const TargetLibraryInfo &TLI, 344 int64_t &EarlierOff, int64_t &LaterOff) { 345 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 346 const Value *P2 = Later.Ptr->stripPointerCasts(); 347 348 // If the start pointers are the same, we just have to compare sizes to see if 349 // the later store was larger than the earlier store. 350 if (P1 == P2) { 351 // If we don't know the sizes of either access, then we can't do a 352 // comparison. 353 if (Later.Size == MemoryLocation::UnknownSize || 354 Earlier.Size == MemoryLocation::UnknownSize) 355 return OverwriteUnknown; 356 357 // Make sure that the Later size is >= the Earlier size. 358 if (Later.Size >= Earlier.Size) 359 return OverwriteComplete; 360 } 361 362 // Otherwise, we have to have size information, and the later store has to be 363 // larger than the earlier one. 364 if (Later.Size == MemoryLocation::UnknownSize || 365 Earlier.Size == MemoryLocation::UnknownSize) 366 return OverwriteUnknown; 367 368 // Check to see if the later store is to the entire object (either a global, 369 // an alloca, or a byval/inalloca argument). If so, then it clearly 370 // overwrites any other store to the same object. 371 const Value *UO1 = GetUnderlyingObject(P1, DL), 372 *UO2 = GetUnderlyingObject(P2, DL); 373 374 // If we can't resolve the same pointers to the same object, then we can't 375 // analyze them at all. 376 if (UO1 != UO2) 377 return OverwriteUnknown; 378 379 // If the "Later" store is to a recognizable object, get its size. 380 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI); 381 if (ObjectSize != MemoryLocation::UnknownSize) 382 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size) 383 return OverwriteComplete; 384 385 // Okay, we have stores to two completely different pointers. Try to 386 // decompose the pointer into a "base + constant_offset" form. If the base 387 // pointers are equal, then we can reason about the two stores. 388 EarlierOff = 0; 389 LaterOff = 0; 390 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 391 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 392 393 // If the base pointers still differ, we have two completely different stores. 394 if (BP1 != BP2) 395 return OverwriteUnknown; 396 397 // The later store completely overlaps the earlier store if: 398 // 399 // 1. Both start at the same offset and the later one's size is greater than 400 // or equal to the earlier one's, or 401 // 402 // |--earlier--| 403 // |-- later --| 404 // 405 // 2. The earlier store has an offset greater than the later offset, but which 406 // still lies completely within the later store. 407 // 408 // |--earlier--| 409 // |----- later ------| 410 // 411 // We have to be careful here as *Off is signed while *.Size is unsigned. 412 if (EarlierOff >= LaterOff && 413 Later.Size >= Earlier.Size && 414 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size) 415 return OverwriteComplete; 416 417 // The other interesting case is if the later store overwrites the end of 418 // the earlier store 419 // 420 // |--earlier--| 421 // |-- later --| 422 // 423 // In this case we may want to trim the size of earlier to avoid generating 424 // writes to addresses which will definitely be overwritten later 425 if (LaterOff > EarlierOff && 426 LaterOff < int64_t(EarlierOff + Earlier.Size) && 427 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size)) 428 return OverwriteEnd; 429 430 // Otherwise, they don't completely overlap. 431 return OverwriteUnknown; 432 } 433 434 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy of a 435 /// memory region into an identical pointer) then it doesn't actually make its 436 /// input dead in the traditional sense. Consider this case: 437 /// 438 /// memcpy(A <- B) 439 /// memcpy(A <- A) 440 /// 441 /// In this case, the second store to A does not make the first store to A dead. 442 /// The usual situation isn't an explicit A<-A store like this (which can be 443 /// trivially removed) but a case where two pointers may alias. 444 /// 445 /// This function detects when it is unsafe to remove a dependent instruction 446 /// because the DSE inducing instruction may be a self-read. 447 static bool isPossibleSelfRead(Instruction *Inst, 448 const MemoryLocation &InstStoreLoc, 449 Instruction *DepWrite, 450 const TargetLibraryInfo &TLI, 451 AliasAnalysis &AA) { 452 // Self reads can only happen for instructions that read memory. Get the 453 // location read. 454 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI); 455 if (!InstReadLoc.Ptr) return false; // Not a reading instruction. 456 457 // If the read and written loc obviously don't alias, it isn't a read. 458 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false; 459 460 // Okay, 'Inst' may copy over itself. However, we can still remove a the 461 // DepWrite instruction if we can prove that it reads from the same location 462 // as Inst. This handles useful cases like: 463 // memcpy(A <- B) 464 // memcpy(A <- B) 465 // Here we don't know if A/B may alias, but we do know that B/B are must 466 // aliases, so removing the first memcpy is safe (assuming it writes <= # 467 // bytes as the second one. 468 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI); 469 470 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr)) 471 return false; 472 473 // If DepWrite doesn't read memory or if we can't prove it is a must alias, 474 // then it can't be considered dead. 475 return true; 476 } 477 478 479 //===----------------------------------------------------------------------===// 480 // DSE Pass 481 //===----------------------------------------------------------------------===// 482 483 bool DSE::runOnBasicBlock(BasicBlock &BB) { 484 bool MadeChange = false; 485 486 // Do a top-down walk on the BB. 487 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 488 Instruction *Inst = BBI++; 489 490 // Handle 'free' calls specially. 491 if (CallInst *F = isFreeCall(Inst, TLI)) { 492 MadeChange |= HandleFree(F); 493 continue; 494 } 495 496 // If we find something that writes memory, get its memory dependence. 497 if (!hasMemoryWrite(Inst, *TLI)) 498 continue; 499 500 // If we're storing the same value back to a pointer that we just 501 // loaded from, then the store can be removed. 502 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 503 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) { 504 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 505 isRemovable(SI) && 506 MemoryIsNotModifiedBetween(DepLoad, SI)) { 507 508 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n " 509 << "LOAD: " << *DepLoad << "\n STORE: " << *SI << '\n'); 510 511 // DeleteDeadInstruction can delete the current instruction. Save BBI 512 // in case we need it. 513 WeakVH NextInst(BBI); 514 515 DeleteDeadInstruction(SI, *MD, *TLI); 516 517 if (!NextInst) // Next instruction deleted. 518 BBI = BB.begin(); 519 else if (BBI != BB.begin()) // Revisit this instruction if possible. 520 --BBI; 521 ++NumRedundantStores; 522 MadeChange = true; 523 continue; 524 } 525 } 526 } 527 528 MemDepResult InstDep = MD->getDependency(Inst); 529 530 // Ignore any store where we can't find a local dependence. 531 // FIXME: cross-block DSE would be fun. :) 532 if (!InstDep.isDef() && !InstDep.isClobber()) 533 continue; 534 535 // Figure out what location is being stored to. 536 MemoryLocation Loc = getLocForWrite(Inst, *AA); 537 538 // If we didn't get a useful location, fail. 539 if (!Loc.Ptr) 540 continue; 541 542 while (InstDep.isDef() || InstDep.isClobber()) { 543 // Get the memory clobbered by the instruction we depend on. MemDep will 544 // skip any instructions that 'Loc' clearly doesn't interact with. If we 545 // end up depending on a may- or must-aliased load, then we can't optimize 546 // away the store and we bail out. However, if we depend on on something 547 // that overwrites the memory location we *can* potentially optimize it. 548 // 549 // Find out what memory location the dependent instruction stores. 550 Instruction *DepWrite = InstDep.getInst(); 551 MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA); 552 // If we didn't get a useful location, or if it isn't a size, bail out. 553 if (!DepLoc.Ptr) 554 break; 555 556 // If we find a write that is a) removable (i.e., non-volatile), b) is 557 // completely obliterated by the store to 'Loc', and c) which we know that 558 // 'Inst' doesn't load from, then we can remove it. 559 if (isRemovable(DepWrite) && 560 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) { 561 int64_t InstWriteOffset, DepWriteOffset; 562 const DataLayout &DL = BB.getModule()->getDataLayout(); 563 OverwriteResult OR = 564 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset); 565 if (OR == OverwriteComplete) { 566 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " 567 << *DepWrite << "\n KILLER: " << *Inst << '\n'); 568 569 // Delete the store and now-dead instructions that feed it. 570 DeleteDeadInstruction(DepWrite, *MD, *TLI); 571 ++NumFastStores; 572 MadeChange = true; 573 574 // DeleteDeadInstruction can delete the current instruction in loop 575 // cases, reset BBI. 576 BBI = Inst; 577 if (BBI != BB.begin()) 578 --BBI; 579 break; 580 } else if (OR == OverwriteEnd && isShortenable(DepWrite)) { 581 // TODO: base this on the target vector size so that if the earlier 582 // store was too small to get vector writes anyway then its likely 583 // a good idea to shorten it 584 // Power of 2 vector writes are probably always a bad idea to optimize 585 // as any store/memset/memcpy is likely using vector instructions so 586 // shortening it to not vector size is likely to be slower 587 MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite); 588 unsigned DepWriteAlign = DepIntrinsic->getAlignment(); 589 if (llvm::isPowerOf2_64(InstWriteOffset) || 590 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) { 591 592 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW END: " 593 << *DepWrite << "\n KILLER (offset " 594 << InstWriteOffset << ", " 595 << DepLoc.Size << ")" 596 << *Inst << '\n'); 597 598 Value* DepWriteLength = DepIntrinsic->getLength(); 599 Value* TrimmedLength = ConstantInt::get(DepWriteLength->getType(), 600 InstWriteOffset - 601 DepWriteOffset); 602 DepIntrinsic->setLength(TrimmedLength); 603 MadeChange = true; 604 } 605 } 606 } 607 608 // If this is a may-aliased store that is clobbering the store value, we 609 // can keep searching past it for another must-aliased pointer that stores 610 // to the same location. For example, in: 611 // store -> P 612 // store -> Q 613 // store -> P 614 // we can remove the first store to P even though we don't know if P and Q 615 // alias. 616 if (DepWrite == &BB.front()) break; 617 618 // Can't look past this instruction if it might read 'Loc'. 619 if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref) 620 break; 621 622 InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB); 623 } 624 } 625 626 // If this block ends in a return, unwind, or unreachable, all allocas are 627 // dead at its end, which means stores to them are also dead. 628 if (BB.getTerminator()->getNumSuccessors() == 0) 629 MadeChange |= handleEndBlock(BB); 630 631 return MadeChange; 632 } 633 634 /// Returns true if the memory which is accessed by the store instruction is not 635 /// modified between the load and the store instruction. 636 /// Precondition: The store instruction must be dominated by the load 637 /// instruction. 638 bool DSE::MemoryIsNotModifiedBetween(LoadInst *LI, StoreInst *SI) { 639 SmallVector<BasicBlock *, 16> WorkList; 640 SmallPtrSet<BasicBlock *, 8> Visited; 641 BasicBlock::iterator LoadBBI(LI); 642 ++LoadBBI; 643 BasicBlock::iterator StoreBBI(SI); 644 BasicBlock *LoadBB = LI->getParent(); 645 BasicBlock *StoreBB = SI->getParent(); 646 MemoryLocation StoreLoc = MemoryLocation::get(SI); 647 648 // Start checking the store-block. 649 WorkList.push_back(StoreBB); 650 bool isFirstBlock = true; 651 652 // Check all blocks going backward until we reach the load-block. 653 while (!WorkList.empty()) { 654 BasicBlock *B = WorkList.pop_back_val(); 655 656 // Ignore instructions before LI if this is the LoadBB. 657 BasicBlock::iterator BI = (B == LoadBB ? LoadBBI : B->begin()); 658 659 BasicBlock::iterator EI; 660 if (isFirstBlock) { 661 // Ignore instructions after SI if this is the first visit of StoreBB. 662 assert(B == StoreBB && "first block is not the store block"); 663 EI = StoreBBI; 664 isFirstBlock = false; 665 } else { 666 // It's not StoreBB or (in case of a loop) the second visit of StoreBB. 667 // In this case we also have to look at instructions after SI. 668 EI = B->end(); 669 } 670 for (; BI != EI; ++BI) { 671 Instruction *I = BI; 672 if (I->mayWriteToMemory() && I != SI) { 673 auto Res = AA->getModRefInfo(I, StoreLoc); 674 if (Res != MRI_NoModRef) 675 return false; 676 } 677 } 678 if (B != LoadBB) { 679 assert(B != &LoadBB->getParent()->getEntryBlock() && 680 "Should not hit the entry block because SI must be dominated by LI"); 681 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) { 682 if (!Visited.insert(*PredI).second) 683 continue; 684 WorkList.push_back(*PredI); 685 } 686 } 687 } 688 return true; 689 } 690 691 /// Find all blocks that will unconditionally lead to the block BB and append 692 /// them to F. 693 static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks, 694 BasicBlock *BB, DominatorTree *DT) { 695 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 696 BasicBlock *Pred = *I; 697 if (Pred == BB) continue; 698 TerminatorInst *PredTI = Pred->getTerminator(); 699 if (PredTI->getNumSuccessors() != 1) 700 continue; 701 702 if (DT->isReachableFromEntry(Pred)) 703 Blocks.push_back(Pred); 704 } 705 } 706 707 /// HandleFree - Handle frees of entire structures whose dependency is a store 708 /// to a field of that structure. 709 bool DSE::HandleFree(CallInst *F) { 710 bool MadeChange = false; 711 712 MemoryLocation Loc = MemoryLocation(F->getOperand(0)); 713 SmallVector<BasicBlock *, 16> Blocks; 714 Blocks.push_back(F->getParent()); 715 const DataLayout &DL = F->getModule()->getDataLayout(); 716 717 while (!Blocks.empty()) { 718 BasicBlock *BB = Blocks.pop_back_val(); 719 Instruction *InstPt = BB->getTerminator(); 720 if (BB == F->getParent()) InstPt = F; 721 722 MemDepResult Dep = MD->getPointerDependencyFrom(Loc, false, InstPt, BB); 723 while (Dep.isDef() || Dep.isClobber()) { 724 Instruction *Dependency = Dep.getInst(); 725 if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency)) 726 break; 727 728 Value *DepPointer = 729 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL); 730 731 // Check for aliasing. 732 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer)) 733 break; 734 735 Instruction *Next = std::next(BasicBlock::iterator(Dependency)); 736 737 // DCE instructions only used to calculate that store 738 DeleteDeadInstruction(Dependency, *MD, *TLI); 739 ++NumFastStores; 740 MadeChange = true; 741 742 // Inst's old Dependency is now deleted. Compute the next dependency, 743 // which may also be dead, as in 744 // s[0] = 0; 745 // s[1] = 0; // This has just been deleted. 746 // free(s); 747 Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB); 748 } 749 750 if (Dep.isNonLocal()) 751 FindUnconditionalPreds(Blocks, BB, DT); 752 } 753 754 return MadeChange; 755 } 756 757 /// handleEndBlock - Remove dead stores to stack-allocated locations in the 758 /// function end block. Ex: 759 /// %A = alloca i32 760 /// ... 761 /// store i32 1, i32* %A 762 /// ret void 763 bool DSE::handleEndBlock(BasicBlock &BB) { 764 bool MadeChange = false; 765 766 // Keep track of all of the stack objects that are dead at the end of the 767 // function. 768 SmallSetVector<Value*, 16> DeadStackObjects; 769 770 // Find all of the alloca'd pointers in the entry block. 771 BasicBlock *Entry = BB.getParent()->begin(); 772 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) { 773 if (isa<AllocaInst>(I)) 774 DeadStackObjects.insert(I); 775 776 // Okay, so these are dead heap objects, but if the pointer never escapes 777 // then it's leaked by this function anyways. 778 else if (isAllocLikeFn(I, TLI) && !PointerMayBeCaptured(I, true, true)) 779 DeadStackObjects.insert(I); 780 } 781 782 // Treat byval or inalloca arguments the same, stores to them are dead at the 783 // end of the function. 784 for (Function::arg_iterator AI = BB.getParent()->arg_begin(), 785 AE = BB.getParent()->arg_end(); AI != AE; ++AI) 786 if (AI->hasByValOrInAllocaAttr()) 787 DeadStackObjects.insert(AI); 788 789 const DataLayout &DL = BB.getModule()->getDataLayout(); 790 791 // Scan the basic block backwards 792 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 793 --BBI; 794 795 // If we find a store, check to see if it points into a dead stack value. 796 if (hasMemoryWrite(BBI, *TLI) && isRemovable(BBI)) { 797 // See through pointer-to-pointer bitcasts 798 SmallVector<Value *, 4> Pointers; 799 GetUnderlyingObjects(getStoredPointerOperand(BBI), Pointers, DL); 800 801 // Stores to stack values are valid candidates for removal. 802 bool AllDead = true; 803 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(), 804 E = Pointers.end(); I != E; ++I) 805 if (!DeadStackObjects.count(*I)) { 806 AllDead = false; 807 break; 808 } 809 810 if (AllDead) { 811 Instruction *Dead = BBI++; 812 813 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: " 814 << *Dead << "\n Objects: "; 815 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(), 816 E = Pointers.end(); I != E; ++I) { 817 dbgs() << **I; 818 if (std::next(I) != E) 819 dbgs() << ", "; 820 } 821 dbgs() << '\n'); 822 823 // DCE instructions only used to calculate that store. 824 DeleteDeadInstruction(Dead, *MD, *TLI, &DeadStackObjects); 825 ++NumFastStores; 826 MadeChange = true; 827 continue; 828 } 829 } 830 831 // Remove any dead non-memory-mutating instructions. 832 if (isInstructionTriviallyDead(BBI, TLI)) { 833 Instruction *Inst = BBI++; 834 DeleteDeadInstruction(Inst, *MD, *TLI, &DeadStackObjects); 835 ++NumFastOther; 836 MadeChange = true; 837 continue; 838 } 839 840 if (isa<AllocaInst>(BBI)) { 841 // Remove allocas from the list of dead stack objects; there can't be 842 // any references before the definition. 843 DeadStackObjects.remove(BBI); 844 continue; 845 } 846 847 if (auto CS = CallSite(BBI)) { 848 // Remove allocation function calls from the list of dead stack objects; 849 // there can't be any references before the definition. 850 if (isAllocLikeFn(BBI, TLI)) 851 DeadStackObjects.remove(BBI); 852 853 // If this call does not access memory, it can't be loading any of our 854 // pointers. 855 if (AA->doesNotAccessMemory(CS)) 856 continue; 857 858 // If the call might load from any of our allocas, then any store above 859 // the call is live. 860 DeadStackObjects.remove_if([&](Value *I) { 861 // See if the call site touches the value. 862 ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI)); 863 864 return A == MRI_ModRef || A == MRI_Ref; 865 }); 866 867 // If all of the allocas were clobbered by the call then we're not going 868 // to find anything else to process. 869 if (DeadStackObjects.empty()) 870 break; 871 872 continue; 873 } 874 875 MemoryLocation LoadedLoc; 876 877 // If we encounter a use of the pointer, it is no longer considered dead 878 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 879 if (!L->isUnordered()) // Be conservative with atomic/volatile load 880 break; 881 LoadedLoc = MemoryLocation::get(L); 882 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 883 LoadedLoc = MemoryLocation::get(V); 884 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) { 885 LoadedLoc = MemoryLocation::getForSource(MTI); 886 } else if (!BBI->mayReadFromMemory()) { 887 // Instruction doesn't read memory. Note that stores that weren't removed 888 // above will hit this case. 889 continue; 890 } else { 891 // Unknown inst; assume it clobbers everything. 892 break; 893 } 894 895 // Remove any allocas from the DeadPointer set that are loaded, as this 896 // makes any stores above the access live. 897 RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL); 898 899 // If all of the allocas were clobbered by the access then we're not going 900 // to find anything else to process. 901 if (DeadStackObjects.empty()) 902 break; 903 } 904 905 return MadeChange; 906 } 907 908 /// RemoveAccessedObjects - Check to see if the specified location may alias any 909 /// of the stack objects in the DeadStackObjects set. If so, they become live 910 /// because the location is being loaded. 911 void DSE::RemoveAccessedObjects(const MemoryLocation &LoadedLoc, 912 SmallSetVector<Value *, 16> &DeadStackObjects, 913 const DataLayout &DL) { 914 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL); 915 916 // A constant can't be in the dead pointer set. 917 if (isa<Constant>(UnderlyingPointer)) 918 return; 919 920 // If the kill pointer can be easily reduced to an alloca, don't bother doing 921 // extraneous AA queries. 922 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) { 923 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer)); 924 return; 925 } 926 927 // Remove objects that could alias LoadedLoc. 928 DeadStackObjects.remove_if([&](Value *I) { 929 // See if the loaded location could alias the stack location. 930 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI)); 931 return !AA->isNoAlias(StackLoc, LoadedLoc); 932 }); 933 } 934