1 //===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements a trivial dead store elimination that only considers 10 // basic-block local redundant stores. 11 // 12 // FIXME: This should eventually be extended to be a post-dominator tree 13 // traversal. Doing so would be pretty trivial. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 18 #include "llvm/ADT/APInt.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/MapVector.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/CaptureTracking.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/MemorySSA.h" 33 #include "llvm/Analysis/MemorySSAUpdater.h" 34 #include "llvm/Analysis/OrderedBasicBlock.h" 35 #include "llvm/Analysis/PostDominators.h" 36 #include "llvm/Analysis/TargetLibraryInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/IR/Argument.h" 39 #include "llvm/IR/BasicBlock.h" 40 #include "llvm/IR/CallSite.h" 41 #include "llvm/IR/Constant.h" 42 #include "llvm/IR/Constants.h" 43 #include "llvm/IR/DataLayout.h" 44 #include "llvm/IR/Dominators.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/InstIterator.h" 47 #include "llvm/IR/InstrTypes.h" 48 #include "llvm/IR/Instruction.h" 49 #include "llvm/IR/Instructions.h" 50 #include "llvm/IR/IntrinsicInst.h" 51 #include "llvm/IR/Intrinsics.h" 52 #include "llvm/IR/LLVMContext.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/PassManager.h" 55 #include "llvm/IR/Value.h" 56 #include "llvm/InitializePasses.h" 57 #include "llvm/Pass.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/MathExtras.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/Transforms/Scalar.h" 65 #include "llvm/Transforms/Utils/Local.h" 66 #include <algorithm> 67 #include <cassert> 68 #include <cstddef> 69 #include <cstdint> 70 #include <iterator> 71 #include <map> 72 #include <utility> 73 74 using namespace llvm; 75 76 #define DEBUG_TYPE "dse" 77 78 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 79 STATISTIC(NumFastStores, "Number of stores deleted"); 80 STATISTIC(NumFastOther, "Number of other instrs removed"); 81 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 82 STATISTIC(NumModifiedStores, "Number of stores modified"); 83 84 static cl::opt<bool> 85 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 86 cl::init(true), cl::Hidden, 87 cl::desc("Enable partial-overwrite tracking in DSE")); 88 89 static cl::opt<bool> 90 EnablePartialStoreMerging("enable-dse-partial-store-merging", 91 cl::init(true), cl::Hidden, 92 cl::desc("Enable partial store merging in DSE")); 93 94 static cl::opt<bool> 95 EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden, 96 cl::desc("Use the new MemorySSA-backed DSE.")); 97 98 static cl::opt<unsigned> 99 MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(100), cl::Hidden, 100 cl::desc("The number of memory instructions to scan for " 101 "dead store elimination (default = 100)")); 102 103 static cl::opt<unsigned> MemorySSADefsPerBlockLimit( 104 "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden, 105 cl::desc("The number of MemoryDefs we consider as candidates to eliminated " 106 "other stores per basic block (default = 5000)")); 107 108 //===----------------------------------------------------------------------===// 109 // Helper functions 110 //===----------------------------------------------------------------------===// 111 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 112 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 113 114 /// Delete this instruction. Before we do, go through and zero out all the 115 /// operands of this instruction. If any of them become dead, delete them and 116 /// the computation tree that feeds them. 117 /// If ValueSet is non-null, remove any deleted instructions from it as well. 118 static void 119 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI, 120 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI, 121 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB, 122 MapVector<Instruction *, bool> &ThrowableInst, 123 SmallSetVector<const Value *, 16> *ValueSet = nullptr) { 124 SmallVector<Instruction*, 32> NowDeadInsts; 125 126 NowDeadInsts.push_back(I); 127 --NumFastOther; 128 129 // Keeping the iterator straight is a pain, so we let this routine tell the 130 // caller what the next instruction is after we're done mucking about. 131 BasicBlock::iterator NewIter = *BBI; 132 133 // Before we touch this instruction, remove it from memdep! 134 do { 135 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 136 // Mark the DeadInst as dead in the list of throwable instructions. 137 auto It = ThrowableInst.find(DeadInst); 138 if (It != ThrowableInst.end()) 139 ThrowableInst[It->first] = false; 140 ++NumFastOther; 141 142 // Try to preserve debug information attached to the dead instruction. 143 salvageDebugInfo(*DeadInst); 144 145 // This instruction is dead, zap it, in stages. Start by removing it from 146 // MemDep, which needs to know the operands and needs it to be in the 147 // function. 148 MD.removeInstruction(DeadInst); 149 150 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 151 Value *Op = DeadInst->getOperand(op); 152 DeadInst->setOperand(op, nullptr); 153 154 // If this operand just became dead, add it to the NowDeadInsts list. 155 if (!Op->use_empty()) continue; 156 157 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 158 if (isInstructionTriviallyDead(OpI, &TLI)) 159 NowDeadInsts.push_back(OpI); 160 } 161 162 if (ValueSet) ValueSet->remove(DeadInst); 163 IOL.erase(DeadInst); 164 OBB.eraseInstruction(DeadInst); 165 166 if (NewIter == DeadInst->getIterator()) 167 NewIter = DeadInst->eraseFromParent(); 168 else 169 DeadInst->eraseFromParent(); 170 } while (!NowDeadInsts.empty()); 171 *BBI = NewIter; 172 // Pop dead entries from back of ThrowableInst till we find an alive entry. 173 while (!ThrowableInst.empty() && !ThrowableInst.back().second) 174 ThrowableInst.pop_back(); 175 } 176 177 /// Does this instruction write some memory? This only returns true for things 178 /// that we can analyze with other helpers below. 179 static bool hasAnalyzableMemoryWrite(Instruction *I, 180 const TargetLibraryInfo &TLI) { 181 if (isa<StoreInst>(I)) 182 return true; 183 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 184 switch (II->getIntrinsicID()) { 185 default: 186 return false; 187 case Intrinsic::memset: 188 case Intrinsic::memmove: 189 case Intrinsic::memcpy: 190 case Intrinsic::memcpy_element_unordered_atomic: 191 case Intrinsic::memmove_element_unordered_atomic: 192 case Intrinsic::memset_element_unordered_atomic: 193 case Intrinsic::init_trampoline: 194 case Intrinsic::lifetime_end: 195 return true; 196 } 197 } 198 if (auto CS = CallSite(I)) { 199 if (Function *F = CS.getCalledFunction()) { 200 LibFunc LF; 201 if (TLI.getLibFunc(*F, LF) && TLI.has(LF)) { 202 switch (LF) { 203 case LibFunc_strcpy: 204 case LibFunc_strncpy: 205 case LibFunc_strcat: 206 case LibFunc_strncat: 207 return true; 208 default: 209 return false; 210 } 211 } 212 } 213 } 214 return false; 215 } 216 217 /// Return a Location stored to by the specified instruction. If isRemovable 218 /// returns true, this function and getLocForRead completely describe the memory 219 /// operations for this instruction. 220 static MemoryLocation getLocForWrite(Instruction *Inst) { 221 222 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 223 return MemoryLocation::get(SI); 224 225 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) { 226 // memcpy/memmove/memset. 227 MemoryLocation Loc = MemoryLocation::getForDest(MI); 228 return Loc; 229 } 230 231 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 232 switch (II->getIntrinsicID()) { 233 default: 234 return MemoryLocation(); // Unhandled intrinsic. 235 case Intrinsic::init_trampoline: 236 return MemoryLocation(II->getArgOperand(0)); 237 case Intrinsic::lifetime_end: { 238 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 239 return MemoryLocation(II->getArgOperand(1), Len); 240 } 241 } 242 } 243 if (auto CS = CallSite(Inst)) 244 // All the supported TLI functions so far happen to have dest as their 245 // first argument. 246 return MemoryLocation(CS.getArgument(0)); 247 return MemoryLocation(); 248 } 249 250 /// Return the location read by the specified "hasAnalyzableMemoryWrite" 251 /// instruction if any. 252 static MemoryLocation getLocForRead(Instruction *Inst, 253 const TargetLibraryInfo &TLI) { 254 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case"); 255 256 // The only instructions that both read and write are the mem transfer 257 // instructions (memcpy/memmove). 258 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst)) 259 return MemoryLocation::getForSource(MTI); 260 return MemoryLocation(); 261 } 262 263 /// If the value of this instruction and the memory it writes to is unused, may 264 /// we delete this instruction? 265 static bool isRemovable(Instruction *I) { 266 // Don't remove volatile/atomic stores. 267 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 268 return SI->isUnordered(); 269 270 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 271 switch (II->getIntrinsicID()) { 272 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate"); 273 case Intrinsic::lifetime_end: 274 // Never remove dead lifetime_end's, e.g. because it is followed by a 275 // free. 276 return false; 277 case Intrinsic::init_trampoline: 278 // Always safe to remove init_trampoline. 279 return true; 280 case Intrinsic::memset: 281 case Intrinsic::memmove: 282 case Intrinsic::memcpy: 283 // Don't remove volatile memory intrinsics. 284 return !cast<MemIntrinsic>(II)->isVolatile(); 285 case Intrinsic::memcpy_element_unordered_atomic: 286 case Intrinsic::memmove_element_unordered_atomic: 287 case Intrinsic::memset_element_unordered_atomic: 288 return true; 289 } 290 } 291 292 // note: only get here for calls with analyzable writes - i.e. libcalls 293 if (auto CS = CallSite(I)) 294 return CS.getInstruction()->use_empty(); 295 296 return false; 297 } 298 299 /// Returns true if the end of this instruction can be safely shortened in 300 /// length. 301 static bool isShortenableAtTheEnd(Instruction *I) { 302 // Don't shorten stores for now 303 if (isa<StoreInst>(I)) 304 return false; 305 306 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 307 switch (II->getIntrinsicID()) { 308 default: return false; 309 case Intrinsic::memset: 310 case Intrinsic::memcpy: 311 case Intrinsic::memcpy_element_unordered_atomic: 312 case Intrinsic::memset_element_unordered_atomic: 313 // Do shorten memory intrinsics. 314 // FIXME: Add memmove if it's also safe to transform. 315 return true; 316 } 317 } 318 319 // Don't shorten libcalls calls for now. 320 321 return false; 322 } 323 324 /// Returns true if the beginning of this instruction can be safely shortened 325 /// in length. 326 static bool isShortenableAtTheBeginning(Instruction *I) { 327 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 328 // easily done by offsetting the source address. 329 return isa<AnyMemSetInst>(I); 330 } 331 332 /// Return the pointer that is being written to. 333 static Value *getStoredPointerOperand(Instruction *I) { 334 //TODO: factor this to reuse getLocForWrite 335 MemoryLocation Loc = getLocForWrite(I); 336 assert(Loc.Ptr && 337 "unable to find pointer written for analyzable instruction?"); 338 // TODO: most APIs don't expect const Value * 339 return const_cast<Value*>(Loc.Ptr); 340 } 341 342 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 343 const TargetLibraryInfo &TLI, 344 const Function *F) { 345 uint64_t Size; 346 ObjectSizeOpts Opts; 347 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 348 349 if (getObjectSize(V, Size, DL, &TLI, Opts)) 350 return Size; 351 return MemoryLocation::UnknownSize; 352 } 353 354 namespace { 355 356 enum OverwriteResult { 357 OW_Begin, 358 OW_Complete, 359 OW_End, 360 OW_PartialEarlierWithFullLater, 361 OW_Unknown 362 }; 363 364 } // end anonymous namespace 365 366 /// Return 'OW_Complete' if a store to the 'Later' location completely 367 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the 368 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the 369 /// beginning of the 'Earlier' location is overwritten by 'Later'. 370 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was 371 /// overwritten by a latter (smaller) store which doesn't write outside the big 372 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 373 static OverwriteResult isOverwrite(const MemoryLocation &Later, 374 const MemoryLocation &Earlier, 375 const DataLayout &DL, 376 const TargetLibraryInfo &TLI, 377 int64_t &EarlierOff, int64_t &LaterOff, 378 Instruction *DepWrite, 379 InstOverlapIntervalsTy &IOL, 380 AliasAnalysis &AA, 381 const Function *F) { 382 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 383 // get imprecise values here, though (except for unknown sizes). 384 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise()) 385 return OW_Unknown; 386 387 const uint64_t LaterSize = Later.Size.getValue(); 388 const uint64_t EarlierSize = Earlier.Size.getValue(); 389 390 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 391 const Value *P2 = Later.Ptr->stripPointerCasts(); 392 393 // If the start pointers are the same, we just have to compare sizes to see if 394 // the later store was larger than the earlier store. 395 if (P1 == P2 || AA.isMustAlias(P1, P2)) { 396 // Make sure that the Later size is >= the Earlier size. 397 if (LaterSize >= EarlierSize) 398 return OW_Complete; 399 } 400 401 // Check to see if the later store is to the entire object (either a global, 402 // an alloca, or a byval/inalloca argument). If so, then it clearly 403 // overwrites any other store to the same object. 404 const Value *UO1 = GetUnderlyingObject(P1, DL), 405 *UO2 = GetUnderlyingObject(P2, DL); 406 407 // If we can't resolve the same pointers to the same object, then we can't 408 // analyze them at all. 409 if (UO1 != UO2) 410 return OW_Unknown; 411 412 // If the "Later" store is to a recognizable object, get its size. 413 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F); 414 if (ObjectSize != MemoryLocation::UnknownSize) 415 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize) 416 return OW_Complete; 417 418 // Okay, we have stores to two completely different pointers. Try to 419 // decompose the pointer into a "base + constant_offset" form. If the base 420 // pointers are equal, then we can reason about the two stores. 421 EarlierOff = 0; 422 LaterOff = 0; 423 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 424 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 425 426 // If the base pointers still differ, we have two completely different stores. 427 if (BP1 != BP2) 428 return OW_Unknown; 429 430 // The later store completely overlaps the earlier store if: 431 // 432 // 1. Both start at the same offset and the later one's size is greater than 433 // or equal to the earlier one's, or 434 // 435 // |--earlier--| 436 // |-- later --| 437 // 438 // 2. The earlier store has an offset greater than the later offset, but which 439 // still lies completely within the later store. 440 // 441 // |--earlier--| 442 // |----- later ------| 443 // 444 // We have to be careful here as *Off is signed while *.Size is unsigned. 445 if (EarlierOff >= LaterOff && 446 LaterSize >= EarlierSize && 447 uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize) 448 return OW_Complete; 449 450 // We may now overlap, although the overlap is not complete. There might also 451 // be other incomplete overlaps, and together, they might cover the complete 452 // earlier write. 453 // Note: The correctness of this logic depends on the fact that this function 454 // is not even called providing DepWrite when there are any intervening reads. 455 if (EnablePartialOverwriteTracking && 456 LaterOff < int64_t(EarlierOff + EarlierSize) && 457 int64_t(LaterOff + LaterSize) >= EarlierOff) { 458 459 // Insert our part of the overlap into the map. 460 auto &IM = IOL[DepWrite]; 461 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff 462 << ", " << int64_t(EarlierOff + EarlierSize) 463 << ") Later [" << LaterOff << ", " 464 << int64_t(LaterOff + LaterSize) << ")\n"); 465 466 // Make sure that we only insert non-overlapping intervals and combine 467 // adjacent intervals. The intervals are stored in the map with the ending 468 // offset as the key (in the half-open sense) and the starting offset as 469 // the value. 470 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize; 471 472 // Find any intervals ending at, or after, LaterIntStart which start 473 // before LaterIntEnd. 474 auto ILI = IM.lower_bound(LaterIntStart); 475 if (ILI != IM.end() && ILI->second <= LaterIntEnd) { 476 // This existing interval is overlapped with the current store somewhere 477 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing 478 // intervals and adjusting our start and end. 479 LaterIntStart = std::min(LaterIntStart, ILI->second); 480 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 481 ILI = IM.erase(ILI); 482 483 // Continue erasing and adjusting our end in case other previous 484 // intervals are also overlapped with the current store. 485 // 486 // |--- ealier 1 ---| |--- ealier 2 ---| 487 // |------- later---------| 488 // 489 while (ILI != IM.end() && ILI->second <= LaterIntEnd) { 490 assert(ILI->second > LaterIntStart && "Unexpected interval"); 491 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 492 ILI = IM.erase(ILI); 493 } 494 } 495 496 IM[LaterIntEnd] = LaterIntStart; 497 498 ILI = IM.begin(); 499 if (ILI->second <= EarlierOff && 500 ILI->first >= int64_t(EarlierOff + EarlierSize)) { 501 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" 502 << EarlierOff << ", " 503 << int64_t(EarlierOff + EarlierSize) 504 << ") Composite Later [" << ILI->second << ", " 505 << ILI->first << ")\n"); 506 ++NumCompletePartials; 507 return OW_Complete; 508 } 509 } 510 511 // Check for an earlier store which writes to all the memory locations that 512 // the later store writes to. 513 if (EnablePartialStoreMerging && LaterOff >= EarlierOff && 514 int64_t(EarlierOff + EarlierSize) > LaterOff && 515 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) { 516 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" 517 << EarlierOff << ", " 518 << int64_t(EarlierOff + EarlierSize) 519 << ") by a later store [" << LaterOff << ", " 520 << int64_t(LaterOff + LaterSize) << ")\n"); 521 // TODO: Maybe come up with a better name? 522 return OW_PartialEarlierWithFullLater; 523 } 524 525 // Another interesting case is if the later store overwrites the end of the 526 // earlier store. 527 // 528 // |--earlier--| 529 // |-- later --| 530 // 531 // In this case we may want to trim the size of earlier to avoid generating 532 // writes to addresses which will definitely be overwritten later 533 if (!EnablePartialOverwriteTracking && 534 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) && 535 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize))) 536 return OW_End; 537 538 // Finally, we also need to check if the later store overwrites the beginning 539 // of the earlier store. 540 // 541 // |--earlier--| 542 // |-- later --| 543 // 544 // In this case we may want to move the destination address and trim the size 545 // of earlier to avoid generating writes to addresses which will definitely 546 // be overwritten later. 547 if (!EnablePartialOverwriteTracking && 548 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) { 549 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) && 550 "Expect to be handled as OW_Complete"); 551 return OW_Begin; 552 } 553 // Otherwise, they don't completely overlap. 554 return OW_Unknown; 555 } 556 557 /// If 'Inst' might be a self read (i.e. a noop copy of a 558 /// memory region into an identical pointer) then it doesn't actually make its 559 /// input dead in the traditional sense. Consider this case: 560 /// 561 /// memmove(A <- B) 562 /// memmove(A <- A) 563 /// 564 /// In this case, the second store to A does not make the first store to A dead. 565 /// The usual situation isn't an explicit A<-A store like this (which can be 566 /// trivially removed) but a case where two pointers may alias. 567 /// 568 /// This function detects when it is unsafe to remove a dependent instruction 569 /// because the DSE inducing instruction may be a self-read. 570 static bool isPossibleSelfRead(Instruction *Inst, 571 const MemoryLocation &InstStoreLoc, 572 Instruction *DepWrite, 573 const TargetLibraryInfo &TLI, 574 AliasAnalysis &AA) { 575 // Self reads can only happen for instructions that read memory. Get the 576 // location read. 577 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI); 578 if (!InstReadLoc.Ptr) 579 return false; // Not a reading instruction. 580 581 // If the read and written loc obviously don't alias, it isn't a read. 582 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) 583 return false; 584 585 if (isa<AnyMemCpyInst>(Inst)) { 586 // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763) 587 // but in practice memcpy(A <- B) either means that A and B are disjoint or 588 // are equal (i.e. there are not partial overlaps). Given that, if we have: 589 // 590 // memcpy/memmove(A <- B) // DepWrite 591 // memcpy(A <- B) // Inst 592 // 593 // with Inst reading/writing a >= size than DepWrite, we can reason as 594 // follows: 595 // 596 // - If A == B then both the copies are no-ops, so the DepWrite can be 597 // removed. 598 // - If A != B then A and B are disjoint locations in Inst. Since 599 // Inst.size >= DepWrite.size A and B are disjoint in DepWrite too. 600 // Therefore DepWrite can be removed. 601 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI); 602 603 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr)) 604 return false; 605 } 606 607 // If DepWrite doesn't read memory or if we can't prove it is a must alias, 608 // then it can't be considered dead. 609 return true; 610 } 611 612 /// Returns true if the memory which is accessed by the second instruction is not 613 /// modified between the first and the second instruction. 614 /// Precondition: Second instruction must be dominated by the first 615 /// instruction. 616 static bool memoryIsNotModifiedBetween(Instruction *FirstI, 617 Instruction *SecondI, 618 AliasAnalysis *AA) { 619 SmallVector<BasicBlock *, 16> WorkList; 620 SmallPtrSet<BasicBlock *, 8> Visited; 621 BasicBlock::iterator FirstBBI(FirstI); 622 ++FirstBBI; 623 BasicBlock::iterator SecondBBI(SecondI); 624 BasicBlock *FirstBB = FirstI->getParent(); 625 BasicBlock *SecondBB = SecondI->getParent(); 626 MemoryLocation MemLoc = MemoryLocation::get(SecondI); 627 628 // Start checking the SecondBB. 629 WorkList.push_back(SecondBB); 630 bool isFirstBlock = true; 631 632 // Check all blocks going backward until we reach the FirstBB. 633 while (!WorkList.empty()) { 634 BasicBlock *B = WorkList.pop_back_val(); 635 636 // Ignore instructions before FirstI if this is the FirstBB. 637 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 638 639 BasicBlock::iterator EI; 640 if (isFirstBlock) { 641 // Ignore instructions after SecondI if this is the first visit of SecondBB. 642 assert(B == SecondBB && "first block is not the store block"); 643 EI = SecondBBI; 644 isFirstBlock = false; 645 } else { 646 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 647 // In this case we also have to look at instructions after SecondI. 648 EI = B->end(); 649 } 650 for (; BI != EI; ++BI) { 651 Instruction *I = &*BI; 652 if (I->mayWriteToMemory() && I != SecondI) 653 if (isModSet(AA->getModRefInfo(I, MemLoc))) 654 return false; 655 } 656 if (B != FirstBB) { 657 assert(B != &FirstBB->getParent()->getEntryBlock() && 658 "Should not hit the entry block because SI must be dominated by LI"); 659 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) { 660 if (!Visited.insert(*PredI).second) 661 continue; 662 WorkList.push_back(*PredI); 663 } 664 } 665 } 666 return true; 667 } 668 669 /// Find all blocks that will unconditionally lead to the block BB and append 670 /// them to F. 671 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks, 672 BasicBlock *BB, DominatorTree *DT) { 673 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 674 BasicBlock *Pred = *I; 675 if (Pred == BB) continue; 676 Instruction *PredTI = Pred->getTerminator(); 677 if (PredTI->getNumSuccessors() != 1) 678 continue; 679 680 if (DT->isReachableFromEntry(Pred)) 681 Blocks.push_back(Pred); 682 } 683 } 684 685 /// Handle frees of entire structures whose dependency is a store 686 /// to a field of that structure. 687 static bool handleFree(CallInst *F, AliasAnalysis *AA, 688 MemoryDependenceResults *MD, DominatorTree *DT, 689 const TargetLibraryInfo *TLI, 690 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB, 691 MapVector<Instruction *, bool> &ThrowableInst) { 692 bool MadeChange = false; 693 694 MemoryLocation Loc = MemoryLocation(F->getOperand(0)); 695 SmallVector<BasicBlock *, 16> Blocks; 696 Blocks.push_back(F->getParent()); 697 const DataLayout &DL = F->getModule()->getDataLayout(); 698 699 while (!Blocks.empty()) { 700 BasicBlock *BB = Blocks.pop_back_val(); 701 Instruction *InstPt = BB->getTerminator(); 702 if (BB == F->getParent()) InstPt = F; 703 704 MemDepResult Dep = 705 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB); 706 while (Dep.isDef() || Dep.isClobber()) { 707 Instruction *Dependency = Dep.getInst(); 708 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) || 709 !isRemovable(Dependency)) 710 break; 711 712 Value *DepPointer = 713 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL); 714 715 // Check for aliasing. 716 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer)) 717 break; 718 719 LLVM_DEBUG( 720 dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: " 721 << *Dependency << '\n'); 722 723 // DCE instructions only used to calculate that store. 724 BasicBlock::iterator BBI(Dependency); 725 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, OBB, 726 ThrowableInst); 727 ++NumFastStores; 728 MadeChange = true; 729 730 // Inst's old Dependency is now deleted. Compute the next dependency, 731 // which may also be dead, as in 732 // s[0] = 0; 733 // s[1] = 0; // This has just been deleted. 734 // free(s); 735 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB); 736 } 737 738 if (Dep.isNonLocal()) 739 findUnconditionalPreds(Blocks, BB, DT); 740 } 741 742 return MadeChange; 743 } 744 745 /// Check to see if the specified location may alias any of the stack objects in 746 /// the DeadStackObjects set. If so, they become live because the location is 747 /// being loaded. 748 static void removeAccessedObjects(const MemoryLocation &LoadedLoc, 749 SmallSetVector<const Value *, 16> &DeadStackObjects, 750 const DataLayout &DL, AliasAnalysis *AA, 751 const TargetLibraryInfo *TLI, 752 const Function *F) { 753 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL); 754 755 // A constant can't be in the dead pointer set. 756 if (isa<Constant>(UnderlyingPointer)) 757 return; 758 759 // If the kill pointer can be easily reduced to an alloca, don't bother doing 760 // extraneous AA queries. 761 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) { 762 DeadStackObjects.remove(UnderlyingPointer); 763 return; 764 } 765 766 // Remove objects that could alias LoadedLoc. 767 DeadStackObjects.remove_if([&](const Value *I) { 768 // See if the loaded location could alias the stack location. 769 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F)); 770 return !AA->isNoAlias(StackLoc, LoadedLoc); 771 }); 772 } 773 774 /// Remove dead stores to stack-allocated locations in the function end block. 775 /// Ex: 776 /// %A = alloca i32 777 /// ... 778 /// store i32 1, i32* %A 779 /// ret void 780 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA, 781 MemoryDependenceResults *MD, 782 const TargetLibraryInfo *TLI, 783 InstOverlapIntervalsTy &IOL, OrderedBasicBlock &OBB, 784 MapVector<Instruction *, bool> &ThrowableInst) { 785 bool MadeChange = false; 786 787 // Keep track of all of the stack objects that are dead at the end of the 788 // function. 789 SmallSetVector<const Value*, 16> DeadStackObjects; 790 791 // Find all of the alloca'd pointers in the entry block. 792 BasicBlock &Entry = BB.getParent()->front(); 793 for (Instruction &I : Entry) { 794 if (isa<AllocaInst>(&I)) 795 DeadStackObjects.insert(&I); 796 797 // Okay, so these are dead heap objects, but if the pointer never escapes 798 // then it's leaked by this function anyways. 799 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true)) 800 DeadStackObjects.insert(&I); 801 } 802 803 // Treat byval or inalloca arguments the same, stores to them are dead at the 804 // end of the function. 805 for (Argument &AI : BB.getParent()->args()) 806 if (AI.hasByValOrInAllocaAttr()) 807 DeadStackObjects.insert(&AI); 808 809 const DataLayout &DL = BB.getModule()->getDataLayout(); 810 811 // Scan the basic block backwards 812 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 813 --BBI; 814 815 // If we find a store, check to see if it points into a dead stack value. 816 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) { 817 // See through pointer-to-pointer bitcasts 818 SmallVector<const Value *, 4> Pointers; 819 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL); 820 821 // Stores to stack values are valid candidates for removal. 822 bool AllDead = true; 823 for (const Value *Pointer : Pointers) 824 if (!DeadStackObjects.count(Pointer)) { 825 AllDead = false; 826 break; 827 } 828 829 if (AllDead) { 830 Instruction *Dead = &*BBI; 831 832 LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: " 833 << *Dead << "\n Objects: "; 834 for (SmallVectorImpl<const Value *>::iterator I = 835 Pointers.begin(), 836 E = Pointers.end(); 837 I != E; ++I) { 838 dbgs() << **I; 839 if (std::next(I) != E) 840 dbgs() << ", "; 841 } dbgs() 842 << '\n'); 843 844 // DCE instructions only used to calculate that store. 845 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst, 846 &DeadStackObjects); 847 ++NumFastStores; 848 MadeChange = true; 849 continue; 850 } 851 } 852 853 // Remove any dead non-memory-mutating instructions. 854 if (isInstructionTriviallyDead(&*BBI, TLI)) { 855 LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: " 856 << *&*BBI << '\n'); 857 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst, 858 &DeadStackObjects); 859 ++NumFastOther; 860 MadeChange = true; 861 continue; 862 } 863 864 if (isa<AllocaInst>(BBI)) { 865 // Remove allocas from the list of dead stack objects; there can't be 866 // any references before the definition. 867 DeadStackObjects.remove(&*BBI); 868 continue; 869 } 870 871 if (auto *Call = dyn_cast<CallBase>(&*BBI)) { 872 // Remove allocation function calls from the list of dead stack objects; 873 // there can't be any references before the definition. 874 if (isAllocLikeFn(&*BBI, TLI)) 875 DeadStackObjects.remove(&*BBI); 876 877 // If this call does not access memory, it can't be loading any of our 878 // pointers. 879 if (AA->doesNotAccessMemory(Call)) 880 continue; 881 882 // If the call might load from any of our allocas, then any store above 883 // the call is live. 884 DeadStackObjects.remove_if([&](const Value *I) { 885 // See if the call site touches the value. 886 return isRefSet(AA->getModRefInfo( 887 Call, I, getPointerSize(I, DL, *TLI, BB.getParent()))); 888 }); 889 890 // If all of the allocas were clobbered by the call then we're not going 891 // to find anything else to process. 892 if (DeadStackObjects.empty()) 893 break; 894 895 continue; 896 } 897 898 // We can remove the dead stores, irrespective of the fence and its ordering 899 // (release/acquire/seq_cst). Fences only constraints the ordering of 900 // already visible stores, it does not make a store visible to other 901 // threads. So, skipping over a fence does not change a store from being 902 // dead. 903 if (isa<FenceInst>(*BBI)) 904 continue; 905 906 MemoryLocation LoadedLoc; 907 908 // If we encounter a use of the pointer, it is no longer considered dead 909 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 910 if (!L->isUnordered()) // Be conservative with atomic/volatile load 911 break; 912 LoadedLoc = MemoryLocation::get(L); 913 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 914 LoadedLoc = MemoryLocation::get(V); 915 } else if (!BBI->mayReadFromMemory()) { 916 // Instruction doesn't read memory. Note that stores that weren't removed 917 // above will hit this case. 918 continue; 919 } else { 920 // Unknown inst; assume it clobbers everything. 921 break; 922 } 923 924 // Remove any allocas from the DeadPointer set that are loaded, as this 925 // makes any stores above the access live. 926 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent()); 927 928 // If all of the allocas were clobbered by the access then we're not going 929 // to find anything else to process. 930 if (DeadStackObjects.empty()) 931 break; 932 } 933 934 return MadeChange; 935 } 936 937 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset, 938 int64_t &EarlierSize, int64_t LaterOffset, 939 int64_t LaterSize, bool IsOverwriteEnd) { 940 // TODO: base this on the target vector size so that if the earlier 941 // store was too small to get vector writes anyway then its likely 942 // a good idea to shorten it 943 // Power of 2 vector writes are probably always a bad idea to optimize 944 // as any store/memset/memcpy is likely using vector instructions so 945 // shortening it to not vector size is likely to be slower 946 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite); 947 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment(); 948 if (!IsOverwriteEnd) 949 LaterOffset = int64_t(LaterOffset + LaterSize); 950 951 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) && 952 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0)) 953 return false; 954 955 int64_t NewLength = IsOverwriteEnd 956 ? LaterOffset - EarlierOffset 957 : EarlierSize - (LaterOffset - EarlierOffset); 958 959 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) { 960 // When shortening an atomic memory intrinsic, the newly shortened 961 // length must remain an integer multiple of the element size. 962 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 963 if (0 != NewLength % ElementSize) 964 return false; 965 } 966 967 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 968 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " 969 << *EarlierWrite << "\n KILLER (offset " << LaterOffset 970 << ", " << EarlierSize << ")\n"); 971 972 Value *EarlierWriteLength = EarlierIntrinsic->getLength(); 973 Value *TrimmedLength = 974 ConstantInt::get(EarlierWriteLength->getType(), NewLength); 975 EarlierIntrinsic->setLength(TrimmedLength); 976 977 EarlierSize = NewLength; 978 if (!IsOverwriteEnd) { 979 int64_t OffsetMoved = (LaterOffset - EarlierOffset); 980 Value *Indices[1] = { 981 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)}; 982 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds( 983 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(), 984 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite); 985 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc()); 986 EarlierIntrinsic->setDest(NewDestGEP); 987 EarlierOffset = EarlierOffset + OffsetMoved; 988 } 989 return true; 990 } 991 992 static bool tryToShortenEnd(Instruction *EarlierWrite, 993 OverlapIntervalsTy &IntervalMap, 994 int64_t &EarlierStart, int64_t &EarlierSize) { 995 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite)) 996 return false; 997 998 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 999 int64_t LaterStart = OII->second; 1000 int64_t LaterSize = OII->first - LaterStart; 1001 1002 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize && 1003 LaterStart + LaterSize >= EarlierStart + EarlierSize) { 1004 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1005 LaterSize, true)) { 1006 IntervalMap.erase(OII); 1007 return true; 1008 } 1009 } 1010 return false; 1011 } 1012 1013 static bool tryToShortenBegin(Instruction *EarlierWrite, 1014 OverlapIntervalsTy &IntervalMap, 1015 int64_t &EarlierStart, int64_t &EarlierSize) { 1016 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite)) 1017 return false; 1018 1019 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 1020 int64_t LaterStart = OII->second; 1021 int64_t LaterSize = OII->first - LaterStart; 1022 1023 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) { 1024 assert(LaterStart + LaterSize < EarlierStart + EarlierSize && 1025 "Should have been handled as OW_Complete"); 1026 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1027 LaterSize, false)) { 1028 IntervalMap.erase(OII); 1029 return true; 1030 } 1031 } 1032 return false; 1033 } 1034 1035 static bool removePartiallyOverlappedStores(AliasAnalysis *AA, 1036 const DataLayout &DL, 1037 InstOverlapIntervalsTy &IOL) { 1038 bool Changed = false; 1039 for (auto OI : IOL) { 1040 Instruction *EarlierWrite = OI.first; 1041 MemoryLocation Loc = getLocForWrite(EarlierWrite); 1042 assert(isRemovable(EarlierWrite) && "Expect only removable instruction"); 1043 1044 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 1045 int64_t EarlierStart = 0; 1046 int64_t EarlierSize = int64_t(Loc.Size.getValue()); 1047 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL); 1048 OverlapIntervalsTy &IntervalMap = OI.second; 1049 Changed |= 1050 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1051 if (IntervalMap.empty()) 1052 continue; 1053 Changed |= 1054 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1055 } 1056 return Changed; 1057 } 1058 1059 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI, 1060 AliasAnalysis *AA, MemoryDependenceResults *MD, 1061 const DataLayout &DL, 1062 const TargetLibraryInfo *TLI, 1063 InstOverlapIntervalsTy &IOL, 1064 OrderedBasicBlock &OBB, 1065 MapVector<Instruction *, bool> &ThrowableInst) { 1066 // Must be a store instruction. 1067 StoreInst *SI = dyn_cast<StoreInst>(Inst); 1068 if (!SI) 1069 return false; 1070 1071 // If we're storing the same value back to a pointer that we just loaded from, 1072 // then the store can be removed. 1073 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) { 1074 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 1075 isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) { 1076 1077 LLVM_DEBUG( 1078 dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: " 1079 << *DepLoad << "\n STORE: " << *SI << '\n'); 1080 1081 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst); 1082 ++NumRedundantStores; 1083 return true; 1084 } 1085 } 1086 1087 // Remove null stores into the calloc'ed objects 1088 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand()); 1089 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) { 1090 Instruction *UnderlyingPointer = 1091 dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL)); 1092 1093 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) && 1094 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) { 1095 LLVM_DEBUG( 1096 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: " 1097 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n'); 1098 1099 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, OBB, ThrowableInst); 1100 ++NumRedundantStores; 1101 return true; 1102 } 1103 } 1104 return false; 1105 } 1106 1107 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA, 1108 MemoryDependenceResults *MD, DominatorTree *DT, 1109 const TargetLibraryInfo *TLI) { 1110 const DataLayout &DL = BB.getModule()->getDataLayout(); 1111 bool MadeChange = false; 1112 1113 OrderedBasicBlock OBB(&BB); 1114 MapVector<Instruction *, bool> ThrowableInst; 1115 1116 // A map of interval maps representing partially-overwritten value parts. 1117 InstOverlapIntervalsTy IOL; 1118 1119 // Do a top-down walk on the BB. 1120 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 1121 // Handle 'free' calls specially. 1122 if (CallInst *F = isFreeCall(&*BBI, TLI)) { 1123 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, OBB, ThrowableInst); 1124 // Increment BBI after handleFree has potentially deleted instructions. 1125 // This ensures we maintain a valid iterator. 1126 ++BBI; 1127 continue; 1128 } 1129 1130 Instruction *Inst = &*BBI++; 1131 1132 if (Inst->mayThrow()) { 1133 ThrowableInst[Inst] = true; 1134 continue; 1135 } 1136 1137 // Check to see if Inst writes to memory. If not, continue. 1138 if (!hasAnalyzableMemoryWrite(Inst, *TLI)) 1139 continue; 1140 1141 // eliminateNoopStore will update in iterator, if necessary. 1142 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, OBB, 1143 ThrowableInst)) { 1144 MadeChange = true; 1145 continue; 1146 } 1147 1148 // If we find something that writes memory, get its memory dependence. 1149 MemDepResult InstDep = MD->getDependency(Inst, &OBB); 1150 1151 // Ignore any store where we can't find a local dependence. 1152 // FIXME: cross-block DSE would be fun. :) 1153 if (!InstDep.isDef() && !InstDep.isClobber()) 1154 continue; 1155 1156 // Figure out what location is being stored to. 1157 MemoryLocation Loc = getLocForWrite(Inst); 1158 1159 // If we didn't get a useful location, fail. 1160 if (!Loc.Ptr) 1161 continue; 1162 1163 // Loop until we find a store we can eliminate or a load that 1164 // invalidates the analysis. Without an upper bound on the number of 1165 // instructions examined, this analysis can become very time-consuming. 1166 // However, the potential gain diminishes as we process more instructions 1167 // without eliminating any of them. Therefore, we limit the number of 1168 // instructions we look at. 1169 auto Limit = MD->getDefaultBlockScanLimit(); 1170 while (InstDep.isDef() || InstDep.isClobber()) { 1171 // Get the memory clobbered by the instruction we depend on. MemDep will 1172 // skip any instructions that 'Loc' clearly doesn't interact with. If we 1173 // end up depending on a may- or must-aliased load, then we can't optimize 1174 // away the store and we bail out. However, if we depend on something 1175 // that overwrites the memory location we *can* potentially optimize it. 1176 // 1177 // Find out what memory location the dependent instruction stores. 1178 Instruction *DepWrite = InstDep.getInst(); 1179 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI)) 1180 break; 1181 MemoryLocation DepLoc = getLocForWrite(DepWrite); 1182 // If we didn't get a useful location, or if it isn't a size, bail out. 1183 if (!DepLoc.Ptr) 1184 break; 1185 1186 // Find the last throwable instruction not removed by call to 1187 // deleteDeadInstruction. 1188 Instruction *LastThrowing = nullptr; 1189 if (!ThrowableInst.empty()) 1190 LastThrowing = ThrowableInst.back().first; 1191 1192 // Make sure we don't look past a call which might throw. This is an 1193 // issue because MemoryDependenceAnalysis works in the wrong direction: 1194 // it finds instructions which dominate the current instruction, rather than 1195 // instructions which are post-dominated by the current instruction. 1196 // 1197 // If the underlying object is a non-escaping memory allocation, any store 1198 // to it is dead along the unwind edge. Otherwise, we need to preserve 1199 // the store. 1200 if (LastThrowing && OBB.dominates(DepWrite, LastThrowing)) { 1201 const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL); 1202 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying); 1203 if (!IsStoreDeadOnUnwind) { 1204 // We're looking for a call to an allocation function 1205 // where the allocation doesn't escape before the last 1206 // throwing instruction; PointerMayBeCaptured 1207 // reasonably fast approximation. 1208 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) && 1209 !PointerMayBeCaptured(Underlying, false, true); 1210 } 1211 if (!IsStoreDeadOnUnwind) 1212 break; 1213 } 1214 1215 // If we find a write that is a) removable (i.e., non-volatile), b) is 1216 // completely obliterated by the store to 'Loc', and c) which we know that 1217 // 'Inst' doesn't load from, then we can remove it. 1218 // Also try to merge two stores if a later one only touches memory written 1219 // to by the earlier one. 1220 if (isRemovable(DepWrite) && 1221 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) { 1222 int64_t InstWriteOffset, DepWriteOffset; 1223 OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, 1224 InstWriteOffset, DepWrite, IOL, *AA, 1225 BB.getParent()); 1226 if (OR == OW_Complete) { 1227 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DepWrite 1228 << "\n KILLER: " << *Inst << '\n'); 1229 1230 // Delete the store and now-dead instructions that feed it. 1231 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, OBB, 1232 ThrowableInst); 1233 ++NumFastStores; 1234 MadeChange = true; 1235 1236 // We erased DepWrite; start over. 1237 InstDep = MD->getDependency(Inst, &OBB); 1238 continue; 1239 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) || 1240 ((OR == OW_Begin && 1241 isShortenableAtTheBeginning(DepWrite)))) { 1242 assert(!EnablePartialOverwriteTracking && "Do not expect to perform " 1243 "when partial-overwrite " 1244 "tracking is enabled"); 1245 // The overwrite result is known, so these must be known, too. 1246 int64_t EarlierSize = DepLoc.Size.getValue(); 1247 int64_t LaterSize = Loc.Size.getValue(); 1248 bool IsOverwriteEnd = (OR == OW_End); 1249 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize, 1250 InstWriteOffset, LaterSize, IsOverwriteEnd); 1251 } else if (EnablePartialStoreMerging && 1252 OR == OW_PartialEarlierWithFullLater) { 1253 auto *Earlier = dyn_cast<StoreInst>(DepWrite); 1254 auto *Later = dyn_cast<StoreInst>(Inst); 1255 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) && 1256 DL.typeSizeEqualsStoreSize( 1257 Earlier->getValueOperand()->getType()) && 1258 Later && isa<ConstantInt>(Later->getValueOperand()) && 1259 DL.typeSizeEqualsStoreSize( 1260 Later->getValueOperand()->getType()) && 1261 memoryIsNotModifiedBetween(Earlier, Later, AA)) { 1262 // If the store we find is: 1263 // a) partially overwritten by the store to 'Loc' 1264 // b) the later store is fully contained in the earlier one and 1265 // c) they both have a constant value 1266 // d) none of the two stores need padding 1267 // Merge the two stores, replacing the earlier store's value with a 1268 // merge of both values. 1269 // TODO: Deal with other constant types (vectors, etc), and probably 1270 // some mem intrinsics (if needed) 1271 1272 APInt EarlierValue = 1273 cast<ConstantInt>(Earlier->getValueOperand())->getValue(); 1274 APInt LaterValue = 1275 cast<ConstantInt>(Later->getValueOperand())->getValue(); 1276 unsigned LaterBits = LaterValue.getBitWidth(); 1277 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth()); 1278 LaterValue = LaterValue.zext(EarlierValue.getBitWidth()); 1279 1280 // Offset of the smaller store inside the larger store 1281 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8; 1282 unsigned LShiftAmount = 1283 DL.isBigEndian() 1284 ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits 1285 : BitOffsetDiff; 1286 APInt Mask = 1287 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount, 1288 LShiftAmount + LaterBits); 1289 // Clear the bits we'll be replacing, then OR with the smaller 1290 // store, shifted appropriately. 1291 APInt Merged = 1292 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount); 1293 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *DepWrite 1294 << "\n Later: " << *Inst 1295 << "\n Merged Value: " << Merged << '\n'); 1296 1297 auto *SI = new StoreInst( 1298 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged), 1299 Earlier->getPointerOperand(), false, 1300 MaybeAlign(Earlier->getAlignment()), Earlier->getOrdering(), 1301 Earlier->getSyncScopeID(), DepWrite); 1302 1303 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa, 1304 LLVMContext::MD_alias_scope, 1305 LLVMContext::MD_noalias, 1306 LLVMContext::MD_nontemporal}; 1307 SI->copyMetadata(*DepWrite, MDToKeep); 1308 ++NumModifiedStores; 1309 1310 // Remove earlier, wider, store 1311 OBB.replaceInstruction(DepWrite, SI); 1312 1313 // Delete the old stores and now-dead instructions that feed them. 1314 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, OBB, 1315 ThrowableInst); 1316 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, OBB, 1317 ThrowableInst); 1318 MadeChange = true; 1319 1320 // We erased DepWrite and Inst (Loc); start over. 1321 break; 1322 } 1323 } 1324 } 1325 1326 // If this is a may-aliased store that is clobbering the store value, we 1327 // can keep searching past it for another must-aliased pointer that stores 1328 // to the same location. For example, in: 1329 // store -> P 1330 // store -> Q 1331 // store -> P 1332 // we can remove the first store to P even though we don't know if P and Q 1333 // alias. 1334 if (DepWrite == &BB.front()) break; 1335 1336 // Can't look past this instruction if it might read 'Loc'. 1337 if (isRefSet(AA->getModRefInfo(DepWrite, Loc))) 1338 break; 1339 1340 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false, 1341 DepWrite->getIterator(), &BB, 1342 /*QueryInst=*/ nullptr, &Limit); 1343 } 1344 } 1345 1346 if (EnablePartialOverwriteTracking) 1347 MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL); 1348 1349 // If this block ends in a return, unwind, or unreachable, all allocas are 1350 // dead at its end, which means stores to them are also dead. 1351 if (BB.getTerminator()->getNumSuccessors() == 0) 1352 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, OBB, ThrowableInst); 1353 1354 return MadeChange; 1355 } 1356 1357 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA, 1358 MemoryDependenceResults *MD, DominatorTree *DT, 1359 const TargetLibraryInfo *TLI) { 1360 bool MadeChange = false; 1361 for (BasicBlock &BB : F) 1362 // Only check non-dead blocks. Dead blocks may have strange pointer 1363 // cycles that will confuse alias analysis. 1364 if (DT->isReachableFromEntry(&BB)) 1365 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI); 1366 1367 return MadeChange; 1368 } 1369 1370 namespace { 1371 //============================================================================= 1372 // MemorySSA backed dead store elimination. 1373 // 1374 // The code below implements dead store elimination using MemorySSA. It uses 1375 // the following general approach: given a MemoryDef, walk upwards to find 1376 // clobbering MemoryDefs that may be killed by the starting def. Then check 1377 // that there are no uses that may read the location of the original MemoryDef 1378 // in between both MemoryDefs. A bit more concretely: 1379 // 1380 // For all MemoryDefs StartDef: 1381 // 1. Get the next dominating clobbering MemoryDef (DomAccess) by walking 1382 // upwards. 1383 // 2. Check that there are no reads between DomAccess and the StartDef by 1384 // checking all uses starting at DomAccess and walking until we see StartDef. 1385 // 3. For each found DomDef, check that: 1386 // 1. There are no barrier instructions between DomDef and StartDef (like 1387 // throws or stores with ordering constraints). 1388 // 2. StartDef is executed whenever DomDef is executed. 1389 // 3. StartDef completely overwrites DomDef. 1390 // 4. Erase DomDef from the function and MemorySSA. 1391 1392 // Returns true if \p M is an intrisnic that does not read or write memory. 1393 bool isNoopIntrinsic(MemoryUseOrDef *M) { 1394 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(M->getMemoryInst())) { 1395 switch (II->getIntrinsicID()) { 1396 case Intrinsic::lifetime_start: 1397 case Intrinsic::lifetime_end: 1398 case Intrinsic::invariant_end: 1399 case Intrinsic::launder_invariant_group: 1400 case Intrinsic::assume: 1401 return true; 1402 case Intrinsic::dbg_addr: 1403 case Intrinsic::dbg_declare: 1404 case Intrinsic::dbg_label: 1405 case Intrinsic::dbg_value: 1406 llvm_unreachable("Intrinsic should not be modeled in MemorySSA"); 1407 default: 1408 return false; 1409 } 1410 } 1411 return false; 1412 } 1413 1414 // Check if we can ignore \p D for DSE. 1415 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) { 1416 Instruction *DI = D->getMemoryInst(); 1417 // Calls that only access inaccessible memory cannot read or write any memory 1418 // locations we consider for elimination. 1419 if (auto CS = CallSite(DI)) 1420 if (CS.onlyAccessesInaccessibleMemory()) 1421 return true; 1422 1423 // We can eliminate stores to locations not visible to the caller across 1424 // throwing instructions. 1425 if (DI->mayThrow() && !DefVisibleToCaller) 1426 return true; 1427 1428 // We can remove the dead stores, irrespective of the fence and its ordering 1429 // (release/acquire/seq_cst). Fences only constraints the ordering of 1430 // already visible stores, it does not make a store visible to other 1431 // threads. So, skipping over a fence does not change a store from being 1432 // dead. 1433 if (isa<FenceInst>(DI)) 1434 return true; 1435 1436 // Skip intrinsics that do not really read or modify memory. 1437 if (isNoopIntrinsic(D)) 1438 return true; 1439 1440 return false; 1441 } 1442 1443 struct DSEState { 1444 Function &F; 1445 AliasAnalysis &AA; 1446 MemorySSA &MSSA; 1447 DominatorTree &DT; 1448 PostDominatorTree &PDT; 1449 const TargetLibraryInfo &TLI; 1450 1451 // All MemoryDefs that potentially could kill other MemDefs. 1452 SmallVector<MemoryDef *, 64> MemDefs; 1453 // Any that should be skipped as they are already deleted 1454 SmallPtrSet<MemoryAccess *, 4> SkipStores; 1455 // Keep track of all of the objects that are invisible to the caller until the 1456 // function returns. 1457 SmallPtrSet<const Value *, 16> InvisibleToCaller; 1458 // Keep track of blocks with throwing instructions not modeled in MemorySSA. 1459 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks; 1460 1461 DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, 1462 PostDominatorTree &PDT, const TargetLibraryInfo &TLI) 1463 : F(F), AA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI) {} 1464 1465 static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 1466 DominatorTree &DT, PostDominatorTree &PDT, 1467 const TargetLibraryInfo &TLI) { 1468 DSEState State(F, AA, MSSA, DT, PDT, TLI); 1469 // Collect blocks with throwing instructions not modeled in MemorySSA and 1470 // alloc-like objects. 1471 for (Instruction &I : instructions(F)) { 1472 if (I.mayThrow() && !MSSA.getMemoryAccess(&I)) 1473 State.ThrowingBlocks.insert(I.getParent()); 1474 1475 auto *MD = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess(&I)); 1476 if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit && 1477 hasAnalyzableMemoryWrite(&I, TLI) && isRemovable(&I)) 1478 State.MemDefs.push_back(MD); 1479 1480 // Track alloca and alloca-like objects. Here we care about objects not 1481 // visible to the caller during function execution. Alloca objects are 1482 // invalid in the caller, for alloca-like objects we ensure that they are 1483 // not captured throughout the function. 1484 if (isa<AllocaInst>(&I) || 1485 (isAllocLikeFn(&I, &TLI) && !PointerMayBeCaptured(&I, false, true))) 1486 State.InvisibleToCaller.insert(&I); 1487 } 1488 // Treat byval or inalloca arguments the same as Allocas, stores to them are 1489 // dead at the end of the function. 1490 for (Argument &AI : F.args()) 1491 if (AI.hasByValOrInAllocaAttr()) 1492 State.InvisibleToCaller.insert(&AI); 1493 return State; 1494 } 1495 1496 Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const { 1497 if (!I->mayWriteToMemory()) 1498 return None; 1499 1500 if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I)) 1501 return {MemoryLocation::getForDest(MTI)}; 1502 1503 if (auto CS = CallSite(I)) { 1504 if (Function *F = CS.getCalledFunction()) { 1505 StringRef FnName = F->getName(); 1506 if (TLI.has(LibFunc_strcpy) && FnName == TLI.getName(LibFunc_strcpy)) 1507 return {MemoryLocation(CS.getArgument(0))}; 1508 if (TLI.has(LibFunc_strncpy) && FnName == TLI.getName(LibFunc_strncpy)) 1509 return {MemoryLocation(CS.getArgument(0))}; 1510 if (TLI.has(LibFunc_strcat) && FnName == TLI.getName(LibFunc_strcat)) 1511 return {MemoryLocation(CS.getArgument(0))}; 1512 if (TLI.has(LibFunc_strncat) && FnName == TLI.getName(LibFunc_strncat)) 1513 return {MemoryLocation(CS.getArgument(0))}; 1514 } 1515 return None; 1516 } 1517 1518 return MemoryLocation::getOrNone(I); 1519 } 1520 1521 /// Returns true if \p Use completely overwrites \p DefLoc. 1522 bool isCompleteOverwrite(MemoryLocation DefLoc, Instruction *UseInst) const { 1523 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a 1524 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a 1525 // MemoryDef. 1526 if (!UseInst->mayWriteToMemory()) 1527 return false; 1528 1529 if (auto CS = CallSite(UseInst)) 1530 if (CS.onlyAccessesInaccessibleMemory()) 1531 return false; 1532 1533 ModRefInfo MR = AA.getModRefInfo(UseInst, DefLoc); 1534 // If necessary, perform additional analysis. 1535 if (isModSet(MR)) 1536 MR = AA.callCapturesBefore(UseInst, DefLoc, &DT); 1537 1538 Optional<MemoryLocation> UseLoc = getLocForWriteEx(UseInst); 1539 return isModSet(MR) && isMustSet(MR) && 1540 UseLoc->Size.getValue() >= DefLoc.Size.getValue(); 1541 } 1542 1543 /// Returns true if \p Use may read from \p DefLoc. 1544 bool isReadClobber(MemoryLocation DefLoc, Instruction *UseInst) const { 1545 if (!UseInst->mayReadFromMemory()) 1546 return false; 1547 1548 if (auto CS = CallSite(UseInst)) 1549 if (CS.onlyAccessesInaccessibleMemory()) 1550 return false; 1551 1552 ModRefInfo MR = AA.getModRefInfo(UseInst, DefLoc); 1553 // If necessary, perform additional analysis. 1554 if (isRefSet(MR)) 1555 MR = AA.callCapturesBefore(UseInst, DefLoc, &DT); 1556 return isRefSet(MR); 1557 } 1558 1559 // Find a MemoryDef writing to \p DefLoc and dominating \p Current, with no 1560 // read access in between or return None otherwise. The returned value may not 1561 // (completely) overwrite \p DefLoc. Currently we bail out when we encounter 1562 // any of the following 1563 // * An aliasing MemoryUse (read). 1564 // * A MemoryPHI. 1565 Optional<MemoryAccess *> getDomMemoryDef(MemoryDef *KillingDef, 1566 MemoryAccess *Current, 1567 MemoryLocation DefLoc, 1568 bool DefVisibleToCaller, 1569 int &ScanLimit) const { 1570 MemoryDef *DomDef; 1571 MemoryAccess *StartDef = Current; 1572 bool StepAgain; 1573 LLVM_DEBUG(dbgs() << " trying to get dominating access for " << *Current 1574 << "\n"); 1575 // Find the next clobbering Mod access for DefLoc, starting at Current. 1576 do { 1577 StepAgain = false; 1578 // Reached TOP. 1579 if (MSSA.isLiveOnEntryDef(Current)) 1580 return None; 1581 1582 MemoryUseOrDef *CurrentUD = dyn_cast<MemoryUseOrDef>(Current); 1583 if (!CurrentUD) 1584 return None; 1585 1586 // Look for access that clobber DefLoc. 1587 MemoryAccess *DomAccess = 1588 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess( 1589 CurrentUD->getDefiningAccess(), DefLoc); 1590 DomDef = dyn_cast<MemoryDef>(DomAccess); 1591 if (!DomDef || MSSA.isLiveOnEntryDef(DomDef)) 1592 return None; 1593 1594 // Check if we can skip DomDef for DSE. We also require the KillingDef 1595 // execute whenever DomDef executes and use post-dominance to ensure that. 1596 if (canSkipDef(DomDef, DefVisibleToCaller) || 1597 !PDT.dominates(KillingDef->getBlock(), DomDef->getBlock())) { 1598 StepAgain = true; 1599 Current = DomDef; 1600 } 1601 1602 } while (StepAgain); 1603 1604 LLVM_DEBUG(dbgs() << " Checking for reads of " << *DomDef << " (" 1605 << *DomDef->getMemoryInst() << ")\n"); 1606 1607 SmallSetVector<MemoryAccess *, 32> WorkList; 1608 auto PushMemUses = [&WorkList](MemoryAccess *Acc) { 1609 for (Use &U : Acc->uses()) 1610 WorkList.insert(cast<MemoryAccess>(U.getUser())); 1611 }; 1612 PushMemUses(DomDef); 1613 1614 // Check if DomDef may be read. 1615 for (unsigned I = 0; I < WorkList.size(); I++) { 1616 MemoryAccess *UseAccess = WorkList[I]; 1617 1618 LLVM_DEBUG(dbgs() << " Checking use " << *UseAccess); 1619 if (--ScanLimit == 0) { 1620 LLVM_DEBUG(dbgs() << " ... hit scan limit\n"); 1621 return None; 1622 } 1623 1624 // Bail out on MemoryPhis for now. 1625 if (isa<MemoryPhi>(UseAccess)) { 1626 LLVM_DEBUG(dbgs() << " ... hit MemoryPhi\n"); 1627 return None; 1628 } 1629 1630 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1631 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n"); 1632 1633 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess))) { 1634 PushMemUses(UseAccess); 1635 continue; 1636 } 1637 1638 // Uses which may read the original MemoryDef mean we cannot eliminate the 1639 // original MD. Stop walk. 1640 if (isReadClobber(DefLoc, UseInst)) { 1641 LLVM_DEBUG(dbgs() << " ... found read clobber\n"); 1642 return None; 1643 } 1644 1645 if (StartDef == UseAccess) 1646 continue; 1647 1648 // Check all uses for MemoryDefs, except for defs completely overwriting 1649 // the original location. Otherwise we have to check uses of *all* 1650 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might 1651 // miss cases like the following 1652 // 1 = Def(LoE) ; <----- DomDef stores [0,1] 1653 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3] 1654 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3]. 1655 // (The Use points to the *first* Def it may alias) 1656 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias, 1657 // stores [0,1] 1658 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) { 1659 if (!isCompleteOverwrite(DefLoc, UseInst)) 1660 PushMemUses(UseDef); 1661 } 1662 } 1663 1664 // No aliasing MemoryUses of DomDef found, DomDef is potentially dead. 1665 return {DomDef}; 1666 } 1667 1668 // Delete dead memory defs 1669 void deleteDeadInstruction(Instruction *SI) { 1670 MemorySSAUpdater Updater(&MSSA); 1671 SmallVector<Instruction *, 32> NowDeadInsts; 1672 NowDeadInsts.push_back(SI); 1673 --NumFastOther; 1674 1675 while (!NowDeadInsts.empty()) { 1676 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 1677 ++NumFastOther; 1678 1679 // Try to preserve debug information attached to the dead instruction. 1680 salvageDebugInfo(*DeadInst); 1681 1682 // Remove the Instruction from MSSA. 1683 if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) { 1684 if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) { 1685 SkipStores.insert(MD); 1686 } 1687 Updater.removeMemoryAccess(MA); 1688 } 1689 1690 // Remove its operands 1691 for (Use &O : DeadInst->operands()) 1692 if (Instruction *OpI = dyn_cast<Instruction>(O)) { 1693 O = nullptr; 1694 if (isInstructionTriviallyDead(OpI, &TLI)) 1695 NowDeadInsts.push_back(OpI); 1696 } 1697 1698 DeadInst->eraseFromParent(); 1699 } 1700 } 1701 1702 // Check for any extra throws between SI and NI that block DSE. This only 1703 // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may 1704 // throw are handled during the walk from one def to the next. 1705 bool mayThrowBetween(Instruction *SI, Instruction *NI, 1706 const Value *SILocUnd) const { 1707 // First see if we can ignore it by using the fact that SI is an 1708 // alloca/alloca like object that is not visible to the caller during 1709 // execution of the function. 1710 if (SILocUnd && InvisibleToCaller.count(SILocUnd)) 1711 return false; 1712 1713 if (SI->getParent() == NI->getParent()) 1714 return ThrowingBlocks.find(SI->getParent()) != ThrowingBlocks.end(); 1715 return !ThrowingBlocks.empty(); 1716 } 1717 1718 // Check if \p NI acts as a DSE barrier for \p SI. The following instructions 1719 // act as barriers: 1720 // * A memory instruction that may throw and \p SI accesses a non-stack 1721 // object. 1722 // * Atomic stores stronger that monotonic. 1723 bool isDSEBarrier(Instruction *SI, MemoryLocation &SILoc, 1724 const Value *SILocUnd, Instruction *NI, 1725 MemoryLocation &NILoc) const { 1726 // If NI may throw it acts as a barrier, unless we are to an alloca/alloca 1727 // like object that does not escape. 1728 if (NI->mayThrow() && !InvisibleToCaller.count(SILocUnd)) 1729 return true; 1730 1731 if (NI->isAtomic()) { 1732 if (auto *NSI = dyn_cast<StoreInst>(NI)) { 1733 if (isStrongerThanMonotonic(NSI->getOrdering())) 1734 return true; 1735 } else 1736 llvm_unreachable( 1737 "Other instructions should be modeled/skipped in MemorySSA"); 1738 } 1739 1740 return false; 1741 } 1742 }; 1743 1744 bool eliminateDeadStoresMemorySSA(Function &F, AliasAnalysis &AA, 1745 MemorySSA &MSSA, DominatorTree &DT, 1746 PostDominatorTree &PDT, 1747 const TargetLibraryInfo &TLI) { 1748 const DataLayout &DL = F.getParent()->getDataLayout(); 1749 bool MadeChange = false; 1750 1751 DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI); 1752 // For each store: 1753 for (unsigned I = 0; I < State.MemDefs.size(); I++) { 1754 MemoryDef *Current = State.MemDefs[I]; 1755 if (State.SkipStores.count(Current)) 1756 continue; 1757 Instruction *SI = cast<MemoryDef>(Current)->getMemoryInst(); 1758 auto MaybeSILoc = State.getLocForWriteEx(SI); 1759 if (!MaybeSILoc) { 1760 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for " 1761 << *SI << "\n"); 1762 continue; 1763 } 1764 MemoryLocation SILoc = *MaybeSILoc; 1765 assert(SILoc.Ptr && "SILoc should not be null"); 1766 const Value *SILocUnd = GetUnderlyingObject(SILoc.Ptr, DL); 1767 Instruction *DefObj = 1768 const_cast<Instruction *>(dyn_cast<Instruction>(SILocUnd)); 1769 bool DefVisibleToCaller = !State.InvisibleToCaller.count(SILocUnd); 1770 if (DefObj && ((isAllocLikeFn(DefObj, &TLI) && 1771 !PointerMayBeCapturedBefore(DefObj, false, true, SI, &DT)))) 1772 DefVisibleToCaller = false; 1773 1774 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by " << *SI 1775 << "\n"); 1776 1777 int ScanLimit = MemorySSAScanLimit; 1778 MemoryDef *StartDef = Current; 1779 // Walk MemorySSA upward to find MemoryDefs that might be killed by SI. 1780 while (Optional<MemoryAccess *> Next = State.getDomMemoryDef( 1781 StartDef, Current, SILoc, DefVisibleToCaller, ScanLimit)) { 1782 MemoryAccess *DomAccess = *Next; 1783 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DomAccess << "\n"); 1784 MemoryDef *NextDef = dyn_cast<MemoryDef>(DomAccess); 1785 Instruction *NI = NextDef->getMemoryInst(); 1786 LLVM_DEBUG(dbgs() << " def " << *NI << "\n"); 1787 1788 if (!hasAnalyzableMemoryWrite(NI, TLI)) 1789 break; 1790 MemoryLocation NILoc = *State.getLocForWriteEx(NI); 1791 // Check for anything that looks like it will be a barrier to further 1792 // removal 1793 if (State.isDSEBarrier(SI, SILoc, SILocUnd, NI, NILoc)) { 1794 LLVM_DEBUG(dbgs() << " stop, barrier\n"); 1795 break; 1796 } 1797 1798 // Before we try to remove anything, check for any extra throwing 1799 // instructions that block us from DSEing 1800 if (State.mayThrowBetween(SI, NI, SILocUnd)) { 1801 LLVM_DEBUG(dbgs() << " stop, may throw!\n"); 1802 break; 1803 } 1804 1805 // Check if NI overwrites SI. 1806 int64_t InstWriteOffset, DepWriteOffset; 1807 InstOverlapIntervalsTy IOL; 1808 OverwriteResult OR = isOverwrite(SILoc, NILoc, DL, TLI, DepWriteOffset, 1809 InstWriteOffset, NI, IOL, AA, &F); 1810 1811 if (OR == OW_Complete) { 1812 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 1813 << "\n KILLER: " << *SI << '\n'); 1814 State.deleteDeadInstruction(NI); 1815 ++NumFastStores; 1816 MadeChange = true; 1817 } else 1818 Current = NextDef; 1819 } 1820 } 1821 1822 return MadeChange; 1823 } 1824 } // end anonymous namespace 1825 1826 //===----------------------------------------------------------------------===// 1827 // DSE Pass 1828 //===----------------------------------------------------------------------===// 1829 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 1830 AliasAnalysis &AA = AM.getResult<AAManager>(F); 1831 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1832 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 1833 1834 if (EnableMemorySSA) { 1835 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 1836 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 1837 1838 if (!eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI)) 1839 return PreservedAnalyses::all(); 1840 } else { 1841 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 1842 1843 if (!eliminateDeadStores(F, &AA, &MD, &DT, &TLI)) 1844 return PreservedAnalyses::all(); 1845 } 1846 1847 PreservedAnalyses PA; 1848 PA.preserveSet<CFGAnalyses>(); 1849 PA.preserve<GlobalsAA>(); 1850 if (EnableMemorySSA) 1851 PA.preserve<MemorySSAAnalysis>(); 1852 else 1853 PA.preserve<MemoryDependenceAnalysis>(); 1854 return PA; 1855 } 1856 1857 namespace { 1858 1859 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 1860 class DSELegacyPass : public FunctionPass { 1861 public: 1862 static char ID; // Pass identification, replacement for typeid 1863 1864 DSELegacyPass() : FunctionPass(ID) { 1865 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 1866 } 1867 1868 bool runOnFunction(Function &F) override { 1869 if (skipFunction(F)) 1870 return false; 1871 1872 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 1873 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1874 const TargetLibraryInfo &TLI = 1875 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1876 1877 if (EnableMemorySSA) { 1878 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 1879 PostDominatorTree &PDT = 1880 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 1881 1882 return eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI); 1883 } else { 1884 MemoryDependenceResults &MD = 1885 getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 1886 1887 return eliminateDeadStores(F, &AA, &MD, &DT, &TLI); 1888 } 1889 } 1890 1891 void getAnalysisUsage(AnalysisUsage &AU) const override { 1892 AU.setPreservesCFG(); 1893 AU.addRequired<AAResultsWrapperPass>(); 1894 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1895 AU.addPreserved<GlobalsAAWrapperPass>(); 1896 AU.addRequired<DominatorTreeWrapperPass>(); 1897 AU.addPreserved<DominatorTreeWrapperPass>(); 1898 1899 if (EnableMemorySSA) { 1900 AU.addRequired<PostDominatorTreeWrapperPass>(); 1901 AU.addRequired<MemorySSAWrapperPass>(); 1902 AU.addPreserved<PostDominatorTreeWrapperPass>(); 1903 AU.addPreserved<MemorySSAWrapperPass>(); 1904 } else { 1905 AU.addRequired<MemoryDependenceWrapperPass>(); 1906 AU.addPreserved<MemoryDependenceWrapperPass>(); 1907 } 1908 } 1909 }; 1910 1911 } // end anonymous namespace 1912 1913 char DSELegacyPass::ID = 0; 1914 1915 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 1916 false) 1917 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1918 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 1919 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1920 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 1921 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1922 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 1923 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1924 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 1925 false) 1926 1927 FunctionPass *llvm::createDeadStoreEliminationPass() { 1928 return new DSELegacyPass(); 1929 } 1930