1 //===- DeadStoreElimination.cpp - MemorySSA Backed 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 // The code below implements dead store elimination using MemorySSA. It uses 10 // the following general approach: given a MemoryDef, walk upwards to find 11 // clobbering MemoryDefs that may be killed by the starting def. Then check 12 // that there are no uses that may read the location of the original MemoryDef 13 // in between both MemoryDefs. A bit more concretely: 14 // 15 // For all MemoryDefs StartDef: 16 // 1. Get the next dominating clobbering MemoryDef (MaybeDeadAccess) by walking 17 // upwards. 18 // 2. Check that there are no reads between MaybeDeadAccess and the StartDef by 19 // checking all uses starting at MaybeDeadAccess and walking until we see 20 // StartDef. 21 // 3. For each found CurrentDef, check that: 22 // 1. There are no barrier instructions between CurrentDef and StartDef (like 23 // throws or stores with ordering constraints). 24 // 2. StartDef is executed whenever CurrentDef is executed. 25 // 3. StartDef completely overwrites CurrentDef. 26 // 4. Erase CurrentDef from the function and MemorySSA. 27 // 28 //===----------------------------------------------------------------------===// 29 30 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/MapVector.h" 34 #include "llvm/ADT/PostOrderIterator.h" 35 #include "llvm/ADT/SetVector.h" 36 #include "llvm/ADT/SmallPtrSet.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/ADT/StringRef.h" 40 #include "llvm/Analysis/AliasAnalysis.h" 41 #include "llvm/Analysis/CaptureTracking.h" 42 #include "llvm/Analysis/GlobalsModRef.h" 43 #include "llvm/Analysis/LoopInfo.h" 44 #include "llvm/Analysis/MemoryBuiltins.h" 45 #include "llvm/Analysis/MemoryLocation.h" 46 #include "llvm/Analysis/MemorySSA.h" 47 #include "llvm/Analysis/MemorySSAUpdater.h" 48 #include "llvm/Analysis/MustExecute.h" 49 #include "llvm/Analysis/PostDominators.h" 50 #include "llvm/Analysis/TargetLibraryInfo.h" 51 #include "llvm/Analysis/ValueTracking.h" 52 #include "llvm/IR/Argument.h" 53 #include "llvm/IR/BasicBlock.h" 54 #include "llvm/IR/Constant.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/Dominators.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/IRBuilder.h" 60 #include "llvm/IR/InstIterator.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/PassManager.h" 67 #include "llvm/IR/PatternMatch.h" 68 #include "llvm/IR/Value.h" 69 #include "llvm/InitializePasses.h" 70 #include "llvm/Pass.h" 71 #include "llvm/Support/Casting.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Debug.h" 74 #include "llvm/Support/DebugCounter.h" 75 #include "llvm/Support/ErrorHandling.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include "llvm/Transforms/Scalar.h" 78 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 79 #include "llvm/Transforms/Utils/BuildLibCalls.h" 80 #include "llvm/Transforms/Utils/Local.h" 81 #include <algorithm> 82 #include <cassert> 83 #include <cstdint> 84 #include <iterator> 85 #include <map> 86 #include <utility> 87 88 using namespace llvm; 89 using namespace PatternMatch; 90 91 #define DEBUG_TYPE "dse" 92 93 STATISTIC(NumRemainingStores, "Number of stores remaining after DSE"); 94 STATISTIC(NumRedundantStores, "Number of redundant stores deleted"); 95 STATISTIC(NumFastStores, "Number of stores deleted"); 96 STATISTIC(NumFastOther, "Number of other instrs removed"); 97 STATISTIC(NumCompletePartials, "Number of stores dead by later partials"); 98 STATISTIC(NumModifiedStores, "Number of stores modified"); 99 STATISTIC(NumCFGChecks, "Number of stores modified"); 100 STATISTIC(NumCFGTries, "Number of stores modified"); 101 STATISTIC(NumCFGSuccess, "Number of stores modified"); 102 STATISTIC(NumGetDomMemoryDefPassed, 103 "Number of times a valid candidate is returned from getDomMemoryDef"); 104 STATISTIC(NumDomMemDefChecks, 105 "Number iterations check for reads in getDomMemoryDef"); 106 107 DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa", 108 "Controls which MemoryDefs are eliminated."); 109 110 static cl::opt<bool> 111 EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking", 112 cl::init(true), cl::Hidden, 113 cl::desc("Enable partial-overwrite tracking in DSE")); 114 115 static cl::opt<bool> 116 EnablePartialStoreMerging("enable-dse-partial-store-merging", 117 cl::init(true), cl::Hidden, 118 cl::desc("Enable partial store merging in DSE")); 119 120 static cl::opt<unsigned> 121 MemorySSAScanLimit("dse-memoryssa-scanlimit", cl::init(150), cl::Hidden, 122 cl::desc("The number of memory instructions to scan for " 123 "dead store elimination (default = 150)")); 124 static cl::opt<unsigned> MemorySSAUpwardsStepLimit( 125 "dse-memoryssa-walklimit", cl::init(90), cl::Hidden, 126 cl::desc("The maximum number of steps while walking upwards to find " 127 "MemoryDefs that may be killed (default = 90)")); 128 129 static cl::opt<unsigned> MemorySSAPartialStoreLimit( 130 "dse-memoryssa-partial-store-limit", cl::init(5), cl::Hidden, 131 cl::desc("The maximum number candidates that only partially overwrite the " 132 "killing MemoryDef to consider" 133 " (default = 5)")); 134 135 static cl::opt<unsigned> MemorySSADefsPerBlockLimit( 136 "dse-memoryssa-defs-per-block-limit", cl::init(5000), cl::Hidden, 137 cl::desc("The number of MemoryDefs we consider as candidates to eliminated " 138 "other stores per basic block (default = 5000)")); 139 140 static cl::opt<unsigned> MemorySSASameBBStepCost( 141 "dse-memoryssa-samebb-cost", cl::init(1), cl::Hidden, 142 cl::desc( 143 "The cost of a step in the same basic block as the killing MemoryDef" 144 "(default = 1)")); 145 146 static cl::opt<unsigned> 147 MemorySSAOtherBBStepCost("dse-memoryssa-otherbb-cost", cl::init(5), 148 cl::Hidden, 149 cl::desc("The cost of a step in a different basic " 150 "block than the killing MemoryDef" 151 "(default = 5)")); 152 153 static cl::opt<unsigned> MemorySSAPathCheckLimit( 154 "dse-memoryssa-path-check-limit", cl::init(50), cl::Hidden, 155 cl::desc("The maximum number of blocks to check when trying to prove that " 156 "all paths to an exit go through a killing block (default = 50)")); 157 158 // This flags allows or disallows DSE to optimize MemorySSA during its 159 // traversal. Note that DSE optimizing MemorySSA may impact other passes 160 // downstream of the DSE invocation and can lead to issues not being 161 // reproducible in isolation (i.e. when MemorySSA is built from scratch). In 162 // those cases, the flag can be used to check if DSE's MemorySSA optimizations 163 // impact follow-up passes. 164 static cl::opt<bool> 165 OptimizeMemorySSA("dse-optimize-memoryssa", cl::init(true), cl::Hidden, 166 cl::desc("Allow DSE to optimize memory accesses.")); 167 168 //===----------------------------------------------------------------------===// 169 // Helper functions 170 //===----------------------------------------------------------------------===// 171 using OverlapIntervalsTy = std::map<int64_t, int64_t>; 172 using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>; 173 174 /// Returns true if the end of this instruction can be safely shortened in 175 /// length. 176 static bool isShortenableAtTheEnd(Instruction *I) { 177 // Don't shorten stores for now 178 if (isa<StoreInst>(I)) 179 return false; 180 181 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 182 switch (II->getIntrinsicID()) { 183 default: return false; 184 case Intrinsic::memset: 185 case Intrinsic::memcpy: 186 case Intrinsic::memcpy_element_unordered_atomic: 187 case Intrinsic::memset_element_unordered_atomic: 188 // Do shorten memory intrinsics. 189 // FIXME: Add memmove if it's also safe to transform. 190 return true; 191 } 192 } 193 194 // Don't shorten libcalls calls for now. 195 196 return false; 197 } 198 199 /// Returns true if the beginning of this instruction can be safely shortened 200 /// in length. 201 static bool isShortenableAtTheBeginning(Instruction *I) { 202 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be 203 // easily done by offsetting the source address. 204 return isa<AnyMemSetInst>(I); 205 } 206 207 static uint64_t getPointerSize(const Value *V, const DataLayout &DL, 208 const TargetLibraryInfo &TLI, 209 const Function *F) { 210 uint64_t Size; 211 ObjectSizeOpts Opts; 212 Opts.NullIsUnknownSize = NullPointerIsDefined(F); 213 214 if (getObjectSize(V, Size, DL, &TLI, Opts)) 215 return Size; 216 return MemoryLocation::UnknownSize; 217 } 218 219 namespace { 220 221 enum OverwriteResult { 222 OW_Begin, 223 OW_Complete, 224 OW_End, 225 OW_PartialEarlierWithFullLater, 226 OW_MaybePartial, 227 OW_None, 228 OW_Unknown 229 }; 230 231 } // end anonymous namespace 232 233 /// Check if two instruction are masked stores that completely 234 /// overwrite one another. More specifically, \p KillingI has to 235 /// overwrite \p DeadI. 236 static OverwriteResult isMaskedStoreOverwrite(const Instruction *KillingI, 237 const Instruction *DeadI, 238 BatchAAResults &AA) { 239 const auto *KillingII = dyn_cast<IntrinsicInst>(KillingI); 240 const auto *DeadII = dyn_cast<IntrinsicInst>(DeadI); 241 if (KillingII == nullptr || DeadII == nullptr) 242 return OW_Unknown; 243 if (KillingII->getIntrinsicID() != Intrinsic::masked_store || 244 DeadII->getIntrinsicID() != Intrinsic::masked_store) 245 return OW_Unknown; 246 // Pointers. 247 Value *KillingPtr = KillingII->getArgOperand(1)->stripPointerCasts(); 248 Value *DeadPtr = DeadII->getArgOperand(1)->stripPointerCasts(); 249 if (KillingPtr != DeadPtr && !AA.isMustAlias(KillingPtr, DeadPtr)) 250 return OW_Unknown; 251 // Masks. 252 // TODO: check that KillingII's mask is a superset of the DeadII's mask. 253 if (KillingII->getArgOperand(3) != DeadII->getArgOperand(3)) 254 return OW_Unknown; 255 return OW_Complete; 256 } 257 258 /// Return 'OW_Complete' if a store to the 'KillingLoc' location completely 259 /// overwrites a store to the 'DeadLoc' location, 'OW_End' if the end of the 260 /// 'DeadLoc' location is completely overwritten by 'KillingLoc', 'OW_Begin' 261 /// if the beginning of the 'DeadLoc' location is overwritten by 'KillingLoc'. 262 /// 'OW_PartialEarlierWithFullLater' means that a dead (big) store was 263 /// overwritten by a killing (smaller) store which doesn't write outside the big 264 /// store's memory locations. Returns 'OW_Unknown' if nothing can be determined. 265 /// NOTE: This function must only be called if both \p KillingLoc and \p 266 /// DeadLoc belong to the same underlying object with valid \p KillingOff and 267 /// \p DeadOff. 268 static OverwriteResult isPartialOverwrite(const MemoryLocation &KillingLoc, 269 const MemoryLocation &DeadLoc, 270 int64_t KillingOff, int64_t DeadOff, 271 Instruction *DeadI, 272 InstOverlapIntervalsTy &IOL) { 273 const uint64_t KillingSize = KillingLoc.Size.getValue(); 274 const uint64_t DeadSize = DeadLoc.Size.getValue(); 275 // We may now overlap, although the overlap is not complete. There might also 276 // be other incomplete overlaps, and together, they might cover the complete 277 // dead store. 278 // Note: The correctness of this logic depends on the fact that this function 279 // is not even called providing DepWrite when there are any intervening reads. 280 if (EnablePartialOverwriteTracking && 281 KillingOff < int64_t(DeadOff + DeadSize) && 282 int64_t(KillingOff + KillingSize) >= DeadOff) { 283 284 // Insert our part of the overlap into the map. 285 auto &IM = IOL[DeadI]; 286 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: DeadLoc [" << DeadOff << ", " 287 << int64_t(DeadOff + DeadSize) << ") KillingLoc [" 288 << KillingOff << ", " << int64_t(KillingOff + KillingSize) 289 << ")\n"); 290 291 // Make sure that we only insert non-overlapping intervals and combine 292 // adjacent intervals. The intervals are stored in the map with the ending 293 // offset as the key (in the half-open sense) and the starting offset as 294 // the value. 295 int64_t KillingIntStart = KillingOff; 296 int64_t KillingIntEnd = KillingOff + KillingSize; 297 298 // Find any intervals ending at, or after, KillingIntStart which start 299 // before KillingIntEnd. 300 auto ILI = IM.lower_bound(KillingIntStart); 301 if (ILI != IM.end() && ILI->second <= KillingIntEnd) { 302 // This existing interval is overlapped with the current store somewhere 303 // in [KillingIntStart, KillingIntEnd]. Merge them by erasing the existing 304 // intervals and adjusting our start and end. 305 KillingIntStart = std::min(KillingIntStart, ILI->second); 306 KillingIntEnd = std::max(KillingIntEnd, ILI->first); 307 ILI = IM.erase(ILI); 308 309 // Continue erasing and adjusting our end in case other previous 310 // intervals are also overlapped with the current store. 311 // 312 // |--- dead 1 ---| |--- dead 2 ---| 313 // |------- killing---------| 314 // 315 while (ILI != IM.end() && ILI->second <= KillingIntEnd) { 316 assert(ILI->second > KillingIntStart && "Unexpected interval"); 317 KillingIntEnd = std::max(KillingIntEnd, ILI->first); 318 ILI = IM.erase(ILI); 319 } 320 } 321 322 IM[KillingIntEnd] = KillingIntStart; 323 324 ILI = IM.begin(); 325 if (ILI->second <= DeadOff && ILI->first >= int64_t(DeadOff + DeadSize)) { 326 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: DeadLoc [" 327 << DeadOff << ", " << int64_t(DeadOff + DeadSize) 328 << ") Composite KillingLoc [" << ILI->second << ", " 329 << ILI->first << ")\n"); 330 ++NumCompletePartials; 331 return OW_Complete; 332 } 333 } 334 335 // Check for a dead store which writes to all the memory locations that 336 // the killing store writes to. 337 if (EnablePartialStoreMerging && KillingOff >= DeadOff && 338 int64_t(DeadOff + DeadSize) > KillingOff && 339 uint64_t(KillingOff - DeadOff) + KillingSize <= DeadSize) { 340 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite a dead load [" << DeadOff 341 << ", " << int64_t(DeadOff + DeadSize) 342 << ") by a killing store [" << KillingOff << ", " 343 << int64_t(KillingOff + KillingSize) << ")\n"); 344 // TODO: Maybe come up with a better name? 345 return OW_PartialEarlierWithFullLater; 346 } 347 348 // Another interesting case is if the killing store overwrites the end of the 349 // dead store. 350 // 351 // |--dead--| 352 // |-- killing --| 353 // 354 // In this case we may want to trim the size of dead store to avoid 355 // generating stores to addresses which will definitely be overwritten killing 356 // store. 357 if (!EnablePartialOverwriteTracking && 358 (KillingOff > DeadOff && KillingOff < int64_t(DeadOff + DeadSize) && 359 int64_t(KillingOff + KillingSize) >= int64_t(DeadOff + DeadSize))) 360 return OW_End; 361 362 // Finally, we also need to check if the killing store overwrites the 363 // beginning of the dead store. 364 // 365 // |--dead--| 366 // |-- killing --| 367 // 368 // In this case we may want to move the destination address and trim the size 369 // of dead store to avoid generating stores to addresses which will definitely 370 // be overwritten killing store. 371 if (!EnablePartialOverwriteTracking && 372 (KillingOff <= DeadOff && int64_t(KillingOff + KillingSize) > DeadOff)) { 373 assert(int64_t(KillingOff + KillingSize) < int64_t(DeadOff + DeadSize) && 374 "Expect to be handled as OW_Complete"); 375 return OW_Begin; 376 } 377 // Otherwise, they don't completely overlap. 378 return OW_Unknown; 379 } 380 381 /// Returns true if the memory which is accessed by the second instruction is not 382 /// modified between the first and the second instruction. 383 /// Precondition: Second instruction must be dominated by the first 384 /// instruction. 385 static bool 386 memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI, 387 BatchAAResults &AA, const DataLayout &DL, 388 DominatorTree *DT) { 389 // Do a backwards scan through the CFG from SecondI to FirstI. Look for 390 // instructions which can modify the memory location accessed by SecondI. 391 // 392 // While doing the walk keep track of the address to check. It might be 393 // different in different basic blocks due to PHI translation. 394 using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>; 395 SmallVector<BlockAddressPair, 16> WorkList; 396 // Keep track of the address we visited each block with. Bail out if we 397 // visit a block with different addresses. 398 DenseMap<BasicBlock *, Value *> Visited; 399 400 BasicBlock::iterator FirstBBI(FirstI); 401 ++FirstBBI; 402 BasicBlock::iterator SecondBBI(SecondI); 403 BasicBlock *FirstBB = FirstI->getParent(); 404 BasicBlock *SecondBB = SecondI->getParent(); 405 MemoryLocation MemLoc; 406 if (auto *MemSet = dyn_cast<MemSetInst>(SecondI)) 407 MemLoc = MemoryLocation::getForDest(MemSet); 408 else 409 MemLoc = MemoryLocation::get(SecondI); 410 411 auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr); 412 413 // Start checking the SecondBB. 414 WorkList.push_back( 415 std::make_pair(SecondBB, PHITransAddr(MemLocPtr, DL, nullptr))); 416 bool isFirstBlock = true; 417 418 // Check all blocks going backward until we reach the FirstBB. 419 while (!WorkList.empty()) { 420 BlockAddressPair Current = WorkList.pop_back_val(); 421 BasicBlock *B = Current.first; 422 PHITransAddr &Addr = Current.second; 423 Value *Ptr = Addr.getAddr(); 424 425 // Ignore instructions before FirstI if this is the FirstBB. 426 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin()); 427 428 BasicBlock::iterator EI; 429 if (isFirstBlock) { 430 // Ignore instructions after SecondI if this is the first visit of SecondBB. 431 assert(B == SecondBB && "first block is not the store block"); 432 EI = SecondBBI; 433 isFirstBlock = false; 434 } else { 435 // It's not SecondBB or (in case of a loop) the second visit of SecondBB. 436 // In this case we also have to look at instructions after SecondI. 437 EI = B->end(); 438 } 439 for (; BI != EI; ++BI) { 440 Instruction *I = &*BI; 441 if (I->mayWriteToMemory() && I != SecondI) 442 if (isModSet(AA.getModRefInfo(I, MemLoc.getWithNewPtr(Ptr)))) 443 return false; 444 } 445 if (B != FirstBB) { 446 assert(B != &FirstBB->getParent()->getEntryBlock() && 447 "Should not hit the entry block because SI must be dominated by LI"); 448 for (BasicBlock *Pred : predecessors(B)) { 449 PHITransAddr PredAddr = Addr; 450 if (PredAddr.NeedsPHITranslationFromBlock(B)) { 451 if (!PredAddr.IsPotentiallyPHITranslatable()) 452 return false; 453 if (PredAddr.PHITranslateValue(B, Pred, DT, false)) 454 return false; 455 } 456 Value *TranslatedPtr = PredAddr.getAddr(); 457 auto Inserted = Visited.insert(std::make_pair(Pred, TranslatedPtr)); 458 if (!Inserted.second) { 459 // We already visited this block before. If it was with a different 460 // address - bail out! 461 if (TranslatedPtr != Inserted.first->second) 462 return false; 463 // ... otherwise just skip it. 464 continue; 465 } 466 WorkList.push_back(std::make_pair(Pred, PredAddr)); 467 } 468 } 469 } 470 return true; 471 } 472 473 static bool tryToShorten(Instruction *DeadI, int64_t &DeadStart, 474 uint64_t &DeadSize, int64_t KillingStart, 475 uint64_t KillingSize, bool IsOverwriteEnd) { 476 auto *DeadIntrinsic = cast<AnyMemIntrinsic>(DeadI); 477 Align PrefAlign = DeadIntrinsic->getDestAlign().valueOrOne(); 478 479 // We assume that memet/memcpy operates in chunks of the "largest" native 480 // type size and aligned on the same value. That means optimal start and size 481 // of memset/memcpy should be modulo of preferred alignment of that type. That 482 // is it there is no any sense in trying to reduce store size any further 483 // since any "extra" stores comes for free anyway. 484 // On the other hand, maximum alignment we can achieve is limited by alignment 485 // of initial store. 486 487 // TODO: Limit maximum alignment by preferred (or abi?) alignment of the 488 // "largest" native type. 489 // Note: What is the proper way to get that value? 490 // Should TargetTransformInfo::getRegisterBitWidth be used or anything else? 491 // PrefAlign = std::min(DL.getPrefTypeAlign(LargestType), PrefAlign); 492 493 int64_t ToRemoveStart = 0; 494 uint64_t ToRemoveSize = 0; 495 // Compute start and size of the region to remove. Make sure 'PrefAlign' is 496 // maintained on the remaining store. 497 if (IsOverwriteEnd) { 498 // Calculate required adjustment for 'KillingStart' in order to keep 499 // remaining store size aligned on 'PerfAlign'. 500 uint64_t Off = 501 offsetToAlignment(uint64_t(KillingStart - DeadStart), PrefAlign); 502 ToRemoveStart = KillingStart + Off; 503 if (DeadSize <= uint64_t(ToRemoveStart - DeadStart)) 504 return false; 505 ToRemoveSize = DeadSize - uint64_t(ToRemoveStart - DeadStart); 506 } else { 507 ToRemoveStart = DeadStart; 508 assert(KillingSize >= uint64_t(DeadStart - KillingStart) && 509 "Not overlapping accesses?"); 510 ToRemoveSize = KillingSize - uint64_t(DeadStart - KillingStart); 511 // Calculate required adjustment for 'ToRemoveSize'in order to keep 512 // start of the remaining store aligned on 'PerfAlign'. 513 uint64_t Off = offsetToAlignment(ToRemoveSize, PrefAlign); 514 if (Off != 0) { 515 if (ToRemoveSize <= (PrefAlign.value() - Off)) 516 return false; 517 ToRemoveSize -= PrefAlign.value() - Off; 518 } 519 assert(isAligned(PrefAlign, ToRemoveSize) && 520 "Should preserve selected alignment"); 521 } 522 523 assert(ToRemoveSize > 0 && "Shouldn't reach here if nothing to remove"); 524 assert(DeadSize > ToRemoveSize && "Can't remove more than original size"); 525 526 uint64_t NewSize = DeadSize - ToRemoveSize; 527 if (auto *AMI = dyn_cast<AtomicMemIntrinsic>(DeadI)) { 528 // When shortening an atomic memory intrinsic, the newly shortened 529 // length must remain an integer multiple of the element size. 530 const uint32_t ElementSize = AMI->getElementSizeInBytes(); 531 if (0 != NewSize % ElementSize) 532 return false; 533 } 534 535 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW " 536 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *DeadI 537 << "\n KILLER [" << ToRemoveStart << ", " 538 << int64_t(ToRemoveStart + ToRemoveSize) << ")\n"); 539 540 Value *DeadWriteLength = DeadIntrinsic->getLength(); 541 Value *TrimmedLength = ConstantInt::get(DeadWriteLength->getType(), NewSize); 542 DeadIntrinsic->setLength(TrimmedLength); 543 DeadIntrinsic->setDestAlignment(PrefAlign); 544 545 if (!IsOverwriteEnd) { 546 Value *OrigDest = DeadIntrinsic->getRawDest(); 547 Type *Int8PtrTy = 548 Type::getInt8PtrTy(DeadIntrinsic->getContext(), 549 OrigDest->getType()->getPointerAddressSpace()); 550 Value *Dest = OrigDest; 551 if (OrigDest->getType() != Int8PtrTy) 552 Dest = CastInst::CreatePointerCast(OrigDest, Int8PtrTy, "", DeadI); 553 Value *Indices[1] = { 554 ConstantInt::get(DeadWriteLength->getType(), ToRemoveSize)}; 555 Instruction *NewDestGEP = GetElementPtrInst::CreateInBounds( 556 Type::getInt8Ty(DeadIntrinsic->getContext()), Dest, Indices, "", DeadI); 557 NewDestGEP->setDebugLoc(DeadIntrinsic->getDebugLoc()); 558 if (NewDestGEP->getType() != OrigDest->getType()) 559 NewDestGEP = CastInst::CreatePointerCast(NewDestGEP, OrigDest->getType(), 560 "", DeadI); 561 DeadIntrinsic->setDest(NewDestGEP); 562 } 563 564 // Finally update start and size of dead access. 565 if (!IsOverwriteEnd) 566 DeadStart += ToRemoveSize; 567 DeadSize = NewSize; 568 569 return true; 570 } 571 572 static bool tryToShortenEnd(Instruction *DeadI, OverlapIntervalsTy &IntervalMap, 573 int64_t &DeadStart, uint64_t &DeadSize) { 574 if (IntervalMap.empty() || !isShortenableAtTheEnd(DeadI)) 575 return false; 576 577 OverlapIntervalsTy::iterator OII = --IntervalMap.end(); 578 int64_t KillingStart = OII->second; 579 uint64_t KillingSize = OII->first - KillingStart; 580 581 assert(OII->first - KillingStart >= 0 && "Size expected to be positive"); 582 583 if (KillingStart > DeadStart && 584 // Note: "KillingStart - KillingStart" is known to be positive due to 585 // preceding check. 586 (uint64_t)(KillingStart - DeadStart) < DeadSize && 587 // Note: "DeadSize - (uint64_t)(KillingStart - DeadStart)" is known to 588 // be non negative due to preceding checks. 589 KillingSize >= DeadSize - (uint64_t)(KillingStart - DeadStart)) { 590 if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize, 591 true)) { 592 IntervalMap.erase(OII); 593 return true; 594 } 595 } 596 return false; 597 } 598 599 static bool tryToShortenBegin(Instruction *DeadI, 600 OverlapIntervalsTy &IntervalMap, 601 int64_t &DeadStart, uint64_t &DeadSize) { 602 if (IntervalMap.empty() || !isShortenableAtTheBeginning(DeadI)) 603 return false; 604 605 OverlapIntervalsTy::iterator OII = IntervalMap.begin(); 606 int64_t KillingStart = OII->second; 607 uint64_t KillingSize = OII->first - KillingStart; 608 609 assert(OII->first - KillingStart >= 0 && "Size expected to be positive"); 610 611 if (KillingStart <= DeadStart && 612 // Note: "DeadStart - KillingStart" is known to be non negative due to 613 // preceding check. 614 KillingSize > (uint64_t)(DeadStart - KillingStart)) { 615 // Note: "KillingSize - (uint64_t)(DeadStart - DeadStart)" is known to 616 // be positive due to preceding checks. 617 assert(KillingSize - (uint64_t)(DeadStart - KillingStart) < DeadSize && 618 "Should have been handled as OW_Complete"); 619 if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize, 620 false)) { 621 IntervalMap.erase(OII); 622 return true; 623 } 624 } 625 return false; 626 } 627 628 static Constant * 629 tryToMergePartialOverlappingStores(StoreInst *KillingI, StoreInst *DeadI, 630 int64_t KillingOffset, int64_t DeadOffset, 631 const DataLayout &DL, BatchAAResults &AA, 632 DominatorTree *DT) { 633 634 if (DeadI && isa<ConstantInt>(DeadI->getValueOperand()) && 635 DL.typeSizeEqualsStoreSize(DeadI->getValueOperand()->getType()) && 636 KillingI && isa<ConstantInt>(KillingI->getValueOperand()) && 637 DL.typeSizeEqualsStoreSize(KillingI->getValueOperand()->getType()) && 638 memoryIsNotModifiedBetween(DeadI, KillingI, AA, DL, DT)) { 639 // If the store we find is: 640 // a) partially overwritten by the store to 'Loc' 641 // b) the killing store is fully contained in the dead one and 642 // c) they both have a constant value 643 // d) none of the two stores need padding 644 // Merge the two stores, replacing the dead store's value with a 645 // merge of both values. 646 // TODO: Deal with other constant types (vectors, etc), and probably 647 // some mem intrinsics (if needed) 648 649 APInt DeadValue = cast<ConstantInt>(DeadI->getValueOperand())->getValue(); 650 APInt KillingValue = 651 cast<ConstantInt>(KillingI->getValueOperand())->getValue(); 652 unsigned KillingBits = KillingValue.getBitWidth(); 653 assert(DeadValue.getBitWidth() > KillingValue.getBitWidth()); 654 KillingValue = KillingValue.zext(DeadValue.getBitWidth()); 655 656 // Offset of the smaller store inside the larger store 657 unsigned BitOffsetDiff = (KillingOffset - DeadOffset) * 8; 658 unsigned LShiftAmount = 659 DL.isBigEndian() ? DeadValue.getBitWidth() - BitOffsetDiff - KillingBits 660 : BitOffsetDiff; 661 APInt Mask = APInt::getBitsSet(DeadValue.getBitWidth(), LShiftAmount, 662 LShiftAmount + KillingBits); 663 // Clear the bits we'll be replacing, then OR with the smaller 664 // store, shifted appropriately. 665 APInt Merged = (DeadValue & ~Mask) | (KillingValue << LShiftAmount); 666 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Dead: " << *DeadI 667 << "\n Killing: " << *KillingI 668 << "\n Merged Value: " << Merged << '\n'); 669 return ConstantInt::get(DeadI->getValueOperand()->getType(), Merged); 670 } 671 return nullptr; 672 } 673 674 namespace { 675 // Returns true if \p I is an intrisnic that does not read or write memory. 676 bool isNoopIntrinsic(Instruction *I) { 677 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 678 switch (II->getIntrinsicID()) { 679 case Intrinsic::lifetime_start: 680 case Intrinsic::lifetime_end: 681 case Intrinsic::invariant_end: 682 case Intrinsic::launder_invariant_group: 683 case Intrinsic::assume: 684 return true; 685 case Intrinsic::dbg_addr: 686 case Intrinsic::dbg_declare: 687 case Intrinsic::dbg_label: 688 case Intrinsic::dbg_value: 689 llvm_unreachable("Intrinsic should not be modeled in MemorySSA"); 690 default: 691 return false; 692 } 693 } 694 return false; 695 } 696 697 // Check if we can ignore \p D for DSE. 698 bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) { 699 Instruction *DI = D->getMemoryInst(); 700 // Calls that only access inaccessible memory cannot read or write any memory 701 // locations we consider for elimination. 702 if (auto *CB = dyn_cast<CallBase>(DI)) 703 if (CB->onlyAccessesInaccessibleMemory()) 704 return true; 705 706 // We can eliminate stores to locations not visible to the caller across 707 // throwing instructions. 708 if (DI->mayThrow() && !DefVisibleToCaller) 709 return true; 710 711 // We can remove the dead stores, irrespective of the fence and its ordering 712 // (release/acquire/seq_cst). Fences only constraints the ordering of 713 // already visible stores, it does not make a store visible to other 714 // threads. So, skipping over a fence does not change a store from being 715 // dead. 716 if (isa<FenceInst>(DI)) 717 return true; 718 719 // Skip intrinsics that do not really read or modify memory. 720 if (isNoopIntrinsic(DI)) 721 return true; 722 723 return false; 724 } 725 726 struct DSEState { 727 Function &F; 728 AliasAnalysis &AA; 729 EarliestEscapeInfo EI; 730 731 /// The single BatchAA instance that is used to cache AA queries. It will 732 /// not be invalidated over the whole run. This is safe, because: 733 /// 1. Only memory writes are removed, so the alias cache for memory 734 /// locations remains valid. 735 /// 2. No new instructions are added (only instructions removed), so cached 736 /// information for a deleted value cannot be accessed by a re-used new 737 /// value pointer. 738 BatchAAResults BatchAA; 739 740 MemorySSA &MSSA; 741 DominatorTree &DT; 742 PostDominatorTree &PDT; 743 const TargetLibraryInfo &TLI; 744 const DataLayout &DL; 745 const LoopInfo &LI; 746 747 // Whether the function contains any irreducible control flow, useful for 748 // being accurately able to detect loops. 749 bool ContainsIrreducibleLoops; 750 751 // All MemoryDefs that potentially could kill other MemDefs. 752 SmallVector<MemoryDef *, 64> MemDefs; 753 // Any that should be skipped as they are already deleted 754 SmallPtrSet<MemoryAccess *, 4> SkipStores; 755 // Keep track whether a given object is captured before return or not. 756 DenseMap<const Value *, bool> CapturedBeforeReturn; 757 // Keep track of all of the objects that are invisible to the caller after 758 // the function returns. 759 DenseMap<const Value *, bool> InvisibleToCallerAfterRet; 760 // Keep track of blocks with throwing instructions not modeled in MemorySSA. 761 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks; 762 // Post-order numbers for each basic block. Used to figure out if memory 763 // accesses are executed before another access. 764 DenseMap<BasicBlock *, unsigned> PostOrderNumbers; 765 766 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per 767 /// basic block. 768 MapVector<BasicBlock *, InstOverlapIntervalsTy> IOLs; 769 // Check if there are root nodes that are terminated by UnreachableInst. 770 // Those roots pessimize post-dominance queries. If there are such roots, 771 // fall back to CFG scan starting from all non-unreachable roots. 772 bool AnyUnreachableExit; 773 774 // Class contains self-reference, make sure it's not copied/moved. 775 DSEState(const DSEState &) = delete; 776 DSEState &operator=(const DSEState &) = delete; 777 778 DSEState(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, DominatorTree &DT, 779 PostDominatorTree &PDT, const TargetLibraryInfo &TLI, 780 const LoopInfo &LI) 781 : F(F), AA(AA), EI(DT, LI), BatchAA(AA, &EI), MSSA(MSSA), DT(DT), 782 PDT(PDT), TLI(TLI), DL(F.getParent()->getDataLayout()), LI(LI) { 783 // Collect blocks with throwing instructions not modeled in MemorySSA and 784 // alloc-like objects. 785 unsigned PO = 0; 786 for (BasicBlock *BB : post_order(&F)) { 787 PostOrderNumbers[BB] = PO++; 788 for (Instruction &I : *BB) { 789 MemoryAccess *MA = MSSA.getMemoryAccess(&I); 790 if (I.mayThrow() && !MA) 791 ThrowingBlocks.insert(I.getParent()); 792 793 auto *MD = dyn_cast_or_null<MemoryDef>(MA); 794 if (MD && MemDefs.size() < MemorySSADefsPerBlockLimit && 795 (getLocForWrite(&I) || isMemTerminatorInst(&I))) 796 MemDefs.push_back(MD); 797 } 798 } 799 800 // Treat byval or inalloca arguments the same as Allocas, stores to them are 801 // dead at the end of the function. 802 for (Argument &AI : F.args()) 803 if (AI.hasPassPointeeByValueCopyAttr()) 804 InvisibleToCallerAfterRet.insert({&AI, true}); 805 806 // Collect whether there is any irreducible control flow in the function. 807 ContainsIrreducibleLoops = mayContainIrreducibleControl(F, &LI); 808 809 AnyUnreachableExit = any_of(PDT.roots(), [](const BasicBlock *E) { 810 return isa<UnreachableInst>(E->getTerminator()); 811 }); 812 } 813 814 /// Return 'OW_Complete' if a store to the 'KillingLoc' location (by \p 815 /// KillingI instruction) completely overwrites a store to the 'DeadLoc' 816 /// location (by \p DeadI instruction). 817 /// Return OW_MaybePartial if \p KillingI does not completely overwrite 818 /// \p DeadI, but they both write to the same underlying object. In that 819 /// case, use isPartialOverwrite to check if \p KillingI partially overwrites 820 /// \p DeadI. Returns 'OR_None' if \p KillingI is known to not overwrite the 821 /// \p DeadI. Returns 'OW_Unknown' if nothing can be determined. 822 OverwriteResult isOverwrite(const Instruction *KillingI, 823 const Instruction *DeadI, 824 const MemoryLocation &KillingLoc, 825 const MemoryLocation &DeadLoc, 826 int64_t &KillingOff, int64_t &DeadOff) { 827 // AliasAnalysis does not always account for loops. Limit overwrite checks 828 // to dependencies for which we can guarantee they are independent of any 829 // loops they are in. 830 if (!isGuaranteedLoopIndependent(DeadI, KillingI, DeadLoc)) 831 return OW_Unknown; 832 833 const Value *DeadPtr = DeadLoc.Ptr->stripPointerCasts(); 834 const Value *KillingPtr = KillingLoc.Ptr->stripPointerCasts(); 835 const Value *DeadUndObj = getUnderlyingObject(DeadPtr); 836 const Value *KillingUndObj = getUnderlyingObject(KillingPtr); 837 838 // Check whether the killing store overwrites the whole object, in which 839 // case the size/offset of the dead store does not matter. 840 if (DeadUndObj == KillingUndObj && KillingLoc.Size.isPrecise()) { 841 uint64_t KillingUndObjSize = getPointerSize(KillingUndObj, DL, TLI, &F); 842 if (KillingUndObjSize != MemoryLocation::UnknownSize && 843 KillingUndObjSize == KillingLoc.Size.getValue()) 844 return OW_Complete; 845 } 846 847 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll 848 // get imprecise values here, though (except for unknown sizes). 849 if (!KillingLoc.Size.isPrecise() || !DeadLoc.Size.isPrecise()) { 850 // In case no constant size is known, try to an IR values for the number 851 // of bytes written and check if they match. 852 const auto *KillingMemI = dyn_cast<MemIntrinsic>(KillingI); 853 const auto *DeadMemI = dyn_cast<MemIntrinsic>(DeadI); 854 if (KillingMemI && DeadMemI) { 855 const Value *KillingV = KillingMemI->getLength(); 856 const Value *DeadV = DeadMemI->getLength(); 857 if (KillingV == DeadV && BatchAA.isMustAlias(DeadLoc, KillingLoc)) 858 return OW_Complete; 859 } 860 861 // Masked stores have imprecise locations, but we can reason about them 862 // to some extent. 863 return isMaskedStoreOverwrite(KillingI, DeadI, BatchAA); 864 } 865 866 const uint64_t KillingSize = KillingLoc.Size.getValue(); 867 const uint64_t DeadSize = DeadLoc.Size.getValue(); 868 869 // Query the alias information 870 AliasResult AAR = BatchAA.alias(KillingLoc, DeadLoc); 871 872 // If the start pointers are the same, we just have to compare sizes to see if 873 // the killing store was larger than the dead store. 874 if (AAR == AliasResult::MustAlias) { 875 // Make sure that the KillingSize size is >= the DeadSize size. 876 if (KillingSize >= DeadSize) 877 return OW_Complete; 878 } 879 880 // If we hit a partial alias we may have a full overwrite 881 if (AAR == AliasResult::PartialAlias && AAR.hasOffset()) { 882 int32_t Off = AAR.getOffset(); 883 if (Off >= 0 && (uint64_t)Off + DeadSize <= KillingSize) 884 return OW_Complete; 885 } 886 887 // If we can't resolve the same pointers to the same object, then we can't 888 // analyze them at all. 889 if (DeadUndObj != KillingUndObj) { 890 // Non aliasing stores to different objects don't overlap. Note that 891 // if the killing store is known to overwrite whole object (out of 892 // bounds access overwrites whole object as well) then it is assumed to 893 // completely overwrite any store to the same object even if they don't 894 // actually alias (see next check). 895 if (AAR == AliasResult::NoAlias) 896 return OW_None; 897 return OW_Unknown; 898 } 899 900 // Okay, we have stores to two completely different pointers. Try to 901 // decompose the pointer into a "base + constant_offset" form. If the base 902 // pointers are equal, then we can reason about the two stores. 903 DeadOff = 0; 904 KillingOff = 0; 905 const Value *DeadBasePtr = 906 GetPointerBaseWithConstantOffset(DeadPtr, DeadOff, DL); 907 const Value *KillingBasePtr = 908 GetPointerBaseWithConstantOffset(KillingPtr, KillingOff, DL); 909 910 // If the base pointers still differ, we have two completely different 911 // stores. 912 if (DeadBasePtr != KillingBasePtr) 913 return OW_Unknown; 914 915 // The killing access completely overlaps the dead store if and only if 916 // both start and end of the dead one is "inside" the killing one: 917 // |<->|--dead--|<->| 918 // |-----killing------| 919 // Accesses may overlap if and only if start of one of them is "inside" 920 // another one: 921 // |<->|--dead--|<-------->| 922 // |-------killing--------| 923 // OR 924 // |-------dead-------| 925 // |<->|---killing---|<----->| 926 // 927 // We have to be careful here as *Off is signed while *.Size is unsigned. 928 929 // Check if the dead access starts "not before" the killing one. 930 if (DeadOff >= KillingOff) { 931 // If the dead access ends "not after" the killing access then the 932 // dead one is completely overwritten by the killing one. 933 if (uint64_t(DeadOff - KillingOff) + DeadSize <= KillingSize) 934 return OW_Complete; 935 // If start of the dead access is "before" end of the killing access 936 // then accesses overlap. 937 else if ((uint64_t)(DeadOff - KillingOff) < KillingSize) 938 return OW_MaybePartial; 939 } 940 // If start of the killing access is "before" end of the dead access then 941 // accesses overlap. 942 else if ((uint64_t)(KillingOff - DeadOff) < DeadSize) { 943 return OW_MaybePartial; 944 } 945 946 // Can reach here only if accesses are known not to overlap. 947 return OW_None; 948 } 949 950 bool isInvisibleToCallerAfterRet(const Value *V) { 951 if (isa<AllocaInst>(V)) 952 return true; 953 auto I = InvisibleToCallerAfterRet.insert({V, false}); 954 if (I.second) { 955 if (!isInvisibleToCallerOnUnwind(V)) { 956 I.first->second = false; 957 } else if (isNoAliasCall(V)) { 958 I.first->second = !PointerMayBeCaptured(V, true, false); 959 } 960 } 961 return I.first->second; 962 } 963 964 bool isInvisibleToCallerOnUnwind(const Value *V) { 965 bool RequiresNoCaptureBeforeUnwind; 966 if (!isNotVisibleOnUnwind(V, RequiresNoCaptureBeforeUnwind)) 967 return false; 968 if (!RequiresNoCaptureBeforeUnwind) 969 return true; 970 971 auto I = CapturedBeforeReturn.insert({V, true}); 972 if (I.second) 973 // NOTE: This could be made more precise by PointerMayBeCapturedBefore 974 // with the killing MemoryDef. But we refrain from doing so for now to 975 // limit compile-time and this does not cause any changes to the number 976 // of stores removed on a large test set in practice. 977 I.first->second = PointerMayBeCaptured(V, false, true); 978 return !I.first->second; 979 } 980 981 Optional<MemoryLocation> getLocForWrite(Instruction *I) const { 982 if (!I->mayWriteToMemory()) 983 return None; 984 985 if (auto *CB = dyn_cast<CallBase>(I)) 986 return MemoryLocation::getForDest(CB, TLI); 987 988 return MemoryLocation::getOrNone(I); 989 } 990 991 /// Assuming this instruction has a dead analyzable write, can we delete 992 /// this instruction? 993 bool isRemovable(Instruction *I) { 994 assert(getLocForWrite(I) && "Must have analyzable write"); 995 996 // Don't remove volatile/atomic stores. 997 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 998 return SI->isUnordered(); 999 1000 if (auto *CB = dyn_cast<CallBase>(I)) { 1001 // Don't remove volatile memory intrinsics. 1002 if (auto *MI = dyn_cast<MemIntrinsic>(CB)) 1003 return !MI->isVolatile(); 1004 1005 // Never remove dead lifetime intrinsics, e.g. because they are followed 1006 // by a free. 1007 if (CB->isLifetimeStartOrEnd()) 1008 return false; 1009 1010 return CB->use_empty() && CB->willReturn() && CB->doesNotThrow(); 1011 } 1012 1013 return false; 1014 } 1015 1016 /// Returns true if \p UseInst completely overwrites \p DefLoc 1017 /// (stored by \p DefInst). 1018 bool isCompleteOverwrite(const MemoryLocation &DefLoc, Instruction *DefInst, 1019 Instruction *UseInst) { 1020 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a 1021 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a 1022 // MemoryDef. 1023 if (!UseInst->mayWriteToMemory()) 1024 return false; 1025 1026 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1027 if (CB->onlyAccessesInaccessibleMemory()) 1028 return false; 1029 1030 int64_t InstWriteOffset, DepWriteOffset; 1031 if (auto CC = getLocForWrite(UseInst)) 1032 return isOverwrite(UseInst, DefInst, *CC, DefLoc, InstWriteOffset, 1033 DepWriteOffset) == OW_Complete; 1034 return false; 1035 } 1036 1037 /// Returns true if \p Def is not read before returning from the function. 1038 bool isWriteAtEndOfFunction(MemoryDef *Def) { 1039 LLVM_DEBUG(dbgs() << " Check if def " << *Def << " (" 1040 << *Def->getMemoryInst() 1041 << ") is at the end the function \n"); 1042 1043 auto MaybeLoc = getLocForWrite(Def->getMemoryInst()); 1044 if (!MaybeLoc) { 1045 LLVM_DEBUG(dbgs() << " ... could not get location for write.\n"); 1046 return false; 1047 } 1048 1049 SmallVector<MemoryAccess *, 4> WorkList; 1050 SmallPtrSet<MemoryAccess *, 8> Visited; 1051 auto PushMemUses = [&WorkList, &Visited](MemoryAccess *Acc) { 1052 if (!Visited.insert(Acc).second) 1053 return; 1054 for (Use &U : Acc->uses()) 1055 WorkList.push_back(cast<MemoryAccess>(U.getUser())); 1056 }; 1057 PushMemUses(Def); 1058 for (unsigned I = 0; I < WorkList.size(); I++) { 1059 if (WorkList.size() >= MemorySSAScanLimit) { 1060 LLVM_DEBUG(dbgs() << " ... hit exploration limit.\n"); 1061 return false; 1062 } 1063 1064 MemoryAccess *UseAccess = WorkList[I]; 1065 // Simply adding the users of MemoryPhi to the worklist is not enough, 1066 // because we might miss read clobbers in different iterations of a loop, 1067 // for example. 1068 // TODO: Add support for phi translation to handle the loop case. 1069 if (isa<MemoryPhi>(UseAccess)) 1070 return false; 1071 1072 // TODO: Checking for aliasing is expensive. Consider reducing the amount 1073 // of times this is called and/or caching it. 1074 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1075 if (isReadClobber(*MaybeLoc, UseInst)) { 1076 LLVM_DEBUG(dbgs() << " ... hit read clobber " << *UseInst << ".\n"); 1077 return false; 1078 } 1079 1080 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) 1081 PushMemUses(UseDef); 1082 } 1083 return true; 1084 } 1085 1086 /// If \p I is a memory terminator like llvm.lifetime.end or free, return a 1087 /// pair with the MemoryLocation terminated by \p I and a boolean flag 1088 /// indicating whether \p I is a free-like call. 1089 Optional<std::pair<MemoryLocation, bool>> 1090 getLocForTerminator(Instruction *I) const { 1091 uint64_t Len; 1092 Value *Ptr; 1093 if (match(I, m_Intrinsic<Intrinsic::lifetime_end>(m_ConstantInt(Len), 1094 m_Value(Ptr)))) 1095 return {std::make_pair(MemoryLocation(Ptr, Len), false)}; 1096 1097 if (auto *CB = dyn_cast<CallBase>(I)) { 1098 if (isFreeCall(I, &TLI)) 1099 return {std::make_pair(MemoryLocation::getAfter(CB->getArgOperand(0)), 1100 true)}; 1101 } 1102 1103 return None; 1104 } 1105 1106 /// Returns true if \p I is a memory terminator instruction like 1107 /// llvm.lifetime.end or free. 1108 bool isMemTerminatorInst(Instruction *I) const { 1109 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1110 return (II && II->getIntrinsicID() == Intrinsic::lifetime_end) || 1111 isFreeCall(I, &TLI); 1112 } 1113 1114 /// Returns true if \p MaybeTerm is a memory terminator for \p Loc from 1115 /// instruction \p AccessI. 1116 bool isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI, 1117 Instruction *MaybeTerm) { 1118 Optional<std::pair<MemoryLocation, bool>> MaybeTermLoc = 1119 getLocForTerminator(MaybeTerm); 1120 1121 if (!MaybeTermLoc) 1122 return false; 1123 1124 // If the terminator is a free-like call, all accesses to the underlying 1125 // object can be considered terminated. 1126 if (getUnderlyingObject(Loc.Ptr) != 1127 getUnderlyingObject(MaybeTermLoc->first.Ptr)) 1128 return false; 1129 1130 auto TermLoc = MaybeTermLoc->first; 1131 if (MaybeTermLoc->second) { 1132 const Value *LocUO = getUnderlyingObject(Loc.Ptr); 1133 return BatchAA.isMustAlias(TermLoc.Ptr, LocUO); 1134 } 1135 int64_t InstWriteOffset = 0; 1136 int64_t DepWriteOffset = 0; 1137 return isOverwrite(MaybeTerm, AccessI, TermLoc, Loc, InstWriteOffset, 1138 DepWriteOffset) == OW_Complete; 1139 } 1140 1141 // Returns true if \p Use may read from \p DefLoc. 1142 bool isReadClobber(const MemoryLocation &DefLoc, Instruction *UseInst) { 1143 if (isNoopIntrinsic(UseInst)) 1144 return false; 1145 1146 // Monotonic or weaker atomic stores can be re-ordered and do not need to be 1147 // treated as read clobber. 1148 if (auto SI = dyn_cast<StoreInst>(UseInst)) 1149 return isStrongerThan(SI->getOrdering(), AtomicOrdering::Monotonic); 1150 1151 if (!UseInst->mayReadFromMemory()) 1152 return false; 1153 1154 if (auto *CB = dyn_cast<CallBase>(UseInst)) 1155 if (CB->onlyAccessesInaccessibleMemory()) 1156 return false; 1157 1158 return isRefSet(BatchAA.getModRefInfo(UseInst, DefLoc)); 1159 } 1160 1161 /// Returns true if a dependency between \p Current and \p KillingDef is 1162 /// guaranteed to be loop invariant for the loops that they are in. Either 1163 /// because they are known to be in the same block, in the same loop level or 1164 /// by guaranteeing that \p CurrentLoc only references a single MemoryLocation 1165 /// during execution of the containing function. 1166 bool isGuaranteedLoopIndependent(const Instruction *Current, 1167 const Instruction *KillingDef, 1168 const MemoryLocation &CurrentLoc) { 1169 // If the dependency is within the same block or loop level (being careful 1170 // of irreducible loops), we know that AA will return a valid result for the 1171 // memory dependency. (Both at the function level, outside of any loop, 1172 // would also be valid but we currently disable that to limit compile time). 1173 if (Current->getParent() == KillingDef->getParent()) 1174 return true; 1175 const Loop *CurrentLI = LI.getLoopFor(Current->getParent()); 1176 if (!ContainsIrreducibleLoops && CurrentLI && 1177 CurrentLI == LI.getLoopFor(KillingDef->getParent())) 1178 return true; 1179 // Otherwise check the memory location is invariant to any loops. 1180 return isGuaranteedLoopInvariant(CurrentLoc.Ptr); 1181 } 1182 1183 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible 1184 /// loop. In particular, this guarantees that it only references a single 1185 /// MemoryLocation during execution of the containing function. 1186 bool isGuaranteedLoopInvariant(const Value *Ptr) { 1187 Ptr = Ptr->stripPointerCasts(); 1188 if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) 1189 if (GEP->hasAllConstantIndices()) 1190 Ptr = GEP->getPointerOperand()->stripPointerCasts(); 1191 1192 if (auto *I = dyn_cast<Instruction>(Ptr)) 1193 return I->getParent()->isEntryBlock(); 1194 return true; 1195 } 1196 1197 // Find a MemoryDef writing to \p KillingLoc and dominating \p StartAccess, 1198 // with no read access between them or on any other path to a function exit 1199 // block if \p KillingLoc is not accessible after the function returns. If 1200 // there is no such MemoryDef, return None. The returned value may not 1201 // (completely) overwrite \p KillingLoc. Currently we bail out when we 1202 // encounter an aliasing MemoryUse (read). 1203 Optional<MemoryAccess *> 1204 getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess, 1205 const MemoryLocation &KillingLoc, const Value *KillingUndObj, 1206 unsigned &ScanLimit, unsigned &WalkerStepLimit, 1207 bool IsMemTerm, unsigned &PartialLimit) { 1208 if (ScanLimit == 0 || WalkerStepLimit == 0) { 1209 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1210 return None; 1211 } 1212 1213 MemoryAccess *Current = StartAccess; 1214 Instruction *KillingI = KillingDef->getMemoryInst(); 1215 LLVM_DEBUG(dbgs() << " trying to get dominating access\n"); 1216 1217 // Only optimize defining access of KillingDef when directly starting at its 1218 // defining access. The defining access also must only access KillingLoc. At 1219 // the moment we only support instructions with a single write location, so 1220 // it should be sufficient to disable optimizations for instructions that 1221 // also read from memory. 1222 bool CanOptimize = OptimizeMemorySSA && 1223 KillingDef->getDefiningAccess() == StartAccess && 1224 !KillingI->mayReadFromMemory(); 1225 1226 // Find the next clobbering Mod access for DefLoc, starting at StartAccess. 1227 Optional<MemoryLocation> CurrentLoc; 1228 for (;; Current = cast<MemoryDef>(Current)->getDefiningAccess()) { 1229 LLVM_DEBUG({ 1230 dbgs() << " visiting " << *Current; 1231 if (!MSSA.isLiveOnEntryDef(Current) && isa<MemoryUseOrDef>(Current)) 1232 dbgs() << " (" << *cast<MemoryUseOrDef>(Current)->getMemoryInst() 1233 << ")"; 1234 dbgs() << "\n"; 1235 }); 1236 1237 // Reached TOP. 1238 if (MSSA.isLiveOnEntryDef(Current)) { 1239 LLVM_DEBUG(dbgs() << " ... found LiveOnEntryDef\n"); 1240 if (CanOptimize && Current != KillingDef->getDefiningAccess()) 1241 // The first clobbering def is... none. 1242 KillingDef->setOptimized(Current); 1243 return None; 1244 } 1245 1246 // Cost of a step. Accesses in the same block are more likely to be valid 1247 // candidates for elimination, hence consider them cheaper. 1248 unsigned StepCost = KillingDef->getBlock() == Current->getBlock() 1249 ? MemorySSASameBBStepCost 1250 : MemorySSAOtherBBStepCost; 1251 if (WalkerStepLimit <= StepCost) { 1252 LLVM_DEBUG(dbgs() << " ... hit walker step limit\n"); 1253 return None; 1254 } 1255 WalkerStepLimit -= StepCost; 1256 1257 // Return for MemoryPhis. They cannot be eliminated directly and the 1258 // caller is responsible for traversing them. 1259 if (isa<MemoryPhi>(Current)) { 1260 LLVM_DEBUG(dbgs() << " ... found MemoryPhi\n"); 1261 return Current; 1262 } 1263 1264 // Below, check if CurrentDef is a valid candidate to be eliminated by 1265 // KillingDef. If it is not, check the next candidate. 1266 MemoryDef *CurrentDef = cast<MemoryDef>(Current); 1267 Instruction *CurrentI = CurrentDef->getMemoryInst(); 1268 1269 if (canSkipDef(CurrentDef, !isInvisibleToCallerOnUnwind(KillingUndObj))) { 1270 CanOptimize = false; 1271 continue; 1272 } 1273 1274 // Before we try to remove anything, check for any extra throwing 1275 // instructions that block us from DSEing 1276 if (mayThrowBetween(KillingI, CurrentI, KillingUndObj)) { 1277 LLVM_DEBUG(dbgs() << " ... skip, may throw!\n"); 1278 return None; 1279 } 1280 1281 // Check for anything that looks like it will be a barrier to further 1282 // removal 1283 if (isDSEBarrier(KillingUndObj, CurrentI)) { 1284 LLVM_DEBUG(dbgs() << " ... skip, barrier\n"); 1285 return None; 1286 } 1287 1288 // If Current is known to be on path that reads DefLoc or is a read 1289 // clobber, bail out, as the path is not profitable. We skip this check 1290 // for intrinsic calls, because the code knows how to handle memcpy 1291 // intrinsics. 1292 if (!isa<IntrinsicInst>(CurrentI) && isReadClobber(KillingLoc, CurrentI)) 1293 return None; 1294 1295 // Quick check if there are direct uses that are read-clobbers. 1296 if (any_of(Current->uses(), [this, &KillingLoc, StartAccess](Use &U) { 1297 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U.getUser())) 1298 return !MSSA.dominates(StartAccess, UseOrDef) && 1299 isReadClobber(KillingLoc, UseOrDef->getMemoryInst()); 1300 return false; 1301 })) { 1302 LLVM_DEBUG(dbgs() << " ... found a read clobber\n"); 1303 return None; 1304 } 1305 1306 // If Current does not have an analyzable write location or is not 1307 // removable, skip it. 1308 CurrentLoc = getLocForWrite(CurrentI); 1309 if (!CurrentLoc || !isRemovable(CurrentI)) { 1310 CanOptimize = false; 1311 continue; 1312 } 1313 1314 // AliasAnalysis does not account for loops. Limit elimination to 1315 // candidates for which we can guarantee they always store to the same 1316 // memory location and not located in different loops. 1317 if (!isGuaranteedLoopIndependent(CurrentI, KillingI, *CurrentLoc)) { 1318 LLVM_DEBUG(dbgs() << " ... not guaranteed loop independent\n"); 1319 CanOptimize = false; 1320 continue; 1321 } 1322 1323 if (IsMemTerm) { 1324 // If the killing def is a memory terminator (e.g. lifetime.end), check 1325 // the next candidate if the current Current does not write the same 1326 // underlying object as the terminator. 1327 if (!isMemTerminator(*CurrentLoc, CurrentI, KillingI)) { 1328 CanOptimize = false; 1329 continue; 1330 } 1331 } else { 1332 int64_t KillingOffset = 0; 1333 int64_t DeadOffset = 0; 1334 auto OR = isOverwrite(KillingI, CurrentI, KillingLoc, *CurrentLoc, 1335 KillingOffset, DeadOffset); 1336 if (CanOptimize) { 1337 // CurrentDef is the earliest write clobber of KillingDef. Use it as 1338 // optimized access. Do not optimize if CurrentDef is already the 1339 // defining access of KillingDef. 1340 if (CurrentDef != KillingDef->getDefiningAccess() && 1341 (OR == OW_Complete || OR == OW_MaybePartial)) 1342 KillingDef->setOptimized(CurrentDef); 1343 1344 // Once a may-aliasing def is encountered do not set an optimized 1345 // access. 1346 if (OR != OW_None) 1347 CanOptimize = false; 1348 } 1349 1350 // If Current does not write to the same object as KillingDef, check 1351 // the next candidate. 1352 if (OR == OW_Unknown || OR == OW_None) 1353 continue; 1354 else if (OR == OW_MaybePartial) { 1355 // If KillingDef only partially overwrites Current, check the next 1356 // candidate if the partial step limit is exceeded. This aggressively 1357 // limits the number of candidates for partial store elimination, 1358 // which are less likely to be removable in the end. 1359 if (PartialLimit <= 1) { 1360 WalkerStepLimit -= 1; 1361 LLVM_DEBUG(dbgs() << " ... reached partial limit ... continue with next access\n"); 1362 continue; 1363 } 1364 PartialLimit -= 1; 1365 } 1366 } 1367 break; 1368 }; 1369 1370 // Accesses to objects accessible after the function returns can only be 1371 // eliminated if the access is dead along all paths to the exit. Collect 1372 // the blocks with killing (=completely overwriting MemoryDefs) and check if 1373 // they cover all paths from MaybeDeadAccess to any function exit. 1374 SmallPtrSet<Instruction *, 16> KillingDefs; 1375 KillingDefs.insert(KillingDef->getMemoryInst()); 1376 MemoryAccess *MaybeDeadAccess = Current; 1377 MemoryLocation MaybeDeadLoc = *CurrentLoc; 1378 Instruction *MaybeDeadI = cast<MemoryDef>(MaybeDeadAccess)->getMemoryInst(); 1379 LLVM_DEBUG(dbgs() << " Checking for reads of " << *MaybeDeadAccess << " (" 1380 << *MaybeDeadI << ")\n"); 1381 1382 SmallSetVector<MemoryAccess *, 32> WorkList; 1383 auto PushMemUses = [&WorkList](MemoryAccess *Acc) { 1384 for (Use &U : Acc->uses()) 1385 WorkList.insert(cast<MemoryAccess>(U.getUser())); 1386 }; 1387 PushMemUses(MaybeDeadAccess); 1388 1389 // Check if DeadDef may be read. 1390 for (unsigned I = 0; I < WorkList.size(); I++) { 1391 MemoryAccess *UseAccess = WorkList[I]; 1392 1393 LLVM_DEBUG(dbgs() << " " << *UseAccess); 1394 // Bail out if the number of accesses to check exceeds the scan limit. 1395 if (ScanLimit < (WorkList.size() - I)) { 1396 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n"); 1397 return None; 1398 } 1399 --ScanLimit; 1400 NumDomMemDefChecks++; 1401 1402 if (isa<MemoryPhi>(UseAccess)) { 1403 if (any_of(KillingDefs, [this, UseAccess](Instruction *KI) { 1404 return DT.properlyDominates(KI->getParent(), 1405 UseAccess->getBlock()); 1406 })) { 1407 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n"); 1408 continue; 1409 } 1410 LLVM_DEBUG(dbgs() << "\n ... adding PHI uses\n"); 1411 PushMemUses(UseAccess); 1412 continue; 1413 } 1414 1415 Instruction *UseInst = cast<MemoryUseOrDef>(UseAccess)->getMemoryInst(); 1416 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n"); 1417 1418 if (any_of(KillingDefs, [this, UseInst](Instruction *KI) { 1419 return DT.dominates(KI, UseInst); 1420 })) { 1421 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n"); 1422 continue; 1423 } 1424 1425 // A memory terminator kills all preceeding MemoryDefs and all succeeding 1426 // MemoryAccesses. We do not have to check it's users. 1427 if (isMemTerminator(MaybeDeadLoc, MaybeDeadI, UseInst)) { 1428 LLVM_DEBUG( 1429 dbgs() 1430 << " ... skipping, memterminator invalidates following accesses\n"); 1431 continue; 1432 } 1433 1434 if (isNoopIntrinsic(cast<MemoryUseOrDef>(UseAccess)->getMemoryInst())) { 1435 LLVM_DEBUG(dbgs() << " ... adding uses of intrinsic\n"); 1436 PushMemUses(UseAccess); 1437 continue; 1438 } 1439 1440 if (UseInst->mayThrow() && !isInvisibleToCallerOnUnwind(KillingUndObj)) { 1441 LLVM_DEBUG(dbgs() << " ... found throwing instruction\n"); 1442 return None; 1443 } 1444 1445 // Uses which may read the original MemoryDef mean we cannot eliminate the 1446 // original MD. Stop walk. 1447 if (isReadClobber(MaybeDeadLoc, UseInst)) { 1448 LLVM_DEBUG(dbgs() << " ... found read clobber\n"); 1449 return None; 1450 } 1451 1452 // If this worklist walks back to the original memory access (and the 1453 // pointer is not guarenteed loop invariant) then we cannot assume that a 1454 // store kills itself. 1455 if (MaybeDeadAccess == UseAccess && 1456 !isGuaranteedLoopInvariant(MaybeDeadLoc.Ptr)) { 1457 LLVM_DEBUG(dbgs() << " ... found not loop invariant self access\n"); 1458 return None; 1459 } 1460 // Otherwise, for the KillingDef and MaybeDeadAccess we only have to check 1461 // if it reads the memory location. 1462 // TODO: It would probably be better to check for self-reads before 1463 // calling the function. 1464 if (KillingDef == UseAccess || MaybeDeadAccess == UseAccess) { 1465 LLVM_DEBUG(dbgs() << " ... skipping killing def/dom access\n"); 1466 continue; 1467 } 1468 1469 // Check all uses for MemoryDefs, except for defs completely overwriting 1470 // the original location. Otherwise we have to check uses of *all* 1471 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might 1472 // miss cases like the following 1473 // 1 = Def(LoE) ; <----- DeadDef stores [0,1] 1474 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3] 1475 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3]. 1476 // (The Use points to the *first* Def it may alias) 1477 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias, 1478 // stores [0,1] 1479 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(UseAccess)) { 1480 if (isCompleteOverwrite(MaybeDeadLoc, MaybeDeadI, UseInst)) { 1481 BasicBlock *MaybeKillingBlock = UseInst->getParent(); 1482 if (PostOrderNumbers.find(MaybeKillingBlock)->second < 1483 PostOrderNumbers.find(MaybeDeadAccess->getBlock())->second) { 1484 if (!isInvisibleToCallerAfterRet(KillingUndObj)) { 1485 LLVM_DEBUG(dbgs() 1486 << " ... found killing def " << *UseInst << "\n"); 1487 KillingDefs.insert(UseInst); 1488 } 1489 } else { 1490 LLVM_DEBUG(dbgs() 1491 << " ... found preceeding def " << *UseInst << "\n"); 1492 return None; 1493 } 1494 } else 1495 PushMemUses(UseDef); 1496 } 1497 } 1498 1499 // For accesses to locations visible after the function returns, make sure 1500 // that the location is dead (=overwritten) along all paths from 1501 // MaybeDeadAccess to the exit. 1502 if (!isInvisibleToCallerAfterRet(KillingUndObj)) { 1503 SmallPtrSet<BasicBlock *, 16> KillingBlocks; 1504 for (Instruction *KD : KillingDefs) 1505 KillingBlocks.insert(KD->getParent()); 1506 assert(!KillingBlocks.empty() && 1507 "Expected at least a single killing block"); 1508 1509 // Find the common post-dominator of all killing blocks. 1510 BasicBlock *CommonPred = *KillingBlocks.begin(); 1511 for (BasicBlock *BB : llvm::drop_begin(KillingBlocks)) { 1512 if (!CommonPred) 1513 break; 1514 CommonPred = PDT.findNearestCommonDominator(CommonPred, BB); 1515 } 1516 1517 // If the common post-dominator does not post-dominate MaybeDeadAccess, 1518 // there is a path from MaybeDeadAccess to an exit not going through a 1519 // killing block. 1520 if (!PDT.dominates(CommonPred, MaybeDeadAccess->getBlock())) { 1521 if (!AnyUnreachableExit) 1522 return None; 1523 1524 // Fall back to CFG scan starting at all non-unreachable roots if not 1525 // all paths to the exit go through CommonPred. 1526 CommonPred = nullptr; 1527 } 1528 1529 // If CommonPred itself is in the set of killing blocks, we're done. 1530 if (KillingBlocks.count(CommonPred)) 1531 return {MaybeDeadAccess}; 1532 1533 SetVector<BasicBlock *> WorkList; 1534 // If CommonPred is null, there are multiple exits from the function. 1535 // They all have to be added to the worklist. 1536 if (CommonPred) 1537 WorkList.insert(CommonPred); 1538 else 1539 for (BasicBlock *R : PDT.roots()) { 1540 if (!isa<UnreachableInst>(R->getTerminator())) 1541 WorkList.insert(R); 1542 } 1543 1544 NumCFGTries++; 1545 // Check if all paths starting from an exit node go through one of the 1546 // killing blocks before reaching MaybeDeadAccess. 1547 for (unsigned I = 0; I < WorkList.size(); I++) { 1548 NumCFGChecks++; 1549 BasicBlock *Current = WorkList[I]; 1550 if (KillingBlocks.count(Current)) 1551 continue; 1552 if (Current == MaybeDeadAccess->getBlock()) 1553 return None; 1554 1555 // MaybeDeadAccess is reachable from the entry, so we don't have to 1556 // explore unreachable blocks further. 1557 if (!DT.isReachableFromEntry(Current)) 1558 continue; 1559 1560 for (BasicBlock *Pred : predecessors(Current)) 1561 WorkList.insert(Pred); 1562 1563 if (WorkList.size() >= MemorySSAPathCheckLimit) 1564 return None; 1565 } 1566 NumCFGSuccess++; 1567 } 1568 1569 // No aliasing MemoryUses of MaybeDeadAccess found, MaybeDeadAccess is 1570 // potentially dead. 1571 return {MaybeDeadAccess}; 1572 } 1573 1574 // Delete dead memory defs 1575 void deleteDeadInstruction(Instruction *SI) { 1576 MemorySSAUpdater Updater(&MSSA); 1577 SmallVector<Instruction *, 32> NowDeadInsts; 1578 NowDeadInsts.push_back(SI); 1579 --NumFastOther; 1580 1581 while (!NowDeadInsts.empty()) { 1582 Instruction *DeadInst = NowDeadInsts.pop_back_val(); 1583 ++NumFastOther; 1584 1585 // Try to preserve debug information attached to the dead instruction. 1586 salvageDebugInfo(*DeadInst); 1587 salvageKnowledge(DeadInst); 1588 1589 // Remove the Instruction from MSSA. 1590 if (MemoryAccess *MA = MSSA.getMemoryAccess(DeadInst)) { 1591 if (MemoryDef *MD = dyn_cast<MemoryDef>(MA)) { 1592 SkipStores.insert(MD); 1593 } 1594 1595 Updater.removeMemoryAccess(MA); 1596 } 1597 1598 auto I = IOLs.find(DeadInst->getParent()); 1599 if (I != IOLs.end()) 1600 I->second.erase(DeadInst); 1601 // Remove its operands 1602 for (Use &O : DeadInst->operands()) 1603 if (Instruction *OpI = dyn_cast<Instruction>(O)) { 1604 O = nullptr; 1605 if (isInstructionTriviallyDead(OpI, &TLI)) 1606 NowDeadInsts.push_back(OpI); 1607 } 1608 1609 EI.removeInstruction(DeadInst); 1610 DeadInst->eraseFromParent(); 1611 } 1612 } 1613 1614 // Check for any extra throws between \p KillingI and \p DeadI that block 1615 // DSE. This only checks extra maythrows (those that aren't MemoryDef's). 1616 // MemoryDef that may throw are handled during the walk from one def to the 1617 // next. 1618 bool mayThrowBetween(Instruction *KillingI, Instruction *DeadI, 1619 const Value *KillingUndObj) { 1620 // First see if we can ignore it by using the fact that KillingI is an 1621 // alloca/alloca like object that is not visible to the caller during 1622 // execution of the function. 1623 if (KillingUndObj && isInvisibleToCallerOnUnwind(KillingUndObj)) 1624 return false; 1625 1626 if (KillingI->getParent() == DeadI->getParent()) 1627 return ThrowingBlocks.count(KillingI->getParent()); 1628 return !ThrowingBlocks.empty(); 1629 } 1630 1631 // Check if \p DeadI acts as a DSE barrier for \p KillingI. The following 1632 // instructions act as barriers: 1633 // * A memory instruction that may throw and \p KillingI accesses a non-stack 1634 // object. 1635 // * Atomic stores stronger that monotonic. 1636 bool isDSEBarrier(const Value *KillingUndObj, Instruction *DeadI) { 1637 // If DeadI may throw it acts as a barrier, unless we are to an 1638 // alloca/alloca like object that does not escape. 1639 if (DeadI->mayThrow() && !isInvisibleToCallerOnUnwind(KillingUndObj)) 1640 return true; 1641 1642 // If DeadI is an atomic load/store stronger than monotonic, do not try to 1643 // eliminate/reorder it. 1644 if (DeadI->isAtomic()) { 1645 if (auto *LI = dyn_cast<LoadInst>(DeadI)) 1646 return isStrongerThanMonotonic(LI->getOrdering()); 1647 if (auto *SI = dyn_cast<StoreInst>(DeadI)) 1648 return isStrongerThanMonotonic(SI->getOrdering()); 1649 if (auto *ARMW = dyn_cast<AtomicRMWInst>(DeadI)) 1650 return isStrongerThanMonotonic(ARMW->getOrdering()); 1651 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(DeadI)) 1652 return isStrongerThanMonotonic(CmpXchg->getSuccessOrdering()) || 1653 isStrongerThanMonotonic(CmpXchg->getFailureOrdering()); 1654 llvm_unreachable("other instructions should be skipped in MemorySSA"); 1655 } 1656 return false; 1657 } 1658 1659 /// Eliminate writes to objects that are not visible in the caller and are not 1660 /// accessed before returning from the function. 1661 bool eliminateDeadWritesAtEndOfFunction() { 1662 bool MadeChange = false; 1663 LLVM_DEBUG( 1664 dbgs() 1665 << "Trying to eliminate MemoryDefs at the end of the function\n"); 1666 for (MemoryDef *Def : llvm::reverse(MemDefs)) { 1667 if (SkipStores.contains(Def)) 1668 continue; 1669 1670 Instruction *DefI = Def->getMemoryInst(); 1671 auto DefLoc = getLocForWrite(DefI); 1672 if (!DefLoc || !isRemovable(DefI)) 1673 continue; 1674 1675 // NOTE: Currently eliminating writes at the end of a function is limited 1676 // to MemoryDefs with a single underlying object, to save compile-time. In 1677 // practice it appears the case with multiple underlying objects is very 1678 // uncommon. If it turns out to be important, we can use 1679 // getUnderlyingObjects here instead. 1680 const Value *UO = getUnderlyingObject(DefLoc->Ptr); 1681 if (!isInvisibleToCallerAfterRet(UO)) 1682 continue; 1683 1684 if (isWriteAtEndOfFunction(Def)) { 1685 // See through pointer-to-pointer bitcasts 1686 LLVM_DEBUG(dbgs() << " ... MemoryDef is not accessed until the end " 1687 "of the function\n"); 1688 deleteDeadInstruction(DefI); 1689 ++NumFastStores; 1690 MadeChange = true; 1691 } 1692 } 1693 return MadeChange; 1694 } 1695 1696 /// If we have a zero initializing memset following a call to malloc, 1697 /// try folding it into a call to calloc. 1698 bool tryFoldIntoCalloc(MemoryDef *Def, const Value *DefUO) { 1699 Instruction *DefI = Def->getMemoryInst(); 1700 MemSetInst *MemSet = dyn_cast<MemSetInst>(DefI); 1701 if (!MemSet) 1702 // TODO: Could handle zero store to small allocation as well. 1703 return false; 1704 Constant *StoredConstant = dyn_cast<Constant>(MemSet->getValue()); 1705 if (!StoredConstant || !StoredConstant->isNullValue()) 1706 return false; 1707 1708 if (!isRemovable(DefI)) 1709 // The memset might be volatile.. 1710 return false; 1711 1712 if (F.hasFnAttribute(Attribute::SanitizeMemory) || 1713 F.hasFnAttribute(Attribute::SanitizeAddress) || 1714 F.hasFnAttribute(Attribute::SanitizeHWAddress) || 1715 F.getName() == "calloc") 1716 return false; 1717 auto *Malloc = const_cast<CallInst *>(dyn_cast<CallInst>(DefUO)); 1718 if (!Malloc) 1719 return false; 1720 auto *InnerCallee = Malloc->getCalledFunction(); 1721 if (!InnerCallee) 1722 return false; 1723 LibFunc Func; 1724 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) || 1725 Func != LibFunc_malloc) 1726 return false; 1727 1728 auto shouldCreateCalloc = [](CallInst *Malloc, CallInst *Memset) { 1729 // Check for br(icmp ptr, null), truebb, falsebb) pattern at the end 1730 // of malloc block 1731 auto *MallocBB = Malloc->getParent(), 1732 *MemsetBB = Memset->getParent(); 1733 if (MallocBB == MemsetBB) 1734 return true; 1735 auto *Ptr = Memset->getArgOperand(0); 1736 auto *TI = MallocBB->getTerminator(); 1737 ICmpInst::Predicate Pred; 1738 BasicBlock *TrueBB, *FalseBB; 1739 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Ptr), m_Zero()), TrueBB, 1740 FalseBB))) 1741 return false; 1742 if (Pred != ICmpInst::ICMP_EQ || MemsetBB != FalseBB) 1743 return false; 1744 return true; 1745 }; 1746 1747 if (Malloc->getOperand(0) != MemSet->getLength()) 1748 return false; 1749 if (!shouldCreateCalloc(Malloc, MemSet) || 1750 !DT.dominates(Malloc, MemSet) || 1751 !memoryIsNotModifiedBetween(Malloc, MemSet, BatchAA, DL, &DT)) 1752 return false; 1753 IRBuilder<> IRB(Malloc); 1754 const auto &DL = Malloc->getModule()->getDataLayout(); 1755 auto *Calloc = 1756 emitCalloc(ConstantInt::get(IRB.getIntPtrTy(DL), 1), 1757 Malloc->getArgOperand(0), IRB, TLI); 1758 if (!Calloc) 1759 return false; 1760 MemorySSAUpdater Updater(&MSSA); 1761 auto *LastDef = 1762 cast<MemoryDef>(Updater.getMemorySSA()->getMemoryAccess(Malloc)); 1763 auto *NewAccess = 1764 Updater.createMemoryAccessAfter(cast<Instruction>(Calloc), LastDef, 1765 LastDef); 1766 auto *NewAccessMD = cast<MemoryDef>(NewAccess); 1767 Updater.insertDef(NewAccessMD, /*RenameUses=*/true); 1768 Updater.removeMemoryAccess(Malloc); 1769 Malloc->replaceAllUsesWith(Calloc); 1770 Malloc->eraseFromParent(); 1771 return true; 1772 } 1773 1774 /// \returns true if \p Def is a no-op store, either because it 1775 /// directly stores back a loaded value or stores zero to a calloced object. 1776 bool storeIsNoop(MemoryDef *Def, const Value *DefUO) { 1777 Instruction *DefI = Def->getMemoryInst(); 1778 StoreInst *Store = dyn_cast<StoreInst>(DefI); 1779 MemSetInst *MemSet = dyn_cast<MemSetInst>(DefI); 1780 Constant *StoredConstant = nullptr; 1781 if (Store) 1782 StoredConstant = dyn_cast<Constant>(Store->getOperand(0)); 1783 else if (MemSet) 1784 StoredConstant = dyn_cast<Constant>(MemSet->getValue()); 1785 else 1786 return false; 1787 1788 if (!isRemovable(DefI)) 1789 return false; 1790 1791 if (StoredConstant && isAllocationFn(DefUO, &TLI)) { 1792 auto *CB = cast<CallBase>(DefUO); 1793 auto *InitC = getInitialValueOfAllocation(CB, &TLI, 1794 StoredConstant->getType()); 1795 // If the clobbering access is LiveOnEntry, no instructions between them 1796 // can modify the memory location. 1797 if (InitC && InitC == StoredConstant) 1798 return MSSA.isLiveOnEntryDef( 1799 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def)); 1800 } 1801 1802 if (!Store) 1803 return false; 1804 1805 if (auto *LoadI = dyn_cast<LoadInst>(Store->getOperand(0))) { 1806 if (LoadI->getPointerOperand() == Store->getOperand(1)) { 1807 // Get the defining access for the load. 1808 auto *LoadAccess = MSSA.getMemoryAccess(LoadI)->getDefiningAccess(); 1809 // Fast path: the defining accesses are the same. 1810 if (LoadAccess == Def->getDefiningAccess()) 1811 return true; 1812 1813 // Look through phi accesses. Recursively scan all phi accesses by 1814 // adding them to a worklist. Bail when we run into a memory def that 1815 // does not match LoadAccess. 1816 SetVector<MemoryAccess *> ToCheck; 1817 MemoryAccess *Current = 1818 MSSA.getWalker()->getClobberingMemoryAccess(Def); 1819 // We don't want to bail when we run into the store memory def. But, 1820 // the phi access may point to it. So, pretend like we've already 1821 // checked it. 1822 ToCheck.insert(Def); 1823 ToCheck.insert(Current); 1824 // Start at current (1) to simulate already having checked Def. 1825 for (unsigned I = 1; I < ToCheck.size(); ++I) { 1826 Current = ToCheck[I]; 1827 if (auto PhiAccess = dyn_cast<MemoryPhi>(Current)) { 1828 // Check all the operands. 1829 for (auto &Use : PhiAccess->incoming_values()) 1830 ToCheck.insert(cast<MemoryAccess>(&Use)); 1831 continue; 1832 } 1833 1834 // If we found a memory def, bail. This happens when we have an 1835 // unrelated write in between an otherwise noop store. 1836 assert(isa<MemoryDef>(Current) && 1837 "Only MemoryDefs should reach here."); 1838 // TODO: Skip no alias MemoryDefs that have no aliasing reads. 1839 // We are searching for the definition of the store's destination. 1840 // So, if that is the same definition as the load, then this is a 1841 // noop. Otherwise, fail. 1842 if (LoadAccess != Current) 1843 return false; 1844 } 1845 return true; 1846 } 1847 } 1848 1849 return false; 1850 } 1851 1852 bool removePartiallyOverlappedStores(InstOverlapIntervalsTy &IOL) { 1853 bool Changed = false; 1854 for (auto OI : IOL) { 1855 Instruction *DeadI = OI.first; 1856 MemoryLocation Loc = *getLocForWrite(DeadI); 1857 assert(isRemovable(DeadI) && "Expect only removable instruction"); 1858 1859 const Value *Ptr = Loc.Ptr->stripPointerCasts(); 1860 int64_t DeadStart = 0; 1861 uint64_t DeadSize = Loc.Size.getValue(); 1862 GetPointerBaseWithConstantOffset(Ptr, DeadStart, DL); 1863 OverlapIntervalsTy &IntervalMap = OI.second; 1864 Changed |= tryToShortenEnd(DeadI, IntervalMap, DeadStart, DeadSize); 1865 if (IntervalMap.empty()) 1866 continue; 1867 Changed |= tryToShortenBegin(DeadI, IntervalMap, DeadStart, DeadSize); 1868 } 1869 return Changed; 1870 } 1871 1872 /// Eliminates writes to locations where the value that is being written 1873 /// is already stored at the same location. 1874 bool eliminateRedundantStoresOfExistingValues() { 1875 bool MadeChange = false; 1876 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs that write the " 1877 "already existing value\n"); 1878 for (auto *Def : MemDefs) { 1879 if (SkipStores.contains(Def) || MSSA.isLiveOnEntryDef(Def)) 1880 continue; 1881 1882 Instruction *DefInst = Def->getMemoryInst(); 1883 auto MaybeDefLoc = getLocForWrite(DefInst); 1884 if (!MaybeDefLoc || !isRemovable(DefInst)) 1885 continue; 1886 1887 MemoryDef *UpperDef; 1888 // To conserve compile-time, we avoid walking to the next clobbering def. 1889 // Instead, we just try to get the optimized access, if it exists. DSE 1890 // will try to optimize defs during the earlier traversal. 1891 if (Def->isOptimized()) 1892 UpperDef = dyn_cast<MemoryDef>(Def->getOptimized()); 1893 else 1894 UpperDef = dyn_cast<MemoryDef>(Def->getDefiningAccess()); 1895 if (!UpperDef || MSSA.isLiveOnEntryDef(UpperDef)) 1896 continue; 1897 1898 Instruction *UpperInst = UpperDef->getMemoryInst(); 1899 auto IsRedundantStore = [&]() { 1900 if (DefInst->isIdenticalTo(UpperInst)) 1901 return true; 1902 if (auto *MemSetI = dyn_cast<MemSetInst>(UpperInst)) { 1903 if (auto *SI = dyn_cast<StoreInst>(DefInst)) { 1904 // MemSetInst must have a write location. 1905 MemoryLocation UpperLoc = *getLocForWrite(UpperInst); 1906 int64_t InstWriteOffset = 0; 1907 int64_t DepWriteOffset = 0; 1908 auto OR = isOverwrite(UpperInst, DefInst, UpperLoc, *MaybeDefLoc, 1909 InstWriteOffset, DepWriteOffset); 1910 Value *StoredByte = isBytewiseValue(SI->getValueOperand(), DL); 1911 return StoredByte && StoredByte == MemSetI->getOperand(1) && 1912 OR == OW_Complete; 1913 } 1914 } 1915 return false; 1916 }; 1917 1918 if (!IsRedundantStore() || isReadClobber(*MaybeDefLoc, DefInst)) 1919 continue; 1920 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *DefInst 1921 << '\n'); 1922 deleteDeadInstruction(DefInst); 1923 NumRedundantStores++; 1924 MadeChange = true; 1925 } 1926 return MadeChange; 1927 } 1928 }; 1929 1930 static bool eliminateDeadStores(Function &F, AliasAnalysis &AA, MemorySSA &MSSA, 1931 DominatorTree &DT, PostDominatorTree &PDT, 1932 const TargetLibraryInfo &TLI, 1933 const LoopInfo &LI) { 1934 bool MadeChange = false; 1935 1936 DSEState State(F, AA, MSSA, DT, PDT, TLI, LI); 1937 // For each store: 1938 for (unsigned I = 0; I < State.MemDefs.size(); I++) { 1939 MemoryDef *KillingDef = State.MemDefs[I]; 1940 if (State.SkipStores.count(KillingDef)) 1941 continue; 1942 Instruction *KillingI = KillingDef->getMemoryInst(); 1943 1944 Optional<MemoryLocation> MaybeKillingLoc; 1945 if (State.isMemTerminatorInst(KillingI)) 1946 MaybeKillingLoc = State.getLocForTerminator(KillingI).map( 1947 [](const std::pair<MemoryLocation, bool> &P) { return P.first; }); 1948 else 1949 MaybeKillingLoc = State.getLocForWrite(KillingI); 1950 1951 if (!MaybeKillingLoc) { 1952 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for " 1953 << *KillingI << "\n"); 1954 continue; 1955 } 1956 MemoryLocation KillingLoc = *MaybeKillingLoc; 1957 assert(KillingLoc.Ptr && "KillingLoc should not be null"); 1958 const Value *KillingUndObj = getUnderlyingObject(KillingLoc.Ptr); 1959 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by " 1960 << *KillingDef << " (" << *KillingI << ")\n"); 1961 1962 unsigned ScanLimit = MemorySSAScanLimit; 1963 unsigned WalkerStepLimit = MemorySSAUpwardsStepLimit; 1964 unsigned PartialLimit = MemorySSAPartialStoreLimit; 1965 // Worklist of MemoryAccesses that may be killed by KillingDef. 1966 SetVector<MemoryAccess *> ToCheck; 1967 ToCheck.insert(KillingDef->getDefiningAccess()); 1968 1969 bool Shortend = false; 1970 bool IsMemTerm = State.isMemTerminatorInst(KillingI); 1971 // Check if MemoryAccesses in the worklist are killed by KillingDef. 1972 for (unsigned I = 0; I < ToCheck.size(); I++) { 1973 MemoryAccess *Current = ToCheck[I]; 1974 if (State.SkipStores.count(Current)) 1975 continue; 1976 1977 Optional<MemoryAccess *> MaybeDeadAccess = State.getDomMemoryDef( 1978 KillingDef, Current, KillingLoc, KillingUndObj, ScanLimit, 1979 WalkerStepLimit, IsMemTerm, PartialLimit); 1980 1981 if (!MaybeDeadAccess) { 1982 LLVM_DEBUG(dbgs() << " finished walk\n"); 1983 continue; 1984 } 1985 1986 MemoryAccess *DeadAccess = *MaybeDeadAccess; 1987 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DeadAccess); 1988 if (isa<MemoryPhi>(DeadAccess)) { 1989 LLVM_DEBUG(dbgs() << "\n ... adding incoming values to worklist\n"); 1990 for (Value *V : cast<MemoryPhi>(DeadAccess)->incoming_values()) { 1991 MemoryAccess *IncomingAccess = cast<MemoryAccess>(V); 1992 BasicBlock *IncomingBlock = IncomingAccess->getBlock(); 1993 BasicBlock *PhiBlock = DeadAccess->getBlock(); 1994 1995 // We only consider incoming MemoryAccesses that come before the 1996 // MemoryPhi. Otherwise we could discover candidates that do not 1997 // strictly dominate our starting def. 1998 if (State.PostOrderNumbers[IncomingBlock] > 1999 State.PostOrderNumbers[PhiBlock]) 2000 ToCheck.insert(IncomingAccess); 2001 } 2002 continue; 2003 } 2004 auto *DeadDefAccess = cast<MemoryDef>(DeadAccess); 2005 Instruction *DeadI = DeadDefAccess->getMemoryInst(); 2006 LLVM_DEBUG(dbgs() << " (" << *DeadI << ")\n"); 2007 ToCheck.insert(DeadDefAccess->getDefiningAccess()); 2008 NumGetDomMemoryDefPassed++; 2009 2010 if (!DebugCounter::shouldExecute(MemorySSACounter)) 2011 continue; 2012 2013 MemoryLocation DeadLoc = *State.getLocForWrite(DeadI); 2014 2015 if (IsMemTerm) { 2016 const Value *DeadUndObj = getUnderlyingObject(DeadLoc.Ptr); 2017 if (KillingUndObj != DeadUndObj) 2018 continue; 2019 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DeadI 2020 << "\n KILLER: " << *KillingI << '\n'); 2021 State.deleteDeadInstruction(DeadI); 2022 ++NumFastStores; 2023 MadeChange = true; 2024 } else { 2025 // Check if DeadI overwrites KillingI. 2026 int64_t KillingOffset = 0; 2027 int64_t DeadOffset = 0; 2028 OverwriteResult OR = State.isOverwrite( 2029 KillingI, DeadI, KillingLoc, DeadLoc, KillingOffset, DeadOffset); 2030 if (OR == OW_MaybePartial) { 2031 auto Iter = State.IOLs.insert( 2032 std::make_pair<BasicBlock *, InstOverlapIntervalsTy>( 2033 DeadI->getParent(), InstOverlapIntervalsTy())); 2034 auto &IOL = Iter.first->second; 2035 OR = isPartialOverwrite(KillingLoc, DeadLoc, KillingOffset, 2036 DeadOffset, DeadI, IOL); 2037 } 2038 2039 if (EnablePartialStoreMerging && OR == OW_PartialEarlierWithFullLater) { 2040 auto *DeadSI = dyn_cast<StoreInst>(DeadI); 2041 auto *KillingSI = dyn_cast<StoreInst>(KillingI); 2042 // We are re-using tryToMergePartialOverlappingStores, which requires 2043 // DeadSI to dominate DeadSI. 2044 // TODO: implement tryToMergeParialOverlappingStores using MemorySSA. 2045 if (DeadSI && KillingSI && DT.dominates(DeadSI, KillingSI)) { 2046 if (Constant *Merged = tryToMergePartialOverlappingStores( 2047 KillingSI, DeadSI, KillingOffset, DeadOffset, State.DL, 2048 State.BatchAA, &DT)) { 2049 2050 // Update stored value of earlier store to merged constant. 2051 DeadSI->setOperand(0, Merged); 2052 ++NumModifiedStores; 2053 MadeChange = true; 2054 2055 Shortend = true; 2056 // Remove killing store and remove any outstanding overlap 2057 // intervals for the updated store. 2058 State.deleteDeadInstruction(KillingSI); 2059 auto I = State.IOLs.find(DeadSI->getParent()); 2060 if (I != State.IOLs.end()) 2061 I->second.erase(DeadSI); 2062 break; 2063 } 2064 } 2065 } 2066 2067 if (OR == OW_Complete) { 2068 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: " << *DeadI 2069 << "\n KILLER: " << *KillingI << '\n'); 2070 State.deleteDeadInstruction(DeadI); 2071 ++NumFastStores; 2072 MadeChange = true; 2073 } 2074 } 2075 } 2076 2077 // Check if the store is a no-op. 2078 if (!Shortend && State.storeIsNoop(KillingDef, KillingUndObj)) { 2079 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *KillingI 2080 << '\n'); 2081 State.deleteDeadInstruction(KillingI); 2082 NumRedundantStores++; 2083 MadeChange = true; 2084 continue; 2085 } 2086 2087 // Can we form a calloc from a memset/malloc pair? 2088 if (!Shortend && State.tryFoldIntoCalloc(KillingDef, KillingUndObj)) { 2089 LLVM_DEBUG(dbgs() << "DSE: Remove memset after forming calloc:\n" 2090 << " DEAD: " << *KillingI << '\n'); 2091 State.deleteDeadInstruction(KillingI); 2092 MadeChange = true; 2093 continue; 2094 } 2095 } 2096 2097 if (EnablePartialOverwriteTracking) 2098 for (auto &KV : State.IOLs) 2099 MadeChange |= State.removePartiallyOverlappedStores(KV.second); 2100 2101 MadeChange |= State.eliminateRedundantStoresOfExistingValues(); 2102 MadeChange |= State.eliminateDeadWritesAtEndOfFunction(); 2103 return MadeChange; 2104 } 2105 } // end anonymous namespace 2106 2107 //===----------------------------------------------------------------------===// 2108 // DSE Pass 2109 //===----------------------------------------------------------------------===// 2110 PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) { 2111 AliasAnalysis &AA = AM.getResult<AAManager>(F); 2112 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(F); 2113 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 2114 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 2115 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 2116 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 2117 2118 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI); 2119 2120 #ifdef LLVM_ENABLE_STATS 2121 if (AreStatisticsEnabled()) 2122 for (auto &I : instructions(F)) 2123 NumRemainingStores += isa<StoreInst>(&I); 2124 #endif 2125 2126 if (!Changed) 2127 return PreservedAnalyses::all(); 2128 2129 PreservedAnalyses PA; 2130 PA.preserveSet<CFGAnalyses>(); 2131 PA.preserve<MemorySSAAnalysis>(); 2132 PA.preserve<LoopAnalysis>(); 2133 return PA; 2134 } 2135 2136 namespace { 2137 2138 /// A legacy pass for the legacy pass manager that wraps \c DSEPass. 2139 class DSELegacyPass : public FunctionPass { 2140 public: 2141 static char ID; // Pass identification, replacement for typeid 2142 2143 DSELegacyPass() : FunctionPass(ID) { 2144 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry()); 2145 } 2146 2147 bool runOnFunction(Function &F) override { 2148 if (skipFunction(F)) 2149 return false; 2150 2151 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2152 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2153 const TargetLibraryInfo &TLI = 2154 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2155 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 2156 PostDominatorTree &PDT = 2157 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 2158 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2159 2160 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, LI); 2161 2162 #ifdef LLVM_ENABLE_STATS 2163 if (AreStatisticsEnabled()) 2164 for (auto &I : instructions(F)) 2165 NumRemainingStores += isa<StoreInst>(&I); 2166 #endif 2167 2168 return Changed; 2169 } 2170 2171 void getAnalysisUsage(AnalysisUsage &AU) const override { 2172 AU.setPreservesCFG(); 2173 AU.addRequired<AAResultsWrapperPass>(); 2174 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2175 AU.addPreserved<GlobalsAAWrapperPass>(); 2176 AU.addRequired<DominatorTreeWrapperPass>(); 2177 AU.addPreserved<DominatorTreeWrapperPass>(); 2178 AU.addRequired<PostDominatorTreeWrapperPass>(); 2179 AU.addRequired<MemorySSAWrapperPass>(); 2180 AU.addPreserved<PostDominatorTreeWrapperPass>(); 2181 AU.addPreserved<MemorySSAWrapperPass>(); 2182 AU.addRequired<LoopInfoWrapperPass>(); 2183 AU.addPreserved<LoopInfoWrapperPass>(); 2184 } 2185 }; 2186 2187 } // end anonymous namespace 2188 2189 char DSELegacyPass::ID = 0; 2190 2191 INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false, 2192 false) 2193 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2194 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 2195 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2196 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 2197 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 2198 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 2199 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2200 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2201 INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false, 2202 false) 2203 2204 FunctionPass *llvm::createDeadStoreEliminationPass() { 2205 return new DSELegacyPass(); 2206 } 2207