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/PostOrderIterator.h" 22 #include "llvm/ADT/SetVector.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Analysis/AliasAnalysis.h" 28 #include "llvm/Analysis/CaptureTracking.h" 29 #include "llvm/Analysis/GlobalsModRef.h" 30 #include "llvm/Analysis/MemoryBuiltins.h" 31 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/MemorySSA.h" 34 #include "llvm/Analysis/MemorySSAUpdater.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/Constant.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DataLayout.h" 43 #include "llvm/IR/Dominators.h" 44 #include "llvm/IR/Function.h" 45 #include "llvm/IR/InstIterator.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/Intrinsics.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/PassManager.h" 54 #include "llvm/IR/PatternMatch.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/DebugCounter.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Transforms/Scalar.h" 66 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 67 #include "llvm/Transforms/Utils/Local.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <cstddef> 71 #include <cstdint> 72 #include <iterator> 73 #include <map> 74 #include <utility> 75 76 using namespace llvm; 77 using namespace PatternMatch; 78 79 #define DEBUG_TYPE "dse" 80 81 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE"); 82 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 83 STATISTIC(NumFastStores, "Number of stores deleted"); 84 STATISTIC(NumFastOther, "Number of other instrs removed"); 85 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 86 STATISTIC(NumModifiedStores, "Number of stores modified"); 87 STATISTIC(NumCFGChecks, "Number of stores modified"); 88 STATISTIC(NumCFGTries, "Number of stores modified"); 89 STATISTIC(NumCFGSuccess, "Number of stores modified"); 90 91 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa", 92 "Controls which MemoryDefs are eliminated."); 93 94 static cl::opt<bool> 95 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 96 cl::init(true), cl::Hidden, 97 cl::desc("Enable partial-overwrite tracking in DSE")); 98 99 static cl::opt<bool> 100 EnablePartialStoreMerging("enable-dse-partial-store-merging", 101 cl::init(true), cl::Hidden, 102 cl::desc("Enable partial store merging in DSE")); 103 104 static cl::opt<bool> 105 EnableMemorySSA("enable-dse-memoryssa", cl::init(false), cl::Hidden, 106 cl::desc("Use the new MemorySSA-backed DSE.")); 107 108 static cl::opt<unsigned> 109 MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden, 110 cl::desc("The number of memory instructions to scan for " 111 "dead store elimination (default = 100)")); 112 113 static cl::opt<unsigned> MemorySSADefsPerBlockLimit( 114 "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden, 115 cl::desc("The number of MemoryDefs we consider as candidates to eliminated " 116 "other stores per basic block (default = 5000)")); 117 118 static cl::opt<unsigned> MemorySSAPathCheckLimit( 119 "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden, 120 cl::desc("The maximum number of blocks to check when trying to prove that " 121 "all paths to an exit go through a killing block (default = 50)")); 122 123 //===----------------------------------------------------------------------===// 124 // Helper functions 125 //===----------------------------------------------------------------------===// 126 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 127 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 128 129 /// Delete this instruction. Before we do, go through and zero out all the 130 /// operands of this instruction. If any of them become dead, delete them and 131 /// the computation tree that feeds them. 132 /// If ValueSet is non-null, remove any deleted instructions from it as well. 133 static void 134 deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI, 135 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI, 136 InstOverlapIntervalsTy &IOL, 137 MapVector<Instruction *, bool> &ThrowableInst, 138 SmallSetVector<const Value *, 16> *ValueSet = nullptr) { 139 SmallVector<Instruction*, 32> NowDeadInsts; 140 141 NowDeadInsts.push_back(I); 142 --NumFastOther; 143 144 // Keeping the iterator straight is a pain, so we let this routine tell the 145 // caller what the next instruction is after we're done mucking about. 146 BasicBlock::iterator NewIter = *BBI; 147 148 // Before we touch this instruction, remove it from memdep! 149 do { 150 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 151 // Mark the DeadInst as dead in the list of throwable instructions. 152 auto It = ThrowableInst.find(DeadInst); 153 if (It != ThrowableInst.end()) 154 ThrowableInst[It->first] = false; 155 ++NumFastOther; 156 157 // Try to preserve debug information attached to the dead instruction. 158 salvageDebugInfo(*DeadInst); 159 salvageKnowledge(DeadInst); 160 161 // This instruction is dead, zap it, in stages. Start by removing it from 162 // MemDep, which needs to know the operands and needs it to be in the 163 // function. 164 MD.removeInstruction(DeadInst); 165 166 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) { 167 Value *Op = DeadInst->getOperand(op); 168 DeadInst->setOperand(op, nullptr); 169 170 // If this operand just became dead, add it to the NowDeadInsts list. 171 if (!Op->use_empty()) continue; 172 173 if (Instruction *OpI = dyn_cast<Instruction>(Op)) 174 if (isInstructionTriviallyDead(OpI, &TLI)) 175 NowDeadInsts.push_back(OpI); 176 } 177 178 if (ValueSet) ValueSet->remove(DeadInst); 179 IOL.erase(DeadInst); 180 181 if (NewIter == DeadInst->getIterator()) 182 NewIter = DeadInst->eraseFromParent(); 183 else 184 DeadInst->eraseFromParent(); 185 } while (!NowDeadInsts.empty()); 186 *BBI = NewIter; 187 // Pop dead entries from back of ThrowableInst till we find an alive entry. 188 while (!ThrowableInst.empty() && !ThrowableInst.back().second) 189 ThrowableInst.pop_back(); 190 } 191 192 /// Does this instruction write some memory? This only returns true for things 193 /// that we can analyze with other helpers below. 194 static bool hasAnalyzableMemoryWrite(Instruction *I, 195 const TargetLibraryInfo &TLI) { 196 if (isa<StoreInst>(I)) 197 return true; 198 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 199 switch (II->getIntrinsicID()) { 200 default: 201 return false; 202 case Intrinsic::memset: 203 case Intrinsic::memmove: 204 case Intrinsic::memcpy: 205 case Intrinsic::memcpy_element_unordered_atomic: 206 case Intrinsic::memmove_element_unordered_atomic: 207 case Intrinsic::memset_element_unordered_atomic: 208 case Intrinsic::init_trampoline: 209 case Intrinsic::lifetime_end: 210 return true; 211 } 212 } 213 if (auto *CB = dyn_cast<CallBase>(I)) { 214 LibFunc LF; 215 if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) { 216 switch (LF) { 217 case LibFunc_strcpy: 218 case LibFunc_strncpy: 219 case LibFunc_strcat: 220 case LibFunc_strncat: 221 return true; 222 default: 223 return false; 224 } 225 } 226 } 227 return false; 228 } 229 230 /// Return a Location stored to by the specified instruction. If isRemovable 231 /// returns true, this function and getLocForRead completely describe the memory 232 /// operations for this instruction. 233 static MemoryLocation getLocForWrite(Instruction *Inst) { 234 235 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 236 return MemoryLocation::get(SI); 237 238 if (auto *MI = dyn_cast<AnyMemIntrinsic>(Inst)) { 239 // memcpy/memmove/memset. 240 MemoryLocation Loc = MemoryLocation::getForDest(MI); 241 return Loc; 242 } 243 244 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 245 switch (II->getIntrinsicID()) { 246 default: 247 return MemoryLocation(); // Unhandled intrinsic. 248 case Intrinsic::init_trampoline: 249 return MemoryLocation(II->getArgOperand(0)); 250 case Intrinsic::lifetime_end: { 251 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(); 252 return MemoryLocation(II->getArgOperand(1), Len); 253 } 254 } 255 } 256 if (auto *CB = dyn_cast<CallBase>(Inst)) 257 // All the supported TLI functions so far happen to have dest as their 258 // first argument. 259 return MemoryLocation(CB->getArgOperand(0)); 260 return MemoryLocation(); 261 } 262 263 /// Return the location read by the specified "hasAnalyzableMemoryWrite" 264 /// instruction if any. 265 static MemoryLocation getLocForRead(Instruction *Inst, 266 const TargetLibraryInfo &TLI) { 267 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case"); 268 269 // The only instructions that both read and write are the mem transfer 270 // instructions (memcpy/memmove). 271 if (auto *MTI = dyn_cast<AnyMemTransferInst>(Inst)) 272 return MemoryLocation::getForSource(MTI); 273 return MemoryLocation(); 274 } 275 276 /// If the value of this instruction and the memory it writes to is unused, may 277 /// we delete this instruction? 278 static bool isRemovable(Instruction *I) { 279 // Don't remove volatile/atomic stores. 280 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 281 return SI->isUnordered(); 282 283 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 284 switch (II->getIntrinsicID()) { 285 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate"); 286 case Intrinsic::lifetime_end: 287 // Never remove dead lifetime_end's, e.g. because it is followed by a 288 // free. 289 return false; 290 case Intrinsic::init_trampoline: 291 // Always safe to remove init_trampoline. 292 return true; 293 case Intrinsic::memset: 294 case Intrinsic::memmove: 295 case Intrinsic::memcpy: 296 // Don't remove volatile memory intrinsics. 297 return !cast<MemIntrinsic>(II)->isVolatile(); 298 case Intrinsic::memcpy_element_unordered_atomic: 299 case Intrinsic::memmove_element_unordered_atomic: 300 case Intrinsic::memset_element_unordered_atomic: 301 return true; 302 } 303 } 304 305 // note: only get here for calls with analyzable writes - i.e. libcalls 306 if (auto *CB = dyn_cast<CallBase>(I)) 307 return CB->use_empty(); 308 309 return false; 310 } 311 312 /// Returns true if the end of this instruction can be safely shortened in 313 /// length. 314 static bool isShortenableAtTheEnd(Instruction *I) { 315 // Don't shorten stores for now 316 if (isa<StoreInst>(I)) 317 return false; 318 319 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 320 switch (II->getIntrinsicID()) { 321 default: return false; 322 case Intrinsic::memset: 323 case Intrinsic::memcpy: 324 case Intrinsic::memcpy_element_unordered_atomic: 325 case Intrinsic::memset_element_unordered_atomic: 326 // Do shorten memory intrinsics. 327 // FIXME: Add memmove if it's also safe to transform. 328 return true; 329 } 330 } 331 332 // Don't shorten libcalls calls for now. 333 334 return false; 335 } 336 337 /// Returns true if the beginning of this instruction can be safely shortened 338 /// in length. 339 static bool isShortenableAtTheBeginning(Instruction *I) { 340 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 341 // easily done by offsetting the source address. 342 return isa<AnyMemSetInst>(I); 343 } 344 345 /// Return the pointer that is being written to. 346 static Value *getStoredPointerOperand(Instruction *I) { 347 //TODO: factor this to reuse getLocForWrite 348 MemoryLocation Loc = getLocForWrite(I); 349 assert(Loc.Ptr && 350 "unable to find pointer written for analyzable instruction?"); 351 // TODO: most APIs don't expect const Value * 352 return const_cast<Value*>(Loc.Ptr); 353 } 354 355 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 356 const TargetLibraryInfo &TLI, 357 const Function *F) { 358 uint64_t Size; 359 ObjectSizeOpts Opts; 360 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 361 362 if (getObjectSize(V, Size, DL, &TLI, Opts)) 363 return Size; 364 return MemoryLocation::UnknownSize; 365 } 366 367 namespace { 368 369 enum OverwriteResult { 370 OW_Begin, 371 OW_Complete, 372 OW_End, 373 OW_PartialEarlierWithFullLater, 374 OW_MaybePartial, 375 OW_Unknown 376 }; 377 378 } // end anonymous namespace 379 380 /// Return 'OW_Complete' if a store to the 'Later' location completely 381 /// overwrites a store to the 'Earlier' location. Return OW_MaybePartial 382 /// if \p Later does not completely overwrite \p Earlier, but they both 383 /// write to the same underlying object. In that case, use isPartialOverwrite to 384 /// check if \p Later partially overwrites \p Earlier. Returns 'OW_Unknown' if 385 /// nothing can be determined. 386 template <typename AATy> 387 static OverwriteResult 388 isOverwrite(const MemoryLocation &Later, const MemoryLocation &Earlier, 389 const DataLayout &DL, const TargetLibraryInfo &TLI, 390 int64_t &EarlierOff, int64_t &LaterOff, AATy &AA, 391 const Function *F) { 392 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 393 // get imprecise values here, though (except for unknown sizes). 394 if (!Later.Size.isPrecise() || !Earlier.Size.isPrecise()) 395 return OW_Unknown; 396 397 const uint64_t LaterSize = Later.Size.getValue(); 398 const uint64_t EarlierSize = Earlier.Size.getValue(); 399 400 const Value *P1 = Earlier.Ptr->stripPointerCasts(); 401 const Value *P2 = Later.Ptr->stripPointerCasts(); 402 403 // If the start pointers are the same, we just have to compare sizes to see if 404 // the later store was larger than the earlier store. 405 if (P1 == P2 || AA.isMustAlias(P1, P2)) { 406 // Make sure that the Later size is >= the Earlier size. 407 if (LaterSize >= EarlierSize) 408 return OW_Complete; 409 } 410 411 // Check to see if the later store is to the entire object (either a global, 412 // an alloca, or a byval/inalloca argument). If so, then it clearly 413 // overwrites any other store to the same object. 414 const Value *UO1 = getUnderlyingObject(P1), *UO2 = getUnderlyingObject(P2); 415 416 // If we can't resolve the same pointers to the same object, then we can't 417 // analyze them at all. 418 if (UO1 != UO2) 419 return OW_Unknown; 420 421 // If the "Later" store is to a recognizable object, get its size. 422 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI, F); 423 if (ObjectSize != MemoryLocation::UnknownSize) 424 if (ObjectSize == LaterSize && ObjectSize >= EarlierSize) 425 return OW_Complete; 426 427 // Okay, we have stores to two completely different pointers. Try to 428 // decompose the pointer into a "base + constant_offset" form. If the base 429 // pointers are equal, then we can reason about the two stores. 430 EarlierOff = 0; 431 LaterOff = 0; 432 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL); 433 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL); 434 435 // If the base pointers still differ, we have two completely different stores. 436 if (BP1 != BP2) 437 return OW_Unknown; 438 439 // The later store completely overlaps the earlier store if: 440 // 441 // 1. Both start at the same offset and the later one's size is greater than 442 // or equal to the earlier one's, or 443 // 444 // |--earlier--| 445 // |-- later --| 446 // 447 // 2. The earlier store has an offset greater than the later offset, but which 448 // still lies completely within the later store. 449 // 450 // |--earlier--| 451 // |----- later ------| 452 // 453 // We have to be careful here as *Off is signed while *.Size is unsigned. 454 if (EarlierOff >= LaterOff && 455 LaterSize >= EarlierSize && 456 uint64_t(EarlierOff - LaterOff) + EarlierSize <= LaterSize) 457 return OW_Complete; 458 459 // Later may overwrite earlier completely with other partial writes. 460 return OW_MaybePartial; 461 } 462 463 /// Return 'OW_Complete' if a store to the 'Later' location completely 464 /// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the 465 /// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the 466 /// beginning of the 'Earlier' location is overwritten by 'Later'. 467 /// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was 468 /// overwritten by a latter (smaller) store which doesn't write outside the big 469 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 470 /// NOTE: This function must only be called if both \p Later and \p Earlier 471 /// write to the same underlying object with valid \p EarlierOff and \p 472 /// LaterOff. 473 static OverwriteResult isPartialOverwrite(const MemoryLocation &Later, 474 const MemoryLocation &Earlier, 475 int64_t EarlierOff, int64_t LaterOff, 476 Instruction *DepWrite, 477 InstOverlapIntervalsTy &IOL) { 478 const uint64_t LaterSize = Later.Size.getValue(); 479 const uint64_t EarlierSize = Earlier.Size.getValue(); 480 // We may now overlap, although the overlap is not complete. There might also 481 // be other incomplete overlaps, and together, they might cover the complete 482 // earlier write. 483 // Note: The correctness of this logic depends on the fact that this function 484 // is not even called providing DepWrite when there are any intervening reads. 485 if (EnablePartialOverwriteTracking && 486 LaterOff < int64_t(EarlierOff + EarlierSize) && 487 int64_t(LaterOff + LaterSize) >= EarlierOff) { 488 489 // Insert our part of the overlap into the map. 490 auto &IM = IOL[DepWrite]; 491 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff 492 << ", " << int64_t(EarlierOff + EarlierSize) 493 << ") Later [" << LaterOff << ", " 494 << int64_t(LaterOff + LaterSize) << ")\n"); 495 496 // Make sure that we only insert non-overlapping intervals and combine 497 // adjacent intervals. The intervals are stored in the map with the ending 498 // offset as the key (in the half-open sense) and the starting offset as 499 // the value. 500 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + LaterSize; 501 502 // Find any intervals ending at, or after, LaterIntStart which start 503 // before LaterIntEnd. 504 auto ILI = IM.lower_bound(LaterIntStart); 505 if (ILI != IM.end() && ILI->second <= LaterIntEnd) { 506 // This existing interval is overlapped with the current store somewhere 507 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing 508 // intervals and adjusting our start and end. 509 LaterIntStart = std::min(LaterIntStart, ILI->second); 510 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 511 ILI = IM.erase(ILI); 512 513 // Continue erasing and adjusting our end in case other previous 514 // intervals are also overlapped with the current store. 515 // 516 // |--- ealier 1 ---| |--- ealier 2 ---| 517 // |------- later---------| 518 // 519 while (ILI != IM.end() && ILI->second <= LaterIntEnd) { 520 assert(ILI->second > LaterIntStart && "Unexpected interval"); 521 LaterIntEnd = std::max(LaterIntEnd, ILI->first); 522 ILI = IM.erase(ILI); 523 } 524 } 525 526 IM[LaterIntEnd] = LaterIntStart; 527 528 ILI = IM.begin(); 529 if (ILI->second <= EarlierOff && 530 ILI->first >= int64_t(EarlierOff + EarlierSize)) { 531 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" 532 << EarlierOff << ", " 533 << int64_t(EarlierOff + EarlierSize) 534 << ") Composite Later [" << ILI->second << ", " 535 << ILI->first << ")\n"); 536 ++NumCompletePartials; 537 return OW_Complete; 538 } 539 } 540 541 // Check for an earlier store which writes to all the memory locations that 542 // the later store writes to. 543 if (EnablePartialStoreMerging && LaterOff >= EarlierOff && 544 int64_t(EarlierOff + EarlierSize) > LaterOff && 545 uint64_t(LaterOff - EarlierOff) + LaterSize <= EarlierSize) { 546 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" 547 << EarlierOff << ", " 548 << int64_t(EarlierOff + EarlierSize) 549 << ") by a later store [" << LaterOff << ", " 550 << int64_t(LaterOff + LaterSize) << ")\n"); 551 // TODO: Maybe come up with a better name? 552 return OW_PartialEarlierWithFullLater; 553 } 554 555 // Another interesting case is if the later store overwrites the end of the 556 // earlier store. 557 // 558 // |--earlier--| 559 // |-- later --| 560 // 561 // In this case we may want to trim the size of earlier to avoid generating 562 // writes to addresses which will definitely be overwritten later 563 if (!EnablePartialOverwriteTracking && 564 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + EarlierSize) && 565 int64_t(LaterOff + LaterSize) >= int64_t(EarlierOff + EarlierSize))) 566 return OW_End; 567 568 // Finally, we also need to check if the later store overwrites the beginning 569 // of the earlier store. 570 // 571 // |--earlier--| 572 // |-- later --| 573 // 574 // In this case we may want to move the destination address and trim the size 575 // of earlier to avoid generating writes to addresses which will definitely 576 // be overwritten later. 577 if (!EnablePartialOverwriteTracking && 578 (LaterOff <= EarlierOff && int64_t(LaterOff + LaterSize) > EarlierOff)) { 579 assert(int64_t(LaterOff + LaterSize) < int64_t(EarlierOff + EarlierSize) && 580 "Expect to be handled as OW_Complete"); 581 return OW_Begin; 582 } 583 // Otherwise, they don't completely overlap. 584 return OW_Unknown; 585 } 586 587 /// If 'Inst' might be a self read (i.e. a noop copy of a 588 /// memory region into an identical pointer) then it doesn't actually make its 589 /// input dead in the traditional sense. Consider this case: 590 /// 591 /// memmove(A <- B) 592 /// memmove(A <- A) 593 /// 594 /// In this case, the second store to A does not make the first store to A dead. 595 /// The usual situation isn't an explicit A<-A store like this (which can be 596 /// trivially removed) but a case where two pointers may alias. 597 /// 598 /// This function detects when it is unsafe to remove a dependent instruction 599 /// because the DSE inducing instruction may be a self-read. 600 static bool isPossibleSelfRead(Instruction *Inst, 601 const MemoryLocation &InstStoreLoc, 602 Instruction *DepWrite, 603 const TargetLibraryInfo &TLI, 604 AliasAnalysis &AA) { 605 // Self reads can only happen for instructions that read memory. Get the 606 // location read. 607 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI); 608 if (!InstReadLoc.Ptr) 609 return false; // Not a reading instruction. 610 611 // If the read and written loc obviously don't alias, it isn't a read. 612 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) 613 return false; 614 615 if (isa<AnyMemCpyInst>(Inst)) { 616 // LLVM's memcpy overlap semantics are not fully fleshed out (see PR11763) 617 // but in practice memcpy(A <- B) either means that A and B are disjoint or 618 // are equal (i.e. there are not partial overlaps). Given that, if we have: 619 // 620 // memcpy/memmove(A <- B) // DepWrite 621 // memcpy(A <- B) // Inst 622 // 623 // with Inst reading/writing a >= size than DepWrite, we can reason as 624 // follows: 625 // 626 // - If A == B then both the copies are no-ops, so the DepWrite can be 627 // removed. 628 // - If A != B then A and B are disjoint locations in Inst. Since 629 // Inst.size >= DepWrite.size A and B are disjoint in DepWrite too. 630 // Therefore DepWrite can be removed. 631 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI); 632 633 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr)) 634 return false; 635 } 636 637 // If DepWrite doesn't read memory or if we can't prove it is a must alias, 638 // then it can't be considered dead. 639 return true; 640 } 641 642 /// Returns true if the memory which is accessed by the second instruction is not 643 /// modified between the first and the second instruction. 644 /// Precondition: Second instruction must be dominated by the first 645 /// instruction. 646 template <typename AATy> 647 static bool 648 memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI, AATy &AA, 649 const DataLayout &DL, DominatorTree *DT) { 650 // Do a backwards scan through the CFG from SecondI to FirstI. Look for 651 // instructions which can modify the memory location accessed by SecondI. 652 // 653 // While doing the walk keep track of the address to check. It might be 654 // different in different basic blocks due to PHI translation. 655 using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>; 656 SmallVector<BlockAddressPair, 16> WorkList; 657 // Keep track of the address we visited each block with. Bail out if we 658 // visit a block with different addresses. 659 DenseMap<BasicBlock *, Value *> Visited; 660 661 BasicBlock::iterator FirstBBI(FirstI); 662 ++FirstBBI; 663 BasicBlock::iterator SecondBBI(SecondI); 664 BasicBlock *FirstBB = FirstI->getParent(); 665 BasicBlock *SecondBB = SecondI->getParent(); 666 MemoryLocation MemLoc = MemoryLocation::get(SecondI); 667 auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr); 668 669 // Start checking the SecondBB. 670 WorkList.push_back( 671 std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr))); 672 bool isFirstBlock = true; 673 674 // Check all blocks going backward until we reach the FirstBB. 675 while (!WorkList.empty()) { 676 BlockAddressPair Current = WorkList.pop_back_val(); 677 BasicBlock *B = Current.first; 678 PHITransAddr &Addr = Current.second; 679 Value *Ptr = Addr.getAddr(); 680 681 // Ignore instructions before FirstI if this is the FirstBB. 682 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 683 684 BasicBlock::iterator EI; 685 if (isFirstBlock) { 686 // Ignore instructions after SecondI if this is the first visit of SecondBB. 687 assert(B == SecondBB && "first block is not the store block"); 688 EI = SecondBBI; 689 isFirstBlock = false; 690 } else { 691 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 692 // In this case we also have to look at instructions after SecondI. 693 EI = B->end(); 694 } 695 for (; BI != EI; ++BI) { 696 Instruction *I = &*BI; 697 if (I->mayWriteToMemory() && I != SecondI) 698 if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr)))) 699 return false; 700 } 701 if (B != FirstBB) { 702 assert(B != &FirstBB->getParent()->getEntryBlock() && 703 "Should not hit the entry block because SI must be dominated by LI"); 704 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) { 705 PHITransAddr PredAddr = Addr; 706 if (PredAddr.NeedsPHITranslationFromBlock(B)) { 707 if (!PredAddr.IsPotentiallyPHITranslatable()) 708 return false; 709 if (PredAddr.PHITranslateValue(B, *PredI, DT, false)) 710 return false; 711 } 712 Value *TranslatedPtr = PredAddr.getAddr(); 713 auto Inserted = Visited.insert(std::make_pair(*PredI, TranslatedPtr)); 714 if (!Inserted.second) { 715 // We already visited this block before. If it was with a different 716 // address - bail out! 717 if (TranslatedPtr != Inserted.first->second) 718 return false; 719 // ... otherwise just skip it. 720 continue; 721 } 722 WorkList.push_back(std::make_pair(*PredI, PredAddr)); 723 } 724 } 725 } 726 return true; 727 } 728 729 /// Find all blocks that will unconditionally lead to the block BB and append 730 /// them to F. 731 static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks, 732 BasicBlock *BB, DominatorTree *DT) { 733 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 734 BasicBlock *Pred = *I; 735 if (Pred == BB) continue; 736 Instruction *PredTI = Pred->getTerminator(); 737 if (PredTI->getNumSuccessors() != 1) 738 continue; 739 740 if (DT->isReachableFromEntry(Pred)) 741 Blocks.push_back(Pred); 742 } 743 } 744 745 /// Handle frees of entire structures whose dependency is a store 746 /// to a field of that structure. 747 static bool handleFree(CallInst *F, AliasAnalysis *AA, 748 MemoryDependenceResults *MD, DominatorTree *DT, 749 const TargetLibraryInfo *TLI, 750 InstOverlapIntervalsTy &IOL, 751 MapVector<Instruction *, bool> &ThrowableInst) { 752 bool MadeChange = false; 753 754 MemoryLocation Loc = MemoryLocation(F->getOperand(0)); 755 SmallVector<BasicBlock *, 16> Blocks; 756 Blocks.push_back(F->getParent()); 757 758 while (!Blocks.empty()) { 759 BasicBlock *BB = Blocks.pop_back_val(); 760 Instruction *InstPt = BB->getTerminator(); 761 if (BB == F->getParent()) InstPt = F; 762 763 MemDepResult Dep = 764 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB); 765 while (Dep.isDef() || Dep.isClobber()) { 766 Instruction *Dependency = Dep.getInst(); 767 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) || 768 !isRemovable(Dependency)) 769 break; 770 771 Value *DepPointer = 772 getUnderlyingObject(getStoredPointerOperand(Dependency)); 773 774 // Check for aliasing. 775 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer)) 776 break; 777 778 LLVM_DEBUG( 779 dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: " 780 << *Dependency << '\n'); 781 782 // DCE instructions only used to calculate that store. 783 BasicBlock::iterator BBI(Dependency); 784 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, 785 ThrowableInst); 786 ++NumFastStores; 787 MadeChange = true; 788 789 // Inst's old Dependency is now deleted. Compute the next dependency, 790 // which may also be dead, as in 791 // s[0] = 0; 792 // s[1] = 0; // This has just been deleted. 793 // free(s); 794 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB); 795 } 796 797 if (Dep.isNonLocal()) 798 findUnconditionalPreds(Blocks, BB, DT); 799 } 800 801 return MadeChange; 802 } 803 804 /// Check to see if the specified location may alias any of the stack objects in 805 /// the DeadStackObjects set. If so, they become live because the location is 806 /// being loaded. 807 static void removeAccessedObjects(const MemoryLocation &LoadedLoc, 808 SmallSetVector<const Value *, 16> &DeadStackObjects, 809 const DataLayout &DL, AliasAnalysis *AA, 810 const TargetLibraryInfo *TLI, 811 const Function *F) { 812 const Value *UnderlyingPointer = getUnderlyingObject(LoadedLoc.Ptr); 813 814 // A constant can't be in the dead pointer set. 815 if (isa<Constant>(UnderlyingPointer)) 816 return; 817 818 // If the kill pointer can be easily reduced to an alloca, don't bother doing 819 // extraneous AA queries. 820 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) { 821 DeadStackObjects.remove(UnderlyingPointer); 822 return; 823 } 824 825 // Remove objects that could alias LoadedLoc. 826 DeadStackObjects.remove_if([&](const Value *I) { 827 // See if the loaded location could alias the stack location. 828 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI, F)); 829 return !AA->isNoAlias(StackLoc, LoadedLoc); 830 }); 831 } 832 833 /// Remove dead stores to stack-allocated locations in the function end block. 834 /// Ex: 835 /// %A = alloca i32 836 /// ... 837 /// store i32 1, i32* %A 838 /// ret void 839 static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA, 840 MemoryDependenceResults *MD, 841 const TargetLibraryInfo *TLI, 842 InstOverlapIntervalsTy &IOL, 843 MapVector<Instruction *, bool> &ThrowableInst) { 844 bool MadeChange = false; 845 846 // Keep track of all of the stack objects that are dead at the end of the 847 // function. 848 SmallSetVector<const Value*, 16> DeadStackObjects; 849 850 // Find all of the alloca'd pointers in the entry block. 851 BasicBlock &Entry = BB.getParent()->front(); 852 for (Instruction &I : Entry) { 853 if (isa<AllocaInst>(&I)) 854 DeadStackObjects.insert(&I); 855 856 // Okay, so these are dead heap objects, but if the pointer never escapes 857 // then it's leaked by this function anyways. 858 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true)) 859 DeadStackObjects.insert(&I); 860 } 861 862 // Treat byval or inalloca arguments the same, stores to them are dead at the 863 // end of the function. 864 for (Argument &AI : BB.getParent()->args()) 865 if (AI.hasPassPointeeByValueCopyAttr()) 866 DeadStackObjects.insert(&AI); 867 868 const DataLayout &DL = BB.getModule()->getDataLayout(); 869 870 // Scan the basic block backwards 871 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ 872 --BBI; 873 874 // If we find a store, check to see if it points into a dead stack value. 875 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) { 876 // See through pointer-to-pointer bitcasts 877 SmallVector<const Value *, 4> Pointers; 878 getUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers); 879 880 // Stores to stack values are valid candidates for removal. 881 bool AllDead = true; 882 for (const Value *Pointer : Pointers) 883 if (!DeadStackObjects.count(Pointer)) { 884 AllDead = false; 885 break; 886 } 887 888 if (AllDead) { 889 Instruction *Dead = &*BBI; 890 891 LLVM_DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: " 892 << *Dead << "\n Objects: "; 893 for (SmallVectorImpl<const Value *>::iterator I = 894 Pointers.begin(), 895 E = Pointers.end(); 896 I != E; ++I) { 897 dbgs() << **I; 898 if (std::next(I) != E) 899 dbgs() << ", "; 900 } dbgs() 901 << '\n'); 902 903 // DCE instructions only used to calculate that store. 904 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, ThrowableInst, 905 &DeadStackObjects); 906 ++NumFastStores; 907 MadeChange = true; 908 continue; 909 } 910 } 911 912 // Remove any dead non-memory-mutating instructions. 913 if (isInstructionTriviallyDead(&*BBI, TLI)) { 914 LLVM_DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: " 915 << *&*BBI << '\n'); 916 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, ThrowableInst, 917 &DeadStackObjects); 918 ++NumFastOther; 919 MadeChange = true; 920 continue; 921 } 922 923 if (isa<AllocaInst>(BBI)) { 924 // Remove allocas from the list of dead stack objects; there can't be 925 // any references before the definition. 926 DeadStackObjects.remove(&*BBI); 927 continue; 928 } 929 930 if (auto *Call = dyn_cast<CallBase>(&*BBI)) { 931 // Remove allocation function calls from the list of dead stack objects; 932 // there can't be any references before the definition. 933 if (isAllocLikeFn(&*BBI, TLI)) 934 DeadStackObjects.remove(&*BBI); 935 936 // If this call does not access memory, it can't be loading any of our 937 // pointers. 938 if (AA->doesNotAccessMemory(Call)) 939 continue; 940 941 // If the call might load from any of our allocas, then any store above 942 // the call is live. 943 DeadStackObjects.remove_if([&](const Value *I) { 944 // See if the call site touches the value. 945 return isRefSet(AA->getModRefInfo( 946 Call, I, getPointerSize(I, DL, *TLI, BB.getParent()))); 947 }); 948 949 // If all of the allocas were clobbered by the call then we're not going 950 // to find anything else to process. 951 if (DeadStackObjects.empty()) 952 break; 953 954 continue; 955 } 956 957 // We can remove the dead stores, irrespective of the fence and its ordering 958 // (release/acquire/seq_cst). Fences only constraints the ordering of 959 // already visible stores, it does not make a store visible to other 960 // threads. So, skipping over a fence does not change a store from being 961 // dead. 962 if (isa<FenceInst>(*BBI)) 963 continue; 964 965 MemoryLocation LoadedLoc; 966 967 // If we encounter a use of the pointer, it is no longer considered dead 968 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) { 969 if (!L->isUnordered()) // Be conservative with atomic/volatile load 970 break; 971 LoadedLoc = MemoryLocation::get(L); 972 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) { 973 LoadedLoc = MemoryLocation::get(V); 974 } else if (!BBI->mayReadFromMemory()) { 975 // Instruction doesn't read memory. Note that stores that weren't removed 976 // above will hit this case. 977 continue; 978 } else { 979 // Unknown inst; assume it clobbers everything. 980 break; 981 } 982 983 // Remove any allocas from the DeadPointer set that are loaded, as this 984 // makes any stores above the access live. 985 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI, BB.getParent()); 986 987 // If all of the allocas were clobbered by the access then we're not going 988 // to find anything else to process. 989 if (DeadStackObjects.empty()) 990 break; 991 } 992 993 return MadeChange; 994 } 995 996 static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset, 997 int64_t &EarlierSize, int64_t LaterOffset, 998 int64_t LaterSize, bool IsOverwriteEnd) { 999 // TODO: base this on the target vector size so that if the earlier 1000 // store was too small to get vector writes anyway then its likely 1001 // a good idea to shorten it 1002 // Power of 2 vector writes are probably always a bad idea to optimize 1003 // as any store/memset/memcpy is likely using vector instructions so 1004 // shortening it to not vector size is likely to be slower 1005 auto *EarlierIntrinsic = cast<AnyMemIntrinsic>(EarlierWrite); 1006 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment(); 1007 if (!IsOverwriteEnd) 1008 LaterOffset = int64_t(LaterOffset + LaterSize); 1009 1010 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) && 1011 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0)) 1012 return false; 1013 1014 int64_t NewLength = IsOverwriteEnd 1015 ? LaterOffset - EarlierOffset 1016 : EarlierSize - (LaterOffset - EarlierOffset); 1017 1018 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(EarlierWrite)) { 1019 // When shortening an atomic memory intrinsic, the newly shortened 1020 // length must remain an integer multiple of the element size. 1021 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 1022 if (0 != NewLength % ElementSize) 1023 return false; 1024 } 1025 1026 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 1027 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " 1028 << *EarlierWrite << "\n KILLER (offset " << LaterOffset 1029 << ", " << EarlierSize << ")\n"); 1030 1031 Value *EarlierWriteLength = EarlierIntrinsic->getLength(); 1032 Value *TrimmedLength = 1033 ConstantInt::get(EarlierWriteLength->getType(), NewLength); 1034 EarlierIntrinsic->setLength(TrimmedLength); 1035 1036 EarlierSize = NewLength; 1037 if (!IsOverwriteEnd) { 1038 int64_t OffsetMoved = (LaterOffset - EarlierOffset); 1039 Value *Indices[1] = { 1040 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)}; 1041 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds( 1042 EarlierIntrinsic->getRawDest()->getType()->getPointerElementType(), 1043 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite); 1044 NewDestGEP->setDebugLoc(EarlierIntrinsic->getDebugLoc()); 1045 EarlierIntrinsic->setDest(NewDestGEP); 1046 EarlierOffset = EarlierOffset + OffsetMoved; 1047 } 1048 return true; 1049 } 1050 1051 static bool tryToShortenEnd(Instruction *EarlierWrite, 1052 OverlapIntervalsTy &IntervalMap, 1053 int64_t &EarlierStart, int64_t &EarlierSize) { 1054 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite)) 1055 return false; 1056 1057 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 1058 int64_t LaterStart = OII->second; 1059 int64_t LaterSize = OII->first - LaterStart; 1060 1061 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize && 1062 LaterStart + LaterSize >= EarlierStart + EarlierSize) { 1063 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1064 LaterSize, true)) { 1065 IntervalMap.erase(OII); 1066 return true; 1067 } 1068 } 1069 return false; 1070 } 1071 1072 static bool tryToShortenBegin(Instruction *EarlierWrite, 1073 OverlapIntervalsTy &IntervalMap, 1074 int64_t &EarlierStart, int64_t &EarlierSize) { 1075 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite)) 1076 return false; 1077 1078 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 1079 int64_t LaterStart = OII->second; 1080 int64_t LaterSize = OII->first - LaterStart; 1081 1082 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) { 1083 assert(LaterStart + LaterSize < EarlierStart + EarlierSize && 1084 "Should have been handled as OW_Complete"); 1085 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart, 1086 LaterSize, false)) { 1087 IntervalMap.erase(OII); 1088 return true; 1089 } 1090 } 1091 return false; 1092 } 1093 1094 static bool removePartiallyOverlappedStores(const DataLayout &DL, 1095 InstOverlapIntervalsTy &IOL) { 1096 bool Changed = false; 1097 for (auto OI : IOL) { 1098 Instruction *EarlierWrite = OI.first; 1099 MemoryLocation Loc = getLocForWrite(EarlierWrite); 1100 assert(isRemovable(EarlierWrite) && "Expect only removable instruction"); 1101 1102 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 1103 int64_t EarlierStart = 0; 1104 int64_t EarlierSize = int64_t(Loc.Size.getValue()); 1105 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL); 1106 OverlapIntervalsTy &IntervalMap = OI.second; 1107 Changed |= 1108 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1109 if (IntervalMap.empty()) 1110 continue; 1111 Changed |= 1112 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize); 1113 } 1114 return Changed; 1115 } 1116 1117 static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI, 1118 AliasAnalysis *AA, MemoryDependenceResults *MD, 1119 const DataLayout &DL, 1120 const TargetLibraryInfo *TLI, 1121 InstOverlapIntervalsTy &IOL, 1122 MapVector<Instruction *, bool> &ThrowableInst, 1123 DominatorTree *DT) { 1124 // Must be a store instruction. 1125 StoreInst *SI = dyn_cast<StoreInst>(Inst); 1126 if (!SI) 1127 return false; 1128 1129 // If we're storing the same value back to a pointer that we just loaded from, 1130 // then the store can be removed. 1131 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) { 1132 if (SI->getPointerOperand() == DepLoad->getPointerOperand() && 1133 isRemovable(SI) && 1134 memoryIsNotModifiedBetween(DepLoad, SI, *AA, DL, DT)) { 1135 1136 LLVM_DEBUG( 1137 dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: " 1138 << *DepLoad << "\n STORE: " << *SI << '\n'); 1139 1140 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst); 1141 ++NumRedundantStores; 1142 return true; 1143 } 1144 } 1145 1146 // Remove null stores into the calloc'ed objects 1147 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand()); 1148 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) { 1149 Instruction *UnderlyingPointer = 1150 dyn_cast<Instruction>(getUnderlyingObject(SI->getPointerOperand())); 1151 1152 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) && 1153 memoryIsNotModifiedBetween(UnderlyingPointer, SI, *AA, DL, DT)) { 1154 LLVM_DEBUG( 1155 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: " 1156 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n'); 1157 1158 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, ThrowableInst); 1159 ++NumRedundantStores; 1160 return true; 1161 } 1162 } 1163 return false; 1164 } 1165 1166 template <typename AATy> 1167 static Constant *tryToMergePartialOverlappingStores( 1168 StoreInst *Earlier, StoreInst *Later, int64_t InstWriteOffset, 1169 int64_t DepWriteOffset, const DataLayout &DL, AATy &AA, DominatorTree *DT) { 1170 1171 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) && 1172 DL.typeSizeEqualsStoreSize(Earlier->getValueOperand()->getType()) && 1173 Later && isa<ConstantInt>(Later->getValueOperand()) && 1174 DL.typeSizeEqualsStoreSize(Later->getValueOperand()->getType()) && 1175 memoryIsNotModifiedBetween(Earlier, Later, AA, DL, DT)) { 1176 // If the store we find is: 1177 // a) partially overwritten by the store to 'Loc' 1178 // b) the later store is fully contained in the earlier one and 1179 // c) they both have a constant value 1180 // d) none of the two stores need padding 1181 // Merge the two stores, replacing the earlier store's value with a 1182 // merge of both values. 1183 // TODO: Deal with other constant types (vectors, etc), and probably 1184 // some mem intrinsics (if needed) 1185 1186 APInt EarlierValue = 1187 cast<ConstantInt>(Earlier->getValueOperand())->getValue(); 1188 APInt LaterValue = cast<ConstantInt>(Later->getValueOperand())->getValue(); 1189 unsigned LaterBits = LaterValue.getBitWidth(); 1190 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth()); 1191 LaterValue = LaterValue.zext(EarlierValue.getBitWidth()); 1192 1193 // Offset of the smaller store inside the larger store 1194 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8; 1195 unsigned LShiftAmount = DL.isBigEndian() ? EarlierValue.getBitWidth() - 1196 BitOffsetDiff - LaterBits 1197 : BitOffsetDiff; 1198 APInt Mask = APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount, 1199 LShiftAmount + LaterBits); 1200 // Clear the bits we'll be replacing, then OR with the smaller 1201 // store, shifted appropriately. 1202 APInt Merged = (EarlierValue & ~Mask) | (LaterValue << LShiftAmount); 1203 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *Earlier 1204 << "\n Later: " << *Later 1205 << "\n Merged Value: " << Merged << '\n'); 1206 return ConstantInt::get(Earlier->getValueOperand()->getType(), Merged); 1207 } 1208 return nullptr; 1209 } 1210 1211 static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA, 1212 MemoryDependenceResults *MD, DominatorTree *DT, 1213 const TargetLibraryInfo *TLI) { 1214 const DataLayout &DL = BB.getModule()->getDataLayout(); 1215 bool MadeChange = false; 1216 1217 MapVector<Instruction *, bool> ThrowableInst; 1218 1219 // A map of interval maps representing partially-overwritten value parts. 1220 InstOverlapIntervalsTy IOL; 1221 1222 // Do a top-down walk on the BB. 1223 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) { 1224 // Handle 'free' calls specially. 1225 if (CallInst *F = isFreeCall(&*BBI, TLI)) { 1226 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, ThrowableInst); 1227 // Increment BBI after handleFree has potentially deleted instructions. 1228 // This ensures we maintain a valid iterator. 1229 ++BBI; 1230 continue; 1231 } 1232 1233 Instruction *Inst = &*BBI++; 1234 1235 if (Inst->mayThrow()) { 1236 ThrowableInst[Inst] = true; 1237 continue; 1238 } 1239 1240 // Check to see if Inst writes to memory. If not, continue. 1241 if (!hasAnalyzableMemoryWrite(Inst, *TLI)) 1242 continue; 1243 1244 // eliminateNoopStore will update in iterator, if necessary. 1245 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, 1246 ThrowableInst, DT)) { 1247 MadeChange = true; 1248 continue; 1249 } 1250 1251 // If we find something that writes memory, get its memory dependence. 1252 MemDepResult InstDep = MD->getDependency(Inst); 1253 1254 // Ignore any store where we can't find a local dependence. 1255 // FIXME: cross-block DSE would be fun. :) 1256 if (!InstDep.isDef() && !InstDep.isClobber()) 1257 continue; 1258 1259 // Figure out what location is being stored to. 1260 MemoryLocation Loc = getLocForWrite(Inst); 1261 1262 // If we didn't get a useful location, fail. 1263 if (!Loc.Ptr) 1264 continue; 1265 1266 // Loop until we find a store we can eliminate or a load that 1267 // invalidates the analysis. Without an upper bound on the number of 1268 // instructions examined, this analysis can become very time-consuming. 1269 // However, the potential gain diminishes as we process more instructions 1270 // without eliminating any of them. Therefore, we limit the number of 1271 // instructions we look at. 1272 auto Limit = MD->getDefaultBlockScanLimit(); 1273 while (InstDep.isDef() || InstDep.isClobber()) { 1274 // Get the memory clobbered by the instruction we depend on. MemDep will 1275 // skip any instructions that 'Loc' clearly doesn't interact with. If we 1276 // end up depending on a may- or must-aliased load, then we can't optimize 1277 // away the store and we bail out. However, if we depend on something 1278 // that overwrites the memory location we *can* potentially optimize it. 1279 // 1280 // Find out what memory location the dependent instruction stores. 1281 Instruction *DepWrite = InstDep.getInst(); 1282 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI)) 1283 break; 1284 MemoryLocation DepLoc = getLocForWrite(DepWrite); 1285 // If we didn't get a useful location, or if it isn't a size, bail out. 1286 if (!DepLoc.Ptr) 1287 break; 1288 1289 // Find the last throwable instruction not removed by call to 1290 // deleteDeadInstruction. 1291 Instruction *LastThrowing = nullptr; 1292 if (!ThrowableInst.empty()) 1293 LastThrowing = ThrowableInst.back().first; 1294 1295 // Make sure we don't look past a call which might throw. This is an 1296 // issue because MemoryDependenceAnalysis works in the wrong direction: 1297 // it finds instructions which dominate the current instruction, rather than 1298 // instructions which are post-dominated by the current instruction. 1299 // 1300 // If the underlying object is a non-escaping memory allocation, any store 1301 // to it is dead along the unwind edge. Otherwise, we need to preserve 1302 // the store. 1303 if (LastThrowing && DepWrite->comesBefore(LastThrowing)) { 1304 const Value *Underlying = getUnderlyingObject(DepLoc.Ptr); 1305 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying); 1306 if (!IsStoreDeadOnUnwind) { 1307 // We're looking for a call to an allocation function 1308 // where the allocation doesn't escape before the last 1309 // throwing instruction; PointerMayBeCaptured 1310 // reasonably fast approximation. 1311 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) && 1312 !PointerMayBeCaptured(Underlying, false, true); 1313 } 1314 if (!IsStoreDeadOnUnwind) 1315 break; 1316 } 1317 1318 // If we find a write that is a) removable (i.e., non-volatile), b) is 1319 // completely obliterated by the store to 'Loc', and c) which we know that 1320 // 'Inst' doesn't load from, then we can remove it. 1321 // Also try to merge two stores if a later one only touches memory written 1322 // to by the earlier one. 1323 if (isRemovable(DepWrite) && 1324 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) { 1325 int64_t InstWriteOffset, DepWriteOffset; 1326 OverwriteResult OR = isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, 1327 InstWriteOffset, *AA, BB.getParent()); 1328 if (OR == OW_MaybePartial) 1329 OR = isPartialOverwrite(Loc, DepLoc, DepWriteOffset, InstWriteOffset, 1330 DepWrite, IOL); 1331 1332 if (OR == OW_Complete) { 1333 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DepWrite 1334 << "\n KILLER: " << *Inst << '\n'); 1335 1336 // Delete the store and now-dead instructions that feed it. 1337 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, 1338 ThrowableInst); 1339 ++NumFastStores; 1340 MadeChange = true; 1341 1342 // We erased DepWrite; start over. 1343 InstDep = MD->getDependency(Inst); 1344 continue; 1345 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) || 1346 ((OR == OW_Begin && 1347 isShortenableAtTheBeginning(DepWrite)))) { 1348 assert(!EnablePartialOverwriteTracking && "Do not expect to perform " 1349 "when partial-overwrite " 1350 "tracking is enabled"); 1351 // The overwrite result is known, so these must be known, too. 1352 int64_t EarlierSize = DepLoc.Size.getValue(); 1353 int64_t LaterSize = Loc.Size.getValue(); 1354 bool IsOverwriteEnd = (OR == OW_End); 1355 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize, 1356 InstWriteOffset, LaterSize, IsOverwriteEnd); 1357 } else if (EnablePartialStoreMerging && 1358 OR == OW_PartialEarlierWithFullLater) { 1359 auto *Earlier = dyn_cast<StoreInst>(DepWrite); 1360 auto *Later = dyn_cast<StoreInst>(Inst); 1361 if (Constant *C = tryToMergePartialOverlappingStores( 1362 Earlier, Later, InstWriteOffset, DepWriteOffset, DL, *AA, 1363 DT)) { 1364 auto *SI = new StoreInst( 1365 C, Earlier->getPointerOperand(), false, Earlier->getAlign(), 1366 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite); 1367 1368 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa, 1369 LLVMContext::MD_alias_scope, 1370 LLVMContext::MD_noalias, 1371 LLVMContext::MD_nontemporal}; 1372 SI->copyMetadata(*DepWrite, MDToKeep); 1373 ++NumModifiedStores; 1374 1375 // Delete the old stores and now-dead instructions that feed them. 1376 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, 1377 ThrowableInst); 1378 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, 1379 ThrowableInst); 1380 MadeChange = true; 1381 1382 // We erased DepWrite and Inst (Loc); start over. 1383 break; 1384 } 1385 } 1386 } 1387 1388 // If this is a may-aliased store that is clobbering the store value, we 1389 // can keep searching past it for another must-aliased pointer that stores 1390 // to the same location. For example, in: 1391 // store -> P 1392 // store -> Q 1393 // store -> P 1394 // we can remove the first store to P even though we don't know if P and Q 1395 // alias. 1396 if (DepWrite == &BB.front()) break; 1397 1398 // Can't look past this instruction if it might read 'Loc'. 1399 if (isRefSet(AA->getModRefInfo(DepWrite, Loc))) 1400 break; 1401 1402 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false, 1403 DepWrite->getIterator(), &BB, 1404 /*QueryInst=*/ nullptr, &Limit); 1405 } 1406 } 1407 1408 if (EnablePartialOverwriteTracking) 1409 MadeChange |= removePartiallyOverlappedStores(DL, IOL); 1410 1411 // If this block ends in a return, unwind, or unreachable, all allocas are 1412 // dead at its end, which means stores to them are also dead. 1413 if (BB.getTerminator()->getNumSuccessors() == 0) 1414 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, ThrowableInst); 1415 1416 return MadeChange; 1417 } 1418 1419 static bool eliminateDeadStores(Function &F, AliasAnalysis *AA, 1420 MemoryDependenceResults *MD, DominatorTree *DT, 1421 const TargetLibraryInfo *TLI) { 1422 bool MadeChange = false; 1423 for (BasicBlock &BB : F) 1424 // Only check non-dead blocks. Dead blocks may have strange pointer 1425 // cycles that will confuse alias analysis. 1426 if (DT->isReachableFromEntry(&BB)) 1427 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI); 1428 1429 return MadeChange; 1430 } 1431 1432 namespace { 1433 //============================================================================= 1434 // MemorySSA backed dead store elimination. 1435 // 1436 // The code below implements dead store elimination using MemorySSA. It uses 1437 // the following general approach: given a MemoryDef, walk upwards to find 1438 // clobbering MemoryDefs that may be killed by the starting def. Then check 1439 // that there are no uses that may read the location of the original MemoryDef 1440 // in between both MemoryDefs. A bit more concretely: 1441 // 1442 // For all MemoryDefs StartDef: 1443 // 1. Get the next dominating clobbering MemoryDef (DomAccess) by walking 1444 // upwards. 1445 // 2. Check that there are no reads between DomAccess and the StartDef by 1446 // checking all uses starting at DomAccess and walking until we see StartDef. 1447 // 3. For each found DomDef, check that: 1448 // 1. There are no barrier instructions between DomDef and StartDef (like 1449 // throws or stores with ordering constraints). 1450 // 2. StartDef is executed whenever DomDef is executed. 1451 // 3. StartDef completely overwrites DomDef. 1452 // 4. Erase DomDef from the function and MemorySSA. 1453 1454 // Returns true if \p M is an intrisnic that does not read or write memory. 1455 bool isNoopIntrinsic(MemoryUseOrDef *M) { 1456 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(M->getMemoryInst())) { 1457 switch (II->getIntrinsicID()) { 1458 case Intrinsic::lifetime_start: 1459 case Intrinsic::lifetime_end: 1460 case Intrinsic::invariant_end: 1461 case Intrinsic::launder_invariant_group: 1462 case Intrinsic::assume: 1463 return true; 1464 case Intrinsic::dbg_addr: 1465 case Intrinsic::dbg_declare: 1466 case Intrinsic::dbg_label: 1467 case Intrinsic::dbg_value: 1468 llvm_unreachable("Intrinsic should not be modeled in MemorySSA"); 1469 default: 1470 return false; 1471 } 1472 } 1473 return false; 1474 } 1475 1476 // Check if we can ignore \p D for DSE. 1477 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) { 1478 Instruction *DI = D->getMemoryInst(); 1479 // Calls that only access inaccessible memory cannot read or write any memory 1480 // locations we consider for elimination. 1481 if (auto *CB = dyn_cast<CallBase>(DI)) 1482 if (CB->onlyAccessesInaccessibleMemory()) 1483 return true; 1484 1485 // We can eliminate stores to locations not visible to the caller across 1486 // throwing instructions. 1487 if (DI->mayThrow() && !DefVisibleToCaller) 1488 return true; 1489 1490 // We can remove the dead stores, irrespective of the fence and its ordering 1491 // (release/acquire/seq_cst). Fences only constraints the ordering of 1492 // already visible stores, it does not make a store visible to other 1493 // threads. So, skipping over a fence does not change a store from being 1494 // dead. 1495 if (isa<FenceInst>(DI)) 1496 return true; 1497 1498 // Skip intrinsics that do not really read or modify memory. 1499 if (isNoopIntrinsic(D)) 1500 return true; 1501 1502 return false; 1503 } 1504 1505 struct DSEState { 1506 Function &F; 1507 AliasAnalysis &AA; 1508 1509 /// The single BatchAA instance that is used to cache AA queries. It will 1510 /// not be invalidated over the whole run. This is safe, because: 1511 /// 1. Only memory writes are removed, so the alias cache for memory 1512 /// locations remains valid. 1513 /// 2. No new instructions are added (only instructions removed), so cached 1514 /// information for a deleted value cannot be accessed by a re-used new 1515 /// value pointer. 1516 BatchAAResults BatchAA; 1517 1518 MemorySSA &MSSA; 1519 DominatorTree &DT; 1520 PostDominatorTree &PDT; 1521 const TargetLibraryInfo &TLI; 1522 const DataLayout &DL; 1523 1524 // All MemoryDefs that potentially could kill other MemDefs. 1525 SmallVector<MemoryDef *, 64> MemDefs; 1526 // Any that should be skipped as they are already deleted 1527 SmallPtrSet<MemoryAccess *, 4> SkipStores; 1528 // Keep track of all of the objects that are invisible to the caller before 1529 // the function returns. 1530 // SmallPtrSet<const Value *, 16> InvisibleToCallerBeforeRet; 1531 DenseMap<const Value *, bool> InvisibleToCallerBeforeRet; 1532 // Keep track of all of the objects that are invisible to the caller after 1533 // the function returns. 1534 DenseMap<const Value *, bool> InvisibleToCallerAfterRet; 1535 // Keep track of blocks with throwing instructions not modeled in MemorySSA. 1536 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks; 1537 // Post-order numbers for each basic block. Used to figure out if memory 1538 // accesses are executed before another access. 1539 DenseMap<BasicBlock *, unsigned> PostOrderNumbers; 1540 1541 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per 1542 /// basic block. 1543 DenseMap<BasicBlock *, InstOverlapIntervalsTy> IOLs; 1544 1545 DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, 1546 PostDominatorTree &PDT, const TargetLibraryInfo &TLI) 1547 : F(F), AA(AA), BatchAA(AA), MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI), 1548 DL(F.getParent()->getDataLayout()) {} 1549 1550 static DSEState get(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 1551 DominatorTree &DT, PostDominatorTree &PDT, 1552 const TargetLibraryInfo &TLI) { 1553 DSEState State(F, AA, MSSA, DT, PDT, TLI); 1554 // Collect blocks with throwing instructions not modeled in MemorySSA and 1555 // alloc-like objects. 1556 unsigned PO = 0; 1557 for (BasicBlock *BB : post_order(&F)) { 1558 State.PostOrderNumbers[BB] = PO++; 1559 for (Instruction &I : *BB) { 1560 MemoryAccess *MA = MSSA.getMemoryAccess(&I); 1561 if (I.mayThrow() && !MA) 1562 State.ThrowingBlocks.insert(I.getParent()); 1563 1564 auto *MD = dyn_cast_or_null<MemoryDef>(MA); 1565 if (MD && State.MemDefs.size() < MemorySSADefsPerBlockLimit && 1566 (State.getLocForWriteEx(&I) || State.isMemTerminatorInst(&I))) 1567 State.MemDefs.push_back(MD); 1568 } 1569 } 1570 1571 // Treat byval or inalloca arguments the same as Allocas, stores to them are 1572 // dead at the end of the function. 1573 for (Argument &AI : F.args()) 1574 if (AI.hasPassPointeeByValueCopyAttr()) { 1575 // For byval, the caller doesn't know the address of the allocation. 1576 if (AI.hasByValAttr()) 1577 State.InvisibleToCallerBeforeRet.insert({&AI, true}); 1578 State.InvisibleToCallerAfterRet.insert({&AI, true}); 1579 } 1580 1581 return State; 1582 } 1583 1584 bool isInvisibleToCallerAfterRet(const Value *V) { 1585 if (isa<AllocaInst>(V)) 1586 return true; 1587 auto I = InvisibleToCallerAfterRet.insert({V, false}); 1588 if (I.second) { 1589 if (!isInvisibleToCallerBeforeRet(V)) { 1590 I.first->second = false; 1591 } else { 1592 auto *Inst = dyn_cast<Instruction>(V); 1593 if (Inst && isAllocLikeFn(Inst, &TLI)) 1594 I.first->second = !PointerMayBeCaptured(V, true, false); 1595 } 1596 } 1597 return I.first->second; 1598 } 1599 1600 bool isInvisibleToCallerBeforeRet(const Value *V) { 1601 if (isa<AllocaInst>(V)) 1602 return true; 1603 auto I = InvisibleToCallerBeforeRet.insert({V, false}); 1604 if (I.second) { 1605 auto *Inst = dyn_cast<Instruction>(V); 1606 if (Inst && isAllocLikeFn(Inst, &TLI)) 1607 // NOTE: This could be made more precise by PointerMayBeCapturedBefore 1608 // with the killing MemoryDef. But we refrain from doing so for now to 1609 // limit compile-time and this does not cause any changes to the number 1610 // of stores removed on a large test set in practice. 1611 I.first->second = !PointerMayBeCaptured(V, false, true); 1612 } 1613 return I.first->second; 1614 } 1615 1616 Optional<MemoryLocation> getLocForWriteEx(Instruction *I) const { 1617 if (!I->mayWriteToMemory()) 1618 return None; 1619 1620 if (auto *MTI = dyn_cast<AnyMemIntrinsic>(I)) 1621 return {MemoryLocation::getForDest(MTI)}; 1622 1623 if (auto *CB = dyn_cast<CallBase>(I)) { 1624 LibFunc LF; 1625 if (TLI.getLibFunc(*CB, LF) && TLI.has(LF)) { 1626 switch (LF) { 1627 case LibFunc_strcpy: 1628 case LibFunc_strncpy: 1629 case LibFunc_strcat: 1630 case LibFunc_strncat: 1631 return {MemoryLocation(CB->getArgOperand(0))}; 1632 default: 1633 break; 1634 } 1635 } 1636 switch (CB->getIntrinsicID()) { 1637 case Intrinsic::init_trampoline: 1638 return {MemoryLocation(CB->getArgOperand(0))}; 1639 default: 1640 break; 1641 } 1642 return None; 1643 } 1644 1645 return MemoryLocation::getOrNone(I); 1646 } 1647 1648 /// Returns true if \p Use completely overwrites \p DefLoc. 1649 bool isCompleteOverwrite(MemoryLocation DefLoc, Instruction *UseInst) { 1650 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a 1651 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a 1652 // MemoryDef. 1653 if (!UseInst->mayWriteToMemory()) 1654 return false; 1655 1656 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1657 if (CB->onlyAccessesInaccessibleMemory()) 1658 return false; 1659 1660 int64_t InstWriteOffset, DepWriteOffset; 1661 auto CC = getLocForWriteEx(UseInst); 1662 return CC && isOverwrite(*CC, DefLoc, DL, TLI, DepWriteOffset, 1663 InstWriteOffset, BatchAA, &F) == OW_Complete; 1664 } 1665 1666 /// Returns true if \p Def is not read before returning from the function. 1667 bool isWriteAtEndOfFunction(MemoryDef *Def) { 1668 LLVM_DEBUG(dbgs() << " Check if def " << *Def << " (" 1669 << *Def->getMemoryInst() 1670 << ") is at the end the function \n"); 1671 1672 auto MaybeLoc = getLocForWriteEx(Def->getMemoryInst()); 1673 if (!MaybeLoc) { 1674 LLVM_DEBUG(dbgs() << " ... could not get location for write.\n"); 1675 return false; 1676 } 1677 1678 SmallVector<MemoryAccess *, 4> WorkList; 1679 SmallPtrSet<MemoryAccess *, 8> Visited; 1680 auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) { 1681 if (!Visited.insert(Acc).second) 1682 return; 1683 for (Use &U : Acc->uses()) 1684 WorkList.push_back(cast<MemoryAccess>(U.getUser())); 1685 }; 1686 PushMemUses(Def); 1687 for (unsigned I = 0; I < WorkList.size(); I++) { 1688 if (WorkList.size() >= MemorySSAScanLimit) { 1689 LLVM_DEBUG(dbgs() << " ... hit exploration limit.\n"); 1690 return false; 1691 } 1692 1693 MemoryAccess *UseAccess = WorkList[I]; 1694 if (isa<MemoryPhi>(UseAccess)) { 1695 PushMemUses(UseAccess); 1696 continue; 1697 } 1698 1699 // TODO: Checking for aliasing is expensive. Consider reducing the amount 1700 // of times this is called and/or caching it. 1701 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1702 if (isReadClobber(*MaybeLoc, UseInst)) { 1703 LLVM_DEBUG(dbgs() << " ... hit read clobber " << *UseInst << ".\n"); 1704 return false; 1705 } 1706 1707 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) 1708 PushMemUses(UseDef); 1709 } 1710 return true; 1711 } 1712 1713 /// If \p I is a memory terminator like llvm.lifetime.end or free, return a 1714 /// pair with the MemoryLocation terminated by \p I and a boolean flag 1715 /// indicating whether \p I is a free-like call. 1716 Optional<std::pair<MemoryLocation, bool>> 1717 getLocForTerminator(Instruction *I) const { 1718 uint64_t Len; 1719 Value *Ptr; 1720 if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len), 1721 m_Value(Ptr)))) 1722 return {std::make_pair(MemoryLocation(Ptr, Len), false)}; 1723 1724 if (auto *CB = dyn_cast<CallBase>(I)) { 1725 if (isFreeCall(I, &TLI)) 1726 return {std::make_pair(MemoryLocation(CB->getArgOperand(0)), true)}; 1727 } 1728 1729 return None; 1730 } 1731 1732 /// Returns true if \p I is a memory terminator instruction like 1733 /// llvm.lifetime.end or free. 1734 bool isMemTerminatorInst(Instruction *I) const { 1735 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1736 return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) || 1737 isFreeCall(I, &TLI); 1738 } 1739 1740 /// Returns true if \p MaybeTerm is a memory terminator for the same 1741 /// underlying object as \p DefLoc. 1742 bool isMemTerminator(MemoryLocation DefLoc, Instruction *MaybeTerm) { 1743 Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc = 1744 getLocForTerminator(MaybeTerm); 1745 1746 if (!MaybeTermLoc) 1747 return false; 1748 1749 // If the terminator is a free-like call, all accesses to the underlying 1750 // object can be considered terminated. 1751 if (MaybeTermLoc->second) 1752 DefLoc = MemoryLocation(getUnderlyingObject(DefLoc.Ptr)); 1753 return BatchAA.isMustAlias(MaybeTermLoc->first, DefLoc); 1754 } 1755 1756 // Returns true if \p Use may read from \p DefLoc. 1757 bool isReadClobber(MemoryLocation DefLoc, Instruction *UseInst) { 1758 if (!UseInst->mayReadFromMemory()) 1759 return false; 1760 1761 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1762 if (CB->onlyAccessesInaccessibleMemory()) 1763 return false; 1764 1765 ModRefInfo MR = BatchAA.getModRefInfo(UseInst, DefLoc); 1766 // If necessary, perform additional analysis. 1767 if (isRefSet(MR)) 1768 MR = AA.callCapturesBefore(UseInst, DefLoc, &DT); 1769 return isRefSet(MR); 1770 } 1771 1772 // Find a MemoryDef writing to \p DefLoc and dominating \p Current, with no 1773 // read access between them or on any other path to a function exit block if 1774 // \p DefLoc is not accessible after the function returns. If there is no such 1775 // MemoryDef, return None. The returned value may not (completely) overwrite 1776 // \p DefLoc. Currently we bail out when we encounter an aliasing MemoryUse 1777 // (read). 1778 Optional<MemoryAccess *> getDomMemoryDef(MemoryDef *KillingDef, 1779 MemoryAccess *Current, 1780 MemoryLocation DefLoc, 1781 const Value *DefUO, 1782 unsigned &ScanLimit) { 1783 if (ScanLimit == 0) { 1784 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1785 return None; 1786 } 1787 1788 MemoryAccess *DomAccess; 1789 bool StepAgain; 1790 LLVM_DEBUG(dbgs() << " trying to get dominating access for " << *Current 1791 << "\n"); 1792 // Find the next clobbering Mod access for DefLoc, starting at Current. 1793 do { 1794 StepAgain = false; 1795 // Reached TOP. 1796 if (MSSA.isLiveOnEntryDef(Current)) 1797 return None; 1798 1799 if (isa<MemoryPhi>(Current)) { 1800 DomAccess = Current; 1801 break; 1802 } 1803 MemoryUseOrDef *CurrentUD = cast<MemoryUseOrDef>(Current); 1804 // Look for access that clobber DefLoc. 1805 DomAccess = MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(CurrentUD, 1806 DefLoc); 1807 if (MSSA.isLiveOnEntryDef(DomAccess)) 1808 return None; 1809 1810 if (isa<MemoryPhi>(DomAccess)) 1811 break; 1812 1813 // Check if we can skip DomDef for DSE. 1814 MemoryDef *DomDef = dyn_cast<MemoryDef>(DomAccess); 1815 if (DomDef && canSkipDef(DomDef, !isInvisibleToCallerBeforeRet(DefUO))) { 1816 StepAgain = true; 1817 Current = DomDef->getDefiningAccess(); 1818 } 1819 1820 } while (StepAgain); 1821 1822 // Accesses to objects accessible after the function returns can only be 1823 // eliminated if the access is killed along all paths to the exit. Collect 1824 // the blocks with killing (=completely overwriting MemoryDefs) and check if 1825 // they cover all paths from DomAccess to any function exit. 1826 SmallPtrSet<Instruction *, 16> KillingDefs; 1827 KillingDefs.insert(KillingDef->getMemoryInst()); 1828 LLVM_DEBUG({ 1829 dbgs() << " Checking for reads of " << *DomAccess; 1830 if (isa<MemoryDef>(DomAccess)) 1831 dbgs() << " (" << *cast<MemoryDef>(DomAccess)->getMemoryInst() << ")\n"; 1832 else 1833 dbgs() << ")\n"; 1834 }); 1835 1836 SmallSetVector<MemoryAccess *, 32> WorkList; 1837 auto PushMemUses = [&WorkList](MemoryAccess *Acc) { 1838 for (Use &U : Acc->uses()) 1839 WorkList.insert(cast<MemoryAccess>(U.getUser())); 1840 }; 1841 PushMemUses(DomAccess); 1842 1843 // Check if DomDef may be read. 1844 for (unsigned I = 0; I < WorkList.size(); I++) { 1845 MemoryAccess *UseAccess = WorkList[I]; 1846 1847 LLVM_DEBUG(dbgs() << " " << *UseAccess); 1848 // Bail out if the number of accesses to check exceeds the scan limit. 1849 if (ScanLimit < (WorkList.size() - I)) { 1850 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1851 return None; 1852 } 1853 --ScanLimit; 1854 1855 if (isa<MemoryPhi>(UseAccess)) { 1856 if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) { 1857 return DT.properlyDominates(KI->getParent(), 1858 UseAccess->getBlock()); 1859 })) { 1860 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n"); 1861 continue; 1862 } 1863 LLVM_DEBUG(dbgs() << "\n ... adding PHI uses\n"); 1864 PushMemUses(UseAccess); 1865 continue; 1866 } 1867 1868 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1869 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n"); 1870 1871 if (any_of(KillingDefs, [this, UseInst](Instruction *KI) { 1872 return DT.dominates(KI, UseInst); 1873 })) { 1874 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n"); 1875 continue; 1876 } 1877 1878 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess))) { 1879 LLVM_DEBUG(dbgs() << " ... adding uses of intrinsic\n"); 1880 PushMemUses(UseAccess); 1881 continue; 1882 } 1883 1884 // A memory terminator kills all preceeding MemoryDefs and all succeeding 1885 // MemoryAccesses. We do not have to check it's users. 1886 if (isMemTerminator(DefLoc, UseInst)) 1887 continue; 1888 1889 // Uses which may read the original MemoryDef mean we cannot eliminate the 1890 // original MD. Stop walk. 1891 if (isReadClobber(DefLoc, UseInst)) { 1892 LLVM_DEBUG(dbgs() << " ... found read clobber\n"); 1893 return None; 1894 } 1895 1896 // For the KillingDef and DomAccess we only have to check if it reads the 1897 // memory location. 1898 // TODO: It would probably be better to check for self-reads before 1899 // calling the function. 1900 if (KillingDef == UseAccess || DomAccess == UseAccess) { 1901 LLVM_DEBUG(dbgs() << " ... skipping killing def/dom access\n"); 1902 continue; 1903 } 1904 1905 // Check all uses for MemoryDefs, except for defs completely overwriting 1906 // the original location. Otherwise we have to check uses of *all* 1907 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might 1908 // miss cases like the following 1909 // 1 = Def(LoE) ; <----- DomDef stores [0,1] 1910 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3] 1911 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3]. 1912 // (The Use points to the *first* Def it may alias) 1913 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias, 1914 // stores [0,1] 1915 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) { 1916 if (isCompleteOverwrite(DefLoc, UseInst)) { 1917 if (!isInvisibleToCallerAfterRet(DefUO) && UseAccess != DomAccess) { 1918 BasicBlock *MaybeKillingBlock = UseInst->getParent(); 1919 if (PostOrderNumbers.find(MaybeKillingBlock)->second < 1920 PostOrderNumbers.find(DomAccess->getBlock())->second) { 1921 1922 LLVM_DEBUG(dbgs() 1923 << " ... found killing def " << *UseInst << "\n"); 1924 KillingDefs.insert(UseInst); 1925 } 1926 } 1927 } else 1928 PushMemUses(UseDef); 1929 } 1930 } 1931 1932 // For accesses to locations visible after the function returns, make sure 1933 // that the location is killed (=overwritten) along all paths from DomAccess 1934 // to the exit. 1935 if (!isInvisibleToCallerAfterRet(DefUO)) { 1936 SmallPtrSet<BasicBlock *, 16> KillingBlocks; 1937 for (Instruction *KD : KillingDefs) 1938 KillingBlocks.insert(KD->getParent()); 1939 assert(!KillingBlocks.empty() && 1940 "Expected at least a single killing block"); 1941 1942 // Find the common post-dominator of all killing blocks. 1943 BasicBlock *CommonPred = *KillingBlocks.begin(); 1944 for (auto I = std::next(KillingBlocks.begin()), E = KillingBlocks.end(); 1945 I != E; I++) { 1946 if (!CommonPred) 1947 break; 1948 CommonPred = PDT.findNearestCommonDominator(CommonPred, *I); 1949 } 1950 1951 // If CommonPred is in the set of killing blocks, just check if it 1952 // post-dominates DomAccess. 1953 if (KillingBlocks.count(CommonPred)) { 1954 if (PDT.dominates(CommonPred, DomAccess->getBlock())) 1955 return {DomAccess}; 1956 return None; 1957 } 1958 1959 // If the common post-dominator does not post-dominate DomAccess, there 1960 // is a path from DomAccess to an exit not going through a killing block. 1961 if (PDT.dominates(CommonPred, DomAccess->getBlock())) { 1962 SetVector<BasicBlock *> WorkList; 1963 1964 // DomAccess's post-order number provides an upper bound of the blocks 1965 // on a path starting at DomAccess. 1966 unsigned UpperBound = 1967 PostOrderNumbers.find(DomAccess->getBlock())->second; 1968 1969 // If CommonPred is null, there are multiple exits from the function. 1970 // They all have to be added to the worklist. 1971 if (CommonPred) 1972 WorkList.insert(CommonPred); 1973 else 1974 for (BasicBlock *R : PDT.roots()) 1975 WorkList.insert(R); 1976 1977 NumCFGTries++; 1978 // Check if all paths starting from an exit node go through one of the 1979 // killing blocks before reaching DomAccess. 1980 for (unsigned I = 0; I < WorkList.size(); I++) { 1981 NumCFGChecks++; 1982 BasicBlock *Current = WorkList[I]; 1983 if (KillingBlocks.count(Current)) 1984 continue; 1985 if (Current == DomAccess->getBlock()) 1986 return None; 1987 1988 // DomAccess is reachable from the entry, so we don't have to explore 1989 // unreachable blocks further. 1990 if (!DT.isReachableFromEntry(Current)) 1991 continue; 1992 1993 unsigned CPO = PostOrderNumbers.find(Current)->second; 1994 // Current block is not on a path starting at DomAccess. 1995 if (CPO > UpperBound) 1996 continue; 1997 for (BasicBlock *Pred : predecessors(Current)) 1998 WorkList.insert(Pred); 1999 2000 if (WorkList.size() >= MemorySSAPathCheckLimit) 2001 return None; 2002 } 2003 NumCFGSuccess++; 2004 return {DomAccess}; 2005 } 2006 return None; 2007 } 2008 2009 // No aliasing MemoryUses of DomAccess found, DomAccess is potentially dead. 2010 return {DomAccess}; 2011 } 2012 2013 // Delete dead memory defs 2014 void deleteDeadInstruction(Instruction *SI) { 2015 MemorySSAUpdater Updater(&MSSA); 2016 SmallVector<Instruction *, 32> NowDeadInsts; 2017 NowDeadInsts.push_back(SI); 2018 --NumFastOther; 2019 2020 while (!NowDeadInsts.empty()) { 2021 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 2022 ++NumFastOther; 2023 2024 // Try to preserve debug information attached to the dead instruction. 2025 salvageDebugInfo(*DeadInst); 2026 salvageKnowledge(DeadInst); 2027 2028 // Remove the Instruction from MSSA. 2029 if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) { 2030 if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) { 2031 SkipStores.insert(MD); 2032 } 2033 Updater.removeMemoryAccess(MA); 2034 } 2035 2036 auto I = IOLs.find(DeadInst->getParent()); 2037 if (I != IOLs.end()) 2038 I->second.erase(DeadInst); 2039 // Remove its operands 2040 for (Use &O : DeadInst->operands()) 2041 if (Instruction *OpI = dyn_cast<Instruction>(O)) { 2042 O = nullptr; 2043 if (isInstructionTriviallyDead(OpI, &TLI)) 2044 NowDeadInsts.push_back(OpI); 2045 } 2046 2047 DeadInst->eraseFromParent(); 2048 } 2049 } 2050 2051 // Check for any extra throws between SI and NI that block DSE. This only 2052 // checks extra maythrows (those that aren't MemoryDef's). MemoryDef that may 2053 // throw are handled during the walk from one def to the next. 2054 bool mayThrowBetween(Instruction *SI, Instruction *NI, 2055 const Value *SILocUnd) { 2056 // First see if we can ignore it by using the fact that SI is an 2057 // alloca/alloca like object that is not visible to the caller during 2058 // execution of the function. 2059 if (SILocUnd && isInvisibleToCallerBeforeRet(SILocUnd)) 2060 return false; 2061 2062 if (SI->getParent() == NI->getParent()) 2063 return ThrowingBlocks.count(SI->getParent()); 2064 return !ThrowingBlocks.empty(); 2065 } 2066 2067 // Check if \p NI acts as a DSE barrier for \p SI. The following instructions 2068 // act as barriers: 2069 // * A memory instruction that may throw and \p SI accesses a non-stack 2070 // object. 2071 // * Atomic stores stronger that monotonic. 2072 bool isDSEBarrier(const Value *SILocUnd, Instruction *NI) { 2073 // If NI may throw it acts as a barrier, unless we are to an alloca/alloca 2074 // like object that does not escape. 2075 if (NI->mayThrow() && !isInvisibleToCallerBeforeRet(SILocUnd)) 2076 return true; 2077 2078 // If NI is an atomic load/store stronger than monotonic, do not try to 2079 // eliminate/reorder it. 2080 if (NI->isAtomic()) { 2081 if (auto *LI = dyn_cast<LoadInst>(NI)) 2082 return isStrongerThanMonotonic(LI->getOrdering()); 2083 if (auto *SI = dyn_cast<StoreInst>(NI)) 2084 return isStrongerThanMonotonic(SI->getOrdering()); 2085 if (auto *ARMW = dyn_cast<AtomicRMWInst>(NI)) 2086 return isStrongerThanMonotonic(ARMW->getOrdering()); 2087 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(NI)) 2088 return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) || 2089 isStrongerThanMonotonic(CmpXchg->getFailureOrdering()); 2090 llvm_unreachable("other instructions should be skipped in MemorySSA"); 2091 } 2092 return false; 2093 } 2094 2095 /// Eliminate writes to objects that are not visible in the caller and are not 2096 /// accessed before returning from the function. 2097 bool eliminateDeadWritesAtEndOfFunction() { 2098 bool MadeChange = false; 2099 LLVM_DEBUG( 2100 dbgs() 2101 << "Trying to eliminate MemoryDefs at the end of the function\n"); 2102 for (int I = MemDefs.size() - 1; I >= 0; I--) { 2103 MemoryDef *Def = MemDefs[I]; 2104 if (SkipStores.find(Def) != SkipStores.end() || 2105 !isRemovable(Def->getMemoryInst())) 2106 continue; 2107 2108 Instruction *DefI = Def->getMemoryInst(); 2109 SmallVector<const Value *, 4> Pointers; 2110 auto DefLoc = getLocForWriteEx(DefI); 2111 if (!DefLoc) 2112 continue; 2113 2114 // NOTE: Currently eliminating writes at the end of a function is limited 2115 // to MemoryDefs with a single underlying object, to save compile-time. In 2116 // practice it appears the case with multiple underlying objects is very 2117 // uncommon. If it turns out to be important, we can use 2118 // getUnderlyingObjects here instead. 2119 const Value *UO = getUnderlyingObject(DefLoc->Ptr); 2120 if (!UO || !isInvisibleToCallerAfterRet(UO)) 2121 continue; 2122 2123 if (isWriteAtEndOfFunction(Def)) { 2124 // See through pointer-to-pointer bitcasts 2125 LLVM_DEBUG(dbgs() << " ... MemoryDef is not accessed until the end " 2126 "of the function\n"); 2127 deleteDeadInstruction(DefI); 2128 ++NumFastStores; 2129 MadeChange = true; 2130 } 2131 } 2132 return MadeChange; 2133 } 2134 2135 /// \returns true if \p Def is a no-op store, either because it 2136 /// directly stores back a loaded value or stores zero to a calloced object. 2137 bool storeIsNoop(MemoryDef *Def, MemoryLocation DefLoc, const Value *DefUO) { 2138 StoreInst *Store = dyn_cast<StoreInst>(Def->getMemoryInst()); 2139 if (!Store) 2140 return false; 2141 2142 if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) { 2143 if (LoadI->getPointerOperand() == Store->getOperand(1)) { 2144 auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess(); 2145 // If both accesses share the same defining access, no instructions 2146 // between them can modify the memory location. 2147 return LoadAccess == Def->getDefiningAccess(); 2148 } 2149 } 2150 2151 Constant *StoredConstant = dyn_cast<Constant>(Store->getOperand(0)); 2152 if (StoredConstant && StoredConstant->isNullValue()) { 2153 auto *DefUOInst = dyn_cast<Instruction>(DefUO); 2154 if (DefUOInst && isCallocLikeFn(DefUOInst, &TLI)) { 2155 auto *UnderlyingDef = cast<MemoryDef>(MSSA.getMemoryAccess(DefUOInst)); 2156 // If UnderlyingDef is the clobbering access of Def, no instructions 2157 // between them can modify the memory location. 2158 auto *ClobberDef = 2159 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def); 2160 return UnderlyingDef == ClobberDef; 2161 } 2162 } 2163 return false; 2164 } 2165 }; 2166 2167 bool eliminateDeadStoresMemorySSA(Function &F, AliasAnalysis &AA, 2168 MemorySSA &MSSA, DominatorTree &DT, 2169 PostDominatorTree &PDT, 2170 const TargetLibraryInfo &TLI) { 2171 bool MadeChange = false; 2172 2173 DSEState State = DSEState::get(F, AA, MSSA, DT, PDT, TLI); 2174 // For each store: 2175 for (unsigned I = 0; I < State.MemDefs.size(); I++) { 2176 MemoryDef *KillingDef = State.MemDefs[I]; 2177 if (State.SkipStores.count(KillingDef)) 2178 continue; 2179 Instruction *SI = KillingDef->getMemoryInst(); 2180 2181 auto MaybeSILoc = State.getLocForWriteEx(SI); 2182 if (State.isMemTerminatorInst(SI)) 2183 MaybeSILoc = State.getLocForTerminator(SI).map( 2184 [](const std::pair<MemoryLocation, bool> &P) { return P.first; }); 2185 else 2186 MaybeSILoc = State.getLocForWriteEx(SI); 2187 2188 if (!MaybeSILoc) { 2189 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for " 2190 << *SI << "\n"); 2191 continue; 2192 } 2193 MemoryLocation SILoc = *MaybeSILoc; 2194 assert(SILoc.Ptr && "SILoc should not be null"); 2195 const Value *SILocUnd = getUnderlyingObject(SILoc.Ptr); 2196 2197 // Check if the store is a no-op. 2198 if (isRemovable(SI) && State.storeIsNoop(KillingDef, SILoc, SILocUnd)) { 2199 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *SI << '\n'); 2200 State.deleteDeadInstruction(SI); 2201 NumRedundantStores++; 2202 MadeChange = true; 2203 continue; 2204 } 2205 2206 MemoryAccess *Current = KillingDef; 2207 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by " 2208 << *KillingDef << " (" << *SI << ")\n"); 2209 2210 unsigned ScanLimit = MemorySSAScanLimit; 2211 // Worklist of MemoryAccesses that may be killed by KillingDef. 2212 SetVector<MemoryAccess *> ToCheck; 2213 ToCheck.insert(KillingDef->getDefiningAccess()); 2214 2215 // Check if MemoryAccesses in the worklist are killed by KillingDef. 2216 for (unsigned I = 0; I < ToCheck.size(); I++) { 2217 Current = ToCheck[I]; 2218 if (State.SkipStores.count(Current)) 2219 continue; 2220 2221 Optional<MemoryAccess *> Next = State.getDomMemoryDef( 2222 KillingDef, Current, SILoc, SILocUnd, ScanLimit); 2223 2224 if (!Next) { 2225 LLVM_DEBUG(dbgs() << " finished walk\n"); 2226 continue; 2227 } 2228 2229 MemoryAccess *DomAccess = *Next; 2230 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DomAccess); 2231 if (isa<MemoryPhi>(DomAccess)) { 2232 LLVM_DEBUG(dbgs() << "\n ... adding incoming values to worklist\n"); 2233 for (Value *V : cast<MemoryPhi>(DomAccess)->incoming_values()) { 2234 MemoryAccess *IncomingAccess = cast<MemoryAccess>(V); 2235 BasicBlock *IncomingBlock = IncomingAccess->getBlock(); 2236 BasicBlock *PhiBlock = DomAccess->getBlock(); 2237 2238 // We only consider incoming MemoryAccesses that come before the 2239 // MemoryPhi. Otherwise we could discover candidates that do not 2240 // strictly dominate our starting def. 2241 if (State.PostOrderNumbers[IncomingBlock] > 2242 State.PostOrderNumbers[PhiBlock]) 2243 ToCheck.insert(IncomingAccess); 2244 } 2245 continue; 2246 } 2247 MemoryDef *NextDef = dyn_cast<MemoryDef>(DomAccess); 2248 Instruction *NI = NextDef->getMemoryInst(); 2249 LLVM_DEBUG(dbgs() << " (" << *NI << ")\n"); 2250 2251 // Before we try to remove anything, check for any extra throwing 2252 // instructions that block us from DSEing 2253 if (State.mayThrowBetween(SI, NI, SILocUnd)) { 2254 LLVM_DEBUG(dbgs() << " ... skip, may throw!\n"); 2255 break; 2256 } 2257 2258 // Check for anything that looks like it will be a barrier to further 2259 // removal 2260 if (State.isDSEBarrier(SILocUnd, NI)) { 2261 LLVM_DEBUG(dbgs() << " ... skip, barrier\n"); 2262 continue; 2263 } 2264 2265 ToCheck.insert(NextDef->getDefiningAccess()); 2266 2267 if (!hasAnalyzableMemoryWrite(NI, TLI)) { 2268 LLVM_DEBUG(dbgs() << " ... skip, cannot analyze def\n"); 2269 continue; 2270 } 2271 2272 if (!isRemovable(NI)) { 2273 LLVM_DEBUG(dbgs() << " ... skip, cannot remove def\n"); 2274 continue; 2275 } 2276 2277 if (!DebugCounter::shouldExecute(MemorySSACounter)) 2278 continue; 2279 2280 MemoryLocation NILoc = *State.getLocForWriteEx(NI); 2281 2282 if (State.isMemTerminatorInst(SI)) { 2283 const Value *NIUnd = getUnderlyingObject(NILoc.Ptr); 2284 if (!SILocUnd || SILocUnd != NIUnd) 2285 continue; 2286 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 2287 << "\n KILLER: " << *SI << '\n'); 2288 State.deleteDeadInstruction(NI); 2289 ++NumFastStores; 2290 MadeChange = true; 2291 } else { 2292 // Check if NI overwrites SI. 2293 int64_t InstWriteOffset, DepWriteOffset; 2294 OverwriteResult OR = 2295 isOverwrite(SILoc, NILoc, State.DL, TLI, DepWriteOffset, 2296 InstWriteOffset, State.BatchAA, &F); 2297 if (OR == OW_MaybePartial) { 2298 auto Iter = State.IOLs.insert( 2299 std::make_pair<BasicBlock *, InstOverlapIntervalsTy>( 2300 NI->getParent(), InstOverlapIntervalsTy())); 2301 auto &IOL = Iter.first->second; 2302 OR = isPartialOverwrite(SILoc, NILoc, DepWriteOffset, InstWriteOffset, 2303 NI, IOL); 2304 } 2305 2306 if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) { 2307 auto *Earlier = dyn_cast<StoreInst>(NI); 2308 auto *Later = dyn_cast<StoreInst>(SI); 2309 // We are re-using tryToMergePartialOverlappingStores, which requires 2310 // Earlier to domiante Later. 2311 // TODO: implement tryToMergeParialOverlappingStores using MemorySSA. 2312 if (Earlier && Later && DT.dominates(Earlier, Later)) { 2313 if (Constant *Merged = tryToMergePartialOverlappingStores( 2314 Earlier, Later, InstWriteOffset, DepWriteOffset, State.DL, 2315 State.BatchAA, &DT)) { 2316 2317 // Update stored value of earlier store to merged constant. 2318 Earlier->setOperand(0, Merged); 2319 ++NumModifiedStores; 2320 MadeChange = true; 2321 2322 // Remove later store and remove any outstanding overlap intervals 2323 // for the updated store. 2324 State.deleteDeadInstruction(Later); 2325 auto I = State.IOLs.find(Earlier->getParent()); 2326 if (I != State.IOLs.end()) 2327 I->second.erase(Earlier); 2328 break; 2329 } 2330 } 2331 } 2332 2333 if (OR == OW_Complete) { 2334 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *NI 2335 << "\n KILLER: " << *SI << '\n'); 2336 State.deleteDeadInstruction(NI); 2337 ++NumFastStores; 2338 MadeChange = true; 2339 } 2340 } 2341 } 2342 } 2343 2344 if (EnablePartialOverwriteTracking) 2345 for (auto &KV : State.IOLs) 2346 MadeChange |= removePartiallyOverlappedStores(State.DL, KV.second); 2347 2348 MadeChange |= State.eliminateDeadWritesAtEndOfFunction(); 2349 return MadeChange; 2350 } 2351 } // end anonymous namespace 2352 2353 //===----------------------------------------------------------------------===// 2354 // DSE Pass 2355 //===----------------------------------------------------------------------===// 2356 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 2357 AliasAnalysis &AA = AM.getResult<AAManager>(F); 2358 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F); 2359 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 2360 2361 bool Changed = false; 2362 if (EnableMemorySSA) { 2363 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 2364 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 2365 2366 Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI); 2367 } else { 2368 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 2369 2370 Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI); 2371 } 2372 2373 #ifdef LLVM_ENABLE_STATS 2374 if (AreStatisticsEnabled()) 2375 for (auto &I : instructions(F)) 2376 NumRemainingStores += isa<StoreInst>(&I); 2377 #endif 2378 2379 if (!Changed) 2380 return PreservedAnalyses::all(); 2381 2382 PreservedAnalyses PA; 2383 PA.preserveSet<CFGAnalyses>(); 2384 PA.preserve<GlobalsAA>(); 2385 if (EnableMemorySSA) 2386 PA.preserve<MemorySSAAnalysis>(); 2387 else 2388 PA.preserve<MemoryDependenceAnalysis>(); 2389 return PA; 2390 } 2391 2392 namespace { 2393 2394 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 2395 class DSELegacyPass : public FunctionPass { 2396 public: 2397 static char ID; // Pass identification, replacement for typeid 2398 2399 DSELegacyPass() : FunctionPass(ID) { 2400 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 2401 } 2402 2403 bool runOnFunction(Function &F) override { 2404 if (skipFunction(F)) 2405 return false; 2406 2407 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2408 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2409 const TargetLibraryInfo &TLI = 2410 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2411 2412 bool Changed = false; 2413 if (EnableMemorySSA) { 2414 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 2415 PostDominatorTree &PDT = 2416 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 2417 2418 Changed = eliminateDeadStoresMemorySSA(F, AA, MSSA, DT, PDT, TLI); 2419 } else { 2420 MemoryDependenceResults &MD = 2421 getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 2422 2423 Changed = eliminateDeadStores(F, &AA, &MD, &DT, &TLI); 2424 } 2425 2426 #ifdef LLVM_ENABLE_STATS 2427 if (AreStatisticsEnabled()) 2428 for (auto &I : instructions(F)) 2429 NumRemainingStores += isa<StoreInst>(&I); 2430 #endif 2431 2432 return Changed; 2433 } 2434 2435 void getAnalysisUsage(AnalysisUsage &AU) const override { 2436 AU.setPreservesCFG(); 2437 AU.addRequired<AAResultsWrapperPass>(); 2438 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2439 AU.addPreserved<GlobalsAAWrapperPass>(); 2440 AU.addRequired<DominatorTreeWrapperPass>(); 2441 AU.addPreserved<DominatorTreeWrapperPass>(); 2442 2443 if (EnableMemorySSA) { 2444 AU.addRequired<PostDominatorTreeWrapperPass>(); 2445 AU.addRequired<MemorySSAWrapperPass>(); 2446 AU.addPreserved<PostDominatorTreeWrapperPass>(); 2447 AU.addPreserved<MemorySSAWrapperPass>(); 2448 } else { 2449 AU.addRequired<MemoryDependenceWrapperPass>(); 2450 AU.addPreserved<MemoryDependenceWrapperPass>(); 2451 } 2452 } 2453 }; 2454 2455 } // end anonymous namespace 2456 2457 char DSELegacyPass::ID = 0; 2458 2459 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 2460 false) 2461 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2462 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 2463 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2464 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 2465 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 2466 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 2467 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2468 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 2469 false) 2470 2471 FunctionPass *llvm::createDeadStoreEliminationPass() { 2472 return new DSELegacyPass(); 2473 } 2474