1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===// 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 pass performs a simple dominator tree walk that eliminates trivially 10 // redundant instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/EarlyCSE.h" 15 #include "llvm/ADT/DenseMapInfo.h" 16 #include "llvm/ADT/Hashing.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/ScopedHashTable.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/GlobalsModRef.h" 24 #include "llvm/Analysis/GuardUtils.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/MemorySSA.h" 27 #include "llvm/Analysis/MemorySSAUpdater.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/InstrTypes.h" 37 #include "llvm/IR/Instruction.h" 38 #include "llvm/IR/Instructions.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/Intrinsics.h" 41 #include "llvm/IR/LLVMContext.h" 42 #include "llvm/IR/PassManager.h" 43 #include "llvm/IR/PatternMatch.h" 44 #include "llvm/IR/Statepoint.h" 45 #include "llvm/IR/Type.h" 46 #include "llvm/IR/Use.h" 47 #include "llvm/IR/Value.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/Pass.h" 50 #include "llvm/Support/Allocator.h" 51 #include "llvm/Support/AtomicOrdering.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/Debug.h" 54 #include "llvm/Support/DebugCounter.h" 55 #include "llvm/Support/RecyclingAllocator.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include "llvm/Transforms/Scalar.h" 58 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 59 #include "llvm/Transforms/Utils/GuardUtils.h" 60 #include "llvm/Transforms/Utils/Local.h" 61 #include <cassert> 62 #include <deque> 63 #include <memory> 64 #include <utility> 65 66 using namespace llvm; 67 using namespace llvm::PatternMatch; 68 69 #define DEBUG_TYPE "early-cse" 70 71 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd"); 72 STATISTIC(NumCSE, "Number of instructions CSE'd"); 73 STATISTIC(NumCSECVP, "Number of compare instructions CVP'd"); 74 STATISTIC(NumCSELoad, "Number of load instructions CSE'd"); 75 STATISTIC(NumCSECall, "Number of call instructions CSE'd"); 76 STATISTIC(NumDSE, "Number of trivial dead stores removed"); 77 78 DEBUG_COUNTER(CSECounter, "early-cse", 79 "Controls which instructions are removed"); 80 81 static cl::opt<unsigned> EarlyCSEMssaOptCap( 82 "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden, 83 cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange " 84 "for faster compile. Caps the MemorySSA clobbering calls.")); 85 86 static cl::opt<bool> EarlyCSEDebugHash( 87 "earlycse-debug-hash", cl::init(false), cl::Hidden, 88 cl::desc("Perform extra assertion checking to verify that SimpleValue's hash " 89 "function is well-behaved w.r.t. its isEqual predicate")); 90 91 //===----------------------------------------------------------------------===// 92 // SimpleValue 93 //===----------------------------------------------------------------------===// 94 95 namespace { 96 97 /// Struct representing the available values in the scoped hash table. 98 struct SimpleValue { 99 Instruction *Inst; 100 101 SimpleValue(Instruction *I) : Inst(I) { 102 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 103 } 104 105 bool isSentinel() const { 106 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 107 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 108 } 109 110 static bool canHandle(Instruction *Inst) { 111 // This can only handle non-void readnone functions. 112 if (CallInst *CI = dyn_cast<CallInst>(Inst)) 113 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy(); 114 return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) || 115 isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) || 116 isa<CmpInst>(Inst) || isa<SelectInst>(Inst) || 117 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) || 118 isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) || 119 isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst); 120 } 121 }; 122 123 } // end anonymous namespace 124 125 namespace llvm { 126 127 template <> struct DenseMapInfo<SimpleValue> { 128 static inline SimpleValue getEmptyKey() { 129 return DenseMapInfo<Instruction *>::getEmptyKey(); 130 } 131 132 static inline SimpleValue getTombstoneKey() { 133 return DenseMapInfo<Instruction *>::getTombstoneKey(); 134 } 135 136 static unsigned getHashValue(SimpleValue Val); 137 static bool isEqual(SimpleValue LHS, SimpleValue RHS); 138 }; 139 140 } // end namespace llvm 141 142 /// Match a 'select' including an optional 'not's of the condition. 143 static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A, 144 Value *&B, 145 SelectPatternFlavor &Flavor) { 146 // Return false if V is not even a select. 147 if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B)))) 148 return false; 149 150 // Look through a 'not' of the condition operand by swapping A/B. 151 Value *CondNot; 152 if (match(Cond, m_Not(m_Value(CondNot)))) { 153 Cond = CondNot; 154 std::swap(A, B); 155 } 156 157 // Match canonical forms of abs/nabs/min/max. We are not using ValueTracking's 158 // more powerful matchSelectPattern() because it may rely on instruction flags 159 // such as "nsw". That would be incompatible with the current hashing 160 // mechanism that may remove flags to increase the likelihood of CSE. 161 162 // These are the canonical forms of abs(X) and nabs(X) created by instcombine: 163 // %N = sub i32 0, %X 164 // %C = icmp slt i32 %X, 0 165 // %ABS = select i1 %C, i32 %N, i32 %X 166 // 167 // %N = sub i32 0, %X 168 // %C = icmp slt i32 %X, 0 169 // %NABS = select i1 %C, i32 %X, i32 %N 170 Flavor = SPF_UNKNOWN; 171 CmpInst::Predicate Pred; 172 if (match(Cond, m_ICmp(Pred, m_Specific(B), m_ZeroInt())) && 173 Pred == ICmpInst::ICMP_SLT && match(A, m_Neg(m_Specific(B)))) { 174 // ABS: B < 0 ? -B : B 175 Flavor = SPF_ABS; 176 return true; 177 } 178 if (match(Cond, m_ICmp(Pred, m_Specific(A), m_ZeroInt())) && 179 Pred == ICmpInst::ICMP_SLT && match(B, m_Neg(m_Specific(A)))) { 180 // NABS: A < 0 ? A : -A 181 Flavor = SPF_NABS; 182 return true; 183 } 184 185 if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) { 186 // Check for commuted variants of min/max by swapping predicate. 187 // If we do not match the standard or commuted patterns, this is not a 188 // recognized form of min/max, but it is still a select, so return true. 189 if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A)))) 190 return true; 191 Pred = ICmpInst::getSwappedPredicate(Pred); 192 } 193 194 switch (Pred) { 195 case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break; 196 case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break; 197 case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break; 198 case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break; 199 default: break; 200 } 201 202 return true; 203 } 204 205 static unsigned getHashValueImpl(SimpleValue Val) { 206 Instruction *Inst = Val.Inst; 207 // Hash in all of the operands as pointers. 208 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) { 209 Value *LHS = BinOp->getOperand(0); 210 Value *RHS = BinOp->getOperand(1); 211 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1)) 212 std::swap(LHS, RHS); 213 214 return hash_combine(BinOp->getOpcode(), LHS, RHS); 215 } 216 217 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) { 218 // Compares can be commuted by swapping the comparands and 219 // updating the predicate. Choose the form that has the 220 // comparands in sorted order, or in the case of a tie, the 221 // one with the lower predicate. 222 Value *LHS = CI->getOperand(0); 223 Value *RHS = CI->getOperand(1); 224 CmpInst::Predicate Pred = CI->getPredicate(); 225 CmpInst::Predicate SwappedPred = CI->getSwappedPredicate(); 226 if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) { 227 std::swap(LHS, RHS); 228 Pred = SwappedPred; 229 } 230 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS); 231 } 232 233 // Hash general selects to allow matching commuted true/false operands. 234 SelectPatternFlavor SPF; 235 Value *Cond, *A, *B; 236 if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) { 237 // Hash min/max/abs (cmp + select) to allow for commuted operands. 238 // Min/max may also have non-canonical compare predicate (eg, the compare for 239 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the 240 // compare. 241 // TODO: We should also detect FP min/max. 242 if (SPF == SPF_SMIN || SPF == SPF_SMAX || 243 SPF == SPF_UMIN || SPF == SPF_UMAX) { 244 if (A > B) 245 std::swap(A, B); 246 return hash_combine(Inst->getOpcode(), SPF, A, B); 247 } 248 if (SPF == SPF_ABS || SPF == SPF_NABS) { 249 // ABS/NABS always puts the input in A and its negation in B. 250 return hash_combine(Inst->getOpcode(), SPF, A, B); 251 } 252 253 // Hash general selects to allow matching commuted true/false operands. 254 255 // If we do not have a compare as the condition, just hash in the condition. 256 CmpInst::Predicate Pred; 257 Value *X, *Y; 258 if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y)))) 259 return hash_combine(Inst->getOpcode(), Cond, A, B); 260 261 // Similar to cmp normalization (above) - canonicalize the predicate value: 262 // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A 263 if (CmpInst::getInversePredicate(Pred) < Pred) { 264 Pred = CmpInst::getInversePredicate(Pred); 265 std::swap(A, B); 266 } 267 return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B); 268 } 269 270 if (CastInst *CI = dyn_cast<CastInst>(Inst)) 271 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0)); 272 273 if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst)) 274 return hash_combine(FI->getOpcode(), FI->getOperand(0)); 275 276 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) 277 return hash_combine(EVI->getOpcode(), EVI->getOperand(0), 278 hash_combine_range(EVI->idx_begin(), EVI->idx_end())); 279 280 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) 281 return hash_combine(IVI->getOpcode(), IVI->getOperand(0), 282 IVI->getOperand(1), 283 hash_combine_range(IVI->idx_begin(), IVI->idx_end())); 284 285 assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) || 286 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) || 287 isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) || 288 isa<FreezeInst>(Inst)) && 289 "Invalid/unknown instruction"); 290 291 // Handle intrinsics with commutative operands. 292 // TODO: Extend this to handle intrinsics with >2 operands where the 1st 293 // 2 operands are commutative. 294 auto *II = dyn_cast<IntrinsicInst>(Inst); 295 if (II && II->isCommutative() && II->getNumArgOperands() == 2) { 296 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 297 if (LHS > RHS) 298 std::swap(LHS, RHS); 299 return hash_combine(II->getOpcode(), LHS, RHS); 300 } 301 302 // Mix in the opcode. 303 return hash_combine( 304 Inst->getOpcode(), 305 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 306 } 307 308 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) { 309 #ifndef NDEBUG 310 // If -earlycse-debug-hash was specified, return a constant -- this 311 // will force all hashing to collide, so we'll exhaustively search 312 // the table for a match, and the assertion in isEqual will fire if 313 // there's a bug causing equal keys to hash differently. 314 if (EarlyCSEDebugHash) 315 return 0; 316 #endif 317 return getHashValueImpl(Val); 318 } 319 320 static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) { 321 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 322 323 if (LHS.isSentinel() || RHS.isSentinel()) 324 return LHSI == RHSI; 325 326 if (LHSI->getOpcode() != RHSI->getOpcode()) 327 return false; 328 if (LHSI->isIdenticalToWhenDefined(RHSI)) 329 return true; 330 331 // If we're not strictly identical, we still might be a commutable instruction 332 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) { 333 if (!LHSBinOp->isCommutative()) 334 return false; 335 336 assert(isa<BinaryOperator>(RHSI) && 337 "same opcode, but different instruction type?"); 338 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI); 339 340 // Commuted equality 341 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) && 342 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0); 343 } 344 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) { 345 assert(isa<CmpInst>(RHSI) && 346 "same opcode, but different instruction type?"); 347 CmpInst *RHSCmp = cast<CmpInst>(RHSI); 348 // Commuted equality 349 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) && 350 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) && 351 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate(); 352 } 353 354 // TODO: Extend this for >2 args by matching the trailing N-2 args. 355 auto *LII = dyn_cast<IntrinsicInst>(LHSI); 356 auto *RII = dyn_cast<IntrinsicInst>(RHSI); 357 if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() && 358 LII->isCommutative() && LII->getNumArgOperands() == 2) { 359 return LII->getArgOperand(0) == RII->getArgOperand(1) && 360 LII->getArgOperand(1) == RII->getArgOperand(0); 361 } 362 363 // Min/max/abs can occur with commuted operands, non-canonical predicates, 364 // and/or non-canonical operands. 365 // Selects can be non-trivially equivalent via inverted conditions and swaps. 366 SelectPatternFlavor LSPF, RSPF; 367 Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB; 368 if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) && 369 matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) { 370 if (LSPF == RSPF) { 371 // TODO: We should also detect FP min/max. 372 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX || 373 LSPF == SPF_UMIN || LSPF == SPF_UMAX) 374 return ((LHSA == RHSA && LHSB == RHSB) || 375 (LHSA == RHSB && LHSB == RHSA)); 376 377 if (LSPF == SPF_ABS || LSPF == SPF_NABS) { 378 // Abs results are placed in a defined order by matchSelectPattern. 379 return LHSA == RHSA && LHSB == RHSB; 380 } 381 382 // select Cond, A, B <--> select not(Cond), B, A 383 if (CondL == CondR && LHSA == RHSA && LHSB == RHSB) 384 return true; 385 } 386 387 // If the true/false operands are swapped and the conditions are compares 388 // with inverted predicates, the selects are equal: 389 // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A 390 // 391 // This also handles patterns with a double-negation in the sense of not + 392 // inverse, because we looked through a 'not' in the matching function and 393 // swapped A/B: 394 // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A 395 // 396 // This intentionally does NOT handle patterns with a double-negation in 397 // the sense of not + not, because doing so could result in values 398 // comparing 399 // as equal that hash differently in the min/max/abs cases like: 400 // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y 401 // ^ hashes as min ^ would not hash as min 402 // In the context of the EarlyCSE pass, however, such cases never reach 403 // this code, as we simplify the double-negation before hashing the second 404 // select (and so still succeed at CSEing them). 405 if (LHSA == RHSB && LHSB == RHSA) { 406 CmpInst::Predicate PredL, PredR; 407 Value *X, *Y; 408 if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) && 409 match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) && 410 CmpInst::getInversePredicate(PredL) == PredR) 411 return true; 412 } 413 } 414 415 return false; 416 } 417 418 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) { 419 // These comparisons are nontrivial, so assert that equality implies 420 // hash equality (DenseMap demands this as an invariant). 421 bool Result = isEqualImpl(LHS, RHS); 422 assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) || 423 getHashValueImpl(LHS) == getHashValueImpl(RHS)); 424 return Result; 425 } 426 427 //===----------------------------------------------------------------------===// 428 // CallValue 429 //===----------------------------------------------------------------------===// 430 431 namespace { 432 433 /// Struct representing the available call values in the scoped hash 434 /// table. 435 struct CallValue { 436 Instruction *Inst; 437 438 CallValue(Instruction *I) : Inst(I) { 439 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 440 } 441 442 bool isSentinel() const { 443 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 444 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 445 } 446 447 static bool canHandle(Instruction *Inst) { 448 // Don't value number anything that returns void. 449 if (Inst->getType()->isVoidTy()) 450 return false; 451 452 CallInst *CI = dyn_cast<CallInst>(Inst); 453 if (!CI || !CI->onlyReadsMemory()) 454 return false; 455 return true; 456 } 457 }; 458 459 } // end anonymous namespace 460 461 namespace llvm { 462 463 template <> struct DenseMapInfo<CallValue> { 464 static inline CallValue getEmptyKey() { 465 return DenseMapInfo<Instruction *>::getEmptyKey(); 466 } 467 468 static inline CallValue getTombstoneKey() { 469 return DenseMapInfo<Instruction *>::getTombstoneKey(); 470 } 471 472 static unsigned getHashValue(CallValue Val); 473 static bool isEqual(CallValue LHS, CallValue RHS); 474 }; 475 476 } // end namespace llvm 477 478 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) { 479 Instruction *Inst = Val.Inst; 480 481 // gc.relocate is 'special' call: its second and third operands are 482 // not real values, but indices into statepoint's argument list. 483 // Get values they point to. 484 if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst)) 485 return hash_combine(GCR->getOpcode(), GCR->getOperand(0), 486 GCR->getBasePtr(), GCR->getDerivedPtr()); 487 488 // Hash all of the operands as pointers and mix in the opcode. 489 return hash_combine( 490 Inst->getOpcode(), 491 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 492 } 493 494 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) { 495 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 496 if (LHS.isSentinel() || RHS.isSentinel()) 497 return LHSI == RHSI; 498 499 // See comment above in `getHashValue()`. 500 if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI)) 501 if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI)) 502 return GCR1->getOperand(0) == GCR2->getOperand(0) && 503 GCR1->getBasePtr() == GCR2->getBasePtr() && 504 GCR1->getDerivedPtr() == GCR2->getDerivedPtr(); 505 506 return LHSI->isIdenticalTo(RHSI); 507 } 508 509 //===----------------------------------------------------------------------===// 510 // EarlyCSE implementation 511 //===----------------------------------------------------------------------===// 512 513 namespace { 514 515 /// A simple and fast domtree-based CSE pass. 516 /// 517 /// This pass does a simple depth-first walk over the dominator tree, 518 /// eliminating trivially redundant instructions and using instsimplify to 519 /// canonicalize things as it goes. It is intended to be fast and catch obvious 520 /// cases so that instcombine and other passes are more effective. It is 521 /// expected that a later pass of GVN will catch the interesting/hard cases. 522 class EarlyCSE { 523 public: 524 const TargetLibraryInfo &TLI; 525 const TargetTransformInfo &TTI; 526 DominatorTree &DT; 527 AssumptionCache &AC; 528 const SimplifyQuery SQ; 529 MemorySSA *MSSA; 530 std::unique_ptr<MemorySSAUpdater> MSSAUpdater; 531 532 using AllocatorTy = 533 RecyclingAllocator<BumpPtrAllocator, 534 ScopedHashTableVal<SimpleValue, Value *>>; 535 using ScopedHTType = 536 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>, 537 AllocatorTy>; 538 539 /// A scoped hash table of the current values of all of our simple 540 /// scalar expressions. 541 /// 542 /// As we walk down the domtree, we look to see if instructions are in this: 543 /// if so, we replace them with what we find, otherwise we insert them so 544 /// that dominated values can succeed in their lookup. 545 ScopedHTType AvailableValues; 546 547 /// A scoped hash table of the current values of previously encountered 548 /// memory locations. 549 /// 550 /// This allows us to get efficient access to dominating loads or stores when 551 /// we have a fully redundant load. In addition to the most recent load, we 552 /// keep track of a generation count of the read, which is compared against 553 /// the current generation count. The current generation count is incremented 554 /// after every possibly writing memory operation, which ensures that we only 555 /// CSE loads with other loads that have no intervening store. Ordering 556 /// events (such as fences or atomic instructions) increment the generation 557 /// count as well; essentially, we model these as writes to all possible 558 /// locations. Note that atomic and/or volatile loads and stores can be 559 /// present the table; it is the responsibility of the consumer to inspect 560 /// the atomicity/volatility if needed. 561 struct LoadValue { 562 Instruction *DefInst = nullptr; 563 unsigned Generation = 0; 564 int MatchingId = -1; 565 bool IsAtomic = false; 566 567 LoadValue() = default; 568 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId, 569 bool IsAtomic) 570 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId), 571 IsAtomic(IsAtomic) {} 572 }; 573 574 using LoadMapAllocator = 575 RecyclingAllocator<BumpPtrAllocator, 576 ScopedHashTableVal<Value *, LoadValue>>; 577 using LoadHTType = 578 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>, 579 LoadMapAllocator>; 580 581 LoadHTType AvailableLoads; 582 583 // A scoped hash table mapping memory locations (represented as typed 584 // addresses) to generation numbers at which that memory location became 585 // (henceforth indefinitely) invariant. 586 using InvariantMapAllocator = 587 RecyclingAllocator<BumpPtrAllocator, 588 ScopedHashTableVal<MemoryLocation, unsigned>>; 589 using InvariantHTType = 590 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>, 591 InvariantMapAllocator>; 592 InvariantHTType AvailableInvariants; 593 594 /// A scoped hash table of the current values of read-only call 595 /// values. 596 /// 597 /// It uses the same generation count as loads. 598 using CallHTType = 599 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>; 600 CallHTType AvailableCalls; 601 602 /// This is the current generation of the memory value. 603 unsigned CurrentGeneration = 0; 604 605 /// Set up the EarlyCSE runner for a particular function. 606 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI, 607 const TargetTransformInfo &TTI, DominatorTree &DT, 608 AssumptionCache &AC, MemorySSA *MSSA) 609 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA), 610 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {} 611 612 bool run(); 613 614 private: 615 unsigned ClobberCounter = 0; 616 // Almost a POD, but needs to call the constructors for the scoped hash 617 // tables so that a new scope gets pushed on. These are RAII so that the 618 // scope gets popped when the NodeScope is destroyed. 619 class NodeScope { 620 public: 621 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 622 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls) 623 : Scope(AvailableValues), LoadScope(AvailableLoads), 624 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {} 625 NodeScope(const NodeScope &) = delete; 626 NodeScope &operator=(const NodeScope &) = delete; 627 628 private: 629 ScopedHTType::ScopeTy Scope; 630 LoadHTType::ScopeTy LoadScope; 631 InvariantHTType::ScopeTy InvariantScope; 632 CallHTType::ScopeTy CallScope; 633 }; 634 635 // Contains all the needed information to create a stack for doing a depth 636 // first traversal of the tree. This includes scopes for values, loads, and 637 // calls as well as the generation. There is a child iterator so that the 638 // children do not need to be store separately. 639 class StackNode { 640 public: 641 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 642 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls, 643 unsigned cg, DomTreeNode *n, DomTreeNode::const_iterator child, 644 DomTreeNode::const_iterator end) 645 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child), 646 EndIter(end), 647 Scopes(AvailableValues, AvailableLoads, AvailableInvariants, 648 AvailableCalls) 649 {} 650 StackNode(const StackNode &) = delete; 651 StackNode &operator=(const StackNode &) = delete; 652 653 // Accessors. 654 unsigned currentGeneration() { return CurrentGeneration; } 655 unsigned childGeneration() { return ChildGeneration; } 656 void childGeneration(unsigned generation) { ChildGeneration = generation; } 657 DomTreeNode *node() { return Node; } 658 DomTreeNode::const_iterator childIter() { return ChildIter; } 659 660 DomTreeNode *nextChild() { 661 DomTreeNode *child = *ChildIter; 662 ++ChildIter; 663 return child; 664 } 665 666 DomTreeNode::const_iterator end() { return EndIter; } 667 bool isProcessed() { return Processed; } 668 void process() { Processed = true; } 669 670 private: 671 unsigned CurrentGeneration; 672 unsigned ChildGeneration; 673 DomTreeNode *Node; 674 DomTreeNode::const_iterator ChildIter; 675 DomTreeNode::const_iterator EndIter; 676 NodeScope Scopes; 677 bool Processed = false; 678 }; 679 680 /// Wrapper class to handle memory instructions, including loads, 681 /// stores and intrinsic loads and stores defined by the target. 682 class ParseMemoryInst { 683 public: 684 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI) 685 : Inst(Inst) { 686 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 687 if (TTI.getTgtMemIntrinsic(II, Info)) 688 IsTargetMemInst = true; 689 } 690 691 bool isLoad() const { 692 if (IsTargetMemInst) return Info.ReadMem; 693 return isa<LoadInst>(Inst); 694 } 695 696 bool isStore() const { 697 if (IsTargetMemInst) return Info.WriteMem; 698 return isa<StoreInst>(Inst); 699 } 700 701 bool isAtomic() const { 702 if (IsTargetMemInst) 703 return Info.Ordering != AtomicOrdering::NotAtomic; 704 return Inst->isAtomic(); 705 } 706 707 bool isUnordered() const { 708 if (IsTargetMemInst) 709 return Info.isUnordered(); 710 711 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 712 return LI->isUnordered(); 713 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 714 return SI->isUnordered(); 715 } 716 // Conservative answer 717 return !Inst->isAtomic(); 718 } 719 720 bool isVolatile() const { 721 if (IsTargetMemInst) 722 return Info.IsVolatile; 723 724 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 725 return LI->isVolatile(); 726 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 727 return SI->isVolatile(); 728 } 729 // Conservative answer 730 return true; 731 } 732 733 bool isInvariantLoad() const { 734 if (auto *LI = dyn_cast<LoadInst>(Inst)) 735 return LI->hasMetadata(LLVMContext::MD_invariant_load); 736 return false; 737 } 738 739 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const { 740 return (getPointerOperand() == Inst.getPointerOperand() && 741 getMatchingId() == Inst.getMatchingId()); 742 } 743 744 bool isValid() const { return getPointerOperand() != nullptr; } 745 746 // For regular (non-intrinsic) loads/stores, this is set to -1. For 747 // intrinsic loads/stores, the id is retrieved from the corresponding 748 // field in the MemIntrinsicInfo structure. That field contains 749 // non-negative values only. 750 int getMatchingId() const { 751 if (IsTargetMemInst) return Info.MatchingId; 752 return -1; 753 } 754 755 Value *getPointerOperand() const { 756 if (IsTargetMemInst) return Info.PtrVal; 757 return getLoadStorePointerOperand(Inst); 758 } 759 760 bool mayReadFromMemory() const { 761 if (IsTargetMemInst) return Info.ReadMem; 762 return Inst->mayReadFromMemory(); 763 } 764 765 bool mayWriteToMemory() const { 766 if (IsTargetMemInst) return Info.WriteMem; 767 return Inst->mayWriteToMemory(); 768 } 769 770 private: 771 bool IsTargetMemInst = false; 772 MemIntrinsicInfo Info; 773 Instruction *Inst; 774 }; 775 776 bool processNode(DomTreeNode *Node); 777 778 bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI, 779 const BasicBlock *BB, const BasicBlock *Pred); 780 781 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const { 782 if (auto *LI = dyn_cast<LoadInst>(Inst)) 783 return LI; 784 if (auto *SI = dyn_cast<StoreInst>(Inst)) 785 return SI->getValueOperand(); 786 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported"); 787 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst), 788 ExpectedType); 789 } 790 791 /// Return true if the instruction is known to only operate on memory 792 /// provably invariant in the given "generation". 793 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt); 794 795 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration, 796 Instruction *EarlierInst, Instruction *LaterInst); 797 798 void removeMSSA(Instruction &Inst) { 799 if (!MSSA) 800 return; 801 if (VerifyMemorySSA) 802 MSSA->verifyMemorySSA(); 803 // Removing a store here can leave MemorySSA in an unoptimized state by 804 // creating MemoryPhis that have identical arguments and by creating 805 // MemoryUses whose defining access is not an actual clobber. The phi case 806 // is handled by MemorySSA when passing OptimizePhis = true to 807 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated 808 // by MemorySSA's getClobberingMemoryAccess. 809 MSSAUpdater->removeMemoryAccess(&Inst, true); 810 } 811 }; 812 813 } // end anonymous namespace 814 815 /// Determine if the memory referenced by LaterInst is from the same heap 816 /// version as EarlierInst. 817 /// This is currently called in two scenarios: 818 /// 819 /// load p 820 /// ... 821 /// load p 822 /// 823 /// and 824 /// 825 /// x = load p 826 /// ... 827 /// store x, p 828 /// 829 /// in both cases we want to verify that there are no possible writes to the 830 /// memory referenced by p between the earlier and later instruction. 831 bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration, 832 unsigned LaterGeneration, 833 Instruction *EarlierInst, 834 Instruction *LaterInst) { 835 // Check the simple memory generation tracking first. 836 if (EarlierGeneration == LaterGeneration) 837 return true; 838 839 if (!MSSA) 840 return false; 841 842 // If MemorySSA has determined that one of EarlierInst or LaterInst does not 843 // read/write memory, then we can safely return true here. 844 // FIXME: We could be more aggressive when checking doesNotAccessMemory(), 845 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass 846 // by also checking the MemorySSA MemoryAccess on the instruction. Initial 847 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled 848 // with the default optimization pipeline. 849 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst); 850 if (!EarlierMA) 851 return true; 852 auto *LaterMA = MSSA->getMemoryAccess(LaterInst); 853 if (!LaterMA) 854 return true; 855 856 // Since we know LaterDef dominates LaterInst and EarlierInst dominates 857 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between 858 // EarlierInst and LaterInst and neither can any other write that potentially 859 // clobbers LaterInst. 860 MemoryAccess *LaterDef; 861 if (ClobberCounter < EarlyCSEMssaOptCap) { 862 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst); 863 ClobberCounter++; 864 } else 865 LaterDef = LaterMA->getDefiningAccess(); 866 867 return MSSA->dominates(LaterDef, EarlierMA); 868 } 869 870 bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) { 871 // A location loaded from with an invariant_load is assumed to *never* change 872 // within the visible scope of the compilation. 873 if (auto *LI = dyn_cast<LoadInst>(I)) 874 if (LI->hasMetadata(LLVMContext::MD_invariant_load)) 875 return true; 876 877 auto MemLocOpt = MemoryLocation::getOrNone(I); 878 if (!MemLocOpt) 879 // "target" intrinsic forms of loads aren't currently known to 880 // MemoryLocation::get. TODO 881 return false; 882 MemoryLocation MemLoc = *MemLocOpt; 883 if (!AvailableInvariants.count(MemLoc)) 884 return false; 885 886 // Is the generation at which this became invariant older than the 887 // current one? 888 return AvailableInvariants.lookup(MemLoc) <= GenAt; 889 } 890 891 bool EarlyCSE::handleBranchCondition(Instruction *CondInst, 892 const BranchInst *BI, const BasicBlock *BB, 893 const BasicBlock *Pred) { 894 assert(BI->isConditional() && "Should be a conditional branch!"); 895 assert(BI->getCondition() == CondInst && "Wrong condition?"); 896 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB); 897 auto *TorF = (BI->getSuccessor(0) == BB) 898 ? ConstantInt::getTrue(BB->getContext()) 899 : ConstantInt::getFalse(BB->getContext()); 900 auto MatchBinOp = [](Instruction *I, unsigned Opcode) { 901 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) 902 return BOp->getOpcode() == Opcode; 903 return false; 904 }; 905 // If the condition is AND operation, we can propagate its operands into the 906 // true branch. If it is OR operation, we can propagate them into the false 907 // branch. 908 unsigned PropagateOpcode = 909 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or; 910 911 bool MadeChanges = false; 912 SmallVector<Instruction *, 4> WorkList; 913 SmallPtrSet<Instruction *, 4> Visited; 914 WorkList.push_back(CondInst); 915 while (!WorkList.empty()) { 916 Instruction *Curr = WorkList.pop_back_val(); 917 918 AvailableValues.insert(Curr, TorF); 919 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '" 920 << Curr->getName() << "' as " << *TorF << " in " 921 << BB->getName() << "\n"); 922 if (!DebugCounter::shouldExecute(CSECounter)) { 923 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 924 } else { 925 // Replace all dominated uses with the known value. 926 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT, 927 BasicBlockEdge(Pred, BB))) { 928 NumCSECVP += Count; 929 MadeChanges = true; 930 } 931 } 932 933 if (MatchBinOp(Curr, PropagateOpcode)) 934 for (auto &Op : cast<BinaryOperator>(Curr)->operands()) 935 if (Instruction *OPI = dyn_cast<Instruction>(Op)) 936 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second) 937 WorkList.push_back(OPI); 938 } 939 940 return MadeChanges; 941 } 942 943 bool EarlyCSE::processNode(DomTreeNode *Node) { 944 bool Changed = false; 945 BasicBlock *BB = Node->getBlock(); 946 947 // If this block has a single predecessor, then the predecessor is the parent 948 // of the domtree node and all of the live out memory values are still current 949 // in this block. If this block has multiple predecessors, then they could 950 // have invalidated the live-out memory values of our parent value. For now, 951 // just be conservative and invalidate memory if this block has multiple 952 // predecessors. 953 if (!BB->getSinglePredecessor()) 954 ++CurrentGeneration; 955 956 // If this node has a single predecessor which ends in a conditional branch, 957 // we can infer the value of the branch condition given that we took this 958 // path. We need the single predecessor to ensure there's not another path 959 // which reaches this block where the condition might hold a different 960 // value. Since we're adding this to the scoped hash table (like any other 961 // def), it will have been popped if we encounter a future merge block. 962 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 963 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()); 964 if (BI && BI->isConditional()) { 965 auto *CondInst = dyn_cast<Instruction>(BI->getCondition()); 966 if (CondInst && SimpleValue::canHandle(CondInst)) 967 Changed |= handleBranchCondition(CondInst, BI, BB, Pred); 968 } 969 } 970 971 /// LastStore - Keep track of the last non-volatile store that we saw... for 972 /// as long as there in no instruction that reads memory. If we see a store 973 /// to the same location, we delete the dead store. This zaps trivial dead 974 /// stores which can occur in bitfield code among other things. 975 Instruction *LastStore = nullptr; 976 977 // See if any instructions in the block can be eliminated. If so, do it. If 978 // not, add them to AvailableValues. 979 for (Instruction &Inst : make_early_inc_range(BB->getInstList())) { 980 // Dead instructions should just be removed. 981 if (isInstructionTriviallyDead(&Inst, &TLI)) { 982 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n'); 983 if (!DebugCounter::shouldExecute(CSECounter)) { 984 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 985 continue; 986 } 987 988 salvageKnowledge(&Inst, &AC); 989 salvageDebugInfo(Inst); 990 removeMSSA(Inst); 991 Inst.eraseFromParent(); 992 Changed = true; 993 ++NumSimplify; 994 continue; 995 } 996 997 // Skip assume intrinsics, they don't really have side effects (although 998 // they're marked as such to ensure preservation of control dependencies), 999 // and this pass will not bother with its removal. However, we should mark 1000 // its condition as true for all dominated blocks. 1001 if (match(&Inst, m_Intrinsic<Intrinsic::assume>())) { 1002 auto *CondI = 1003 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0)); 1004 if (CondI && SimpleValue::canHandle(CondI)) { 1005 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst 1006 << '\n'); 1007 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 1008 } else 1009 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n'); 1010 continue; 1011 } 1012 1013 // Skip sideeffect intrinsics, for the same reason as assume intrinsics. 1014 if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) { 1015 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n'); 1016 continue; 1017 } 1018 1019 // We can skip all invariant.start intrinsics since they only read memory, 1020 // and we can forward values across it. For invariant starts without 1021 // invariant ends, we can use the fact that the invariantness never ends to 1022 // start a scope in the current generaton which is true for all future 1023 // generations. Also, we dont need to consume the last store since the 1024 // semantics of invariant.start allow us to perform DSE of the last 1025 // store, if there was a store following invariant.start. Consider: 1026 // 1027 // store 30, i8* p 1028 // invariant.start(p) 1029 // store 40, i8* p 1030 // We can DSE the store to 30, since the store 40 to invariant location p 1031 // causes undefined behaviour. 1032 if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) { 1033 // If there are any uses, the scope might end. 1034 if (!Inst.use_empty()) 1035 continue; 1036 MemoryLocation MemLoc = 1037 MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI); 1038 // Don't start a scope if we already have a better one pushed 1039 if (!AvailableInvariants.count(MemLoc)) 1040 AvailableInvariants.insert(MemLoc, CurrentGeneration); 1041 continue; 1042 } 1043 1044 if (isGuard(&Inst)) { 1045 if (auto *CondI = 1046 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) { 1047 if (SimpleValue::canHandle(CondI)) { 1048 // Do we already know the actual value of this condition? 1049 if (auto *KnownCond = AvailableValues.lookup(CondI)) { 1050 // Is the condition known to be true? 1051 if (isa<ConstantInt>(KnownCond) && 1052 cast<ConstantInt>(KnownCond)->isOne()) { 1053 LLVM_DEBUG(dbgs() 1054 << "EarlyCSE removing guard: " << Inst << '\n'); 1055 salvageKnowledge(&Inst, &AC); 1056 removeMSSA(Inst); 1057 Inst.eraseFromParent(); 1058 Changed = true; 1059 continue; 1060 } else 1061 // Use the known value if it wasn't true. 1062 cast<CallInst>(Inst).setArgOperand(0, KnownCond); 1063 } 1064 // The condition we're on guarding here is true for all dominated 1065 // locations. 1066 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 1067 } 1068 } 1069 1070 // Guard intrinsics read all memory, but don't write any memory. 1071 // Accordingly, don't update the generation but consume the last store (to 1072 // avoid an incorrect DSE). 1073 LastStore = nullptr; 1074 continue; 1075 } 1076 1077 // If the instruction can be simplified (e.g. X+0 = X) then replace it with 1078 // its simpler value. 1079 if (Value *V = SimplifyInstruction(&Inst, SQ)) { 1080 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V 1081 << '\n'); 1082 if (!DebugCounter::shouldExecute(CSECounter)) { 1083 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1084 } else { 1085 bool Killed = false; 1086 if (!Inst.use_empty()) { 1087 Inst.replaceAllUsesWith(V); 1088 Changed = true; 1089 } 1090 if (isInstructionTriviallyDead(&Inst, &TLI)) { 1091 salvageKnowledge(&Inst, &AC); 1092 removeMSSA(Inst); 1093 Inst.eraseFromParent(); 1094 Changed = true; 1095 Killed = true; 1096 } 1097 if (Changed) 1098 ++NumSimplify; 1099 if (Killed) 1100 continue; 1101 } 1102 } 1103 1104 // If this is a simple instruction that we can value number, process it. 1105 if (SimpleValue::canHandle(&Inst)) { 1106 // See if the instruction has an available value. If so, use it. 1107 if (Value *V = AvailableValues.lookup(&Inst)) { 1108 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V 1109 << '\n'); 1110 if (!DebugCounter::shouldExecute(CSECounter)) { 1111 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1112 continue; 1113 } 1114 if (auto *I = dyn_cast<Instruction>(V)) 1115 I->andIRFlags(&Inst); 1116 Inst.replaceAllUsesWith(V); 1117 salvageKnowledge(&Inst, &AC); 1118 removeMSSA(Inst); 1119 Inst.eraseFromParent(); 1120 Changed = true; 1121 ++NumCSE; 1122 continue; 1123 } 1124 1125 // Otherwise, just remember that this value is available. 1126 AvailableValues.insert(&Inst, &Inst); 1127 continue; 1128 } 1129 1130 ParseMemoryInst MemInst(&Inst, TTI); 1131 // If this is a non-volatile load, process it. 1132 if (MemInst.isValid() && MemInst.isLoad()) { 1133 // (conservatively) we can't peak past the ordering implied by this 1134 // operation, but we can add this load to our set of available values 1135 if (MemInst.isVolatile() || !MemInst.isUnordered()) { 1136 LastStore = nullptr; 1137 ++CurrentGeneration; 1138 } 1139 1140 if (MemInst.isInvariantLoad()) { 1141 // If we pass an invariant load, we know that memory location is 1142 // indefinitely constant from the moment of first dereferenceability. 1143 // We conservatively treat the invariant_load as that moment. If we 1144 // pass a invariant load after already establishing a scope, don't 1145 // restart it since we want to preserve the earliest point seen. 1146 auto MemLoc = MemoryLocation::get(&Inst); 1147 if (!AvailableInvariants.count(MemLoc)) 1148 AvailableInvariants.insert(MemLoc, CurrentGeneration); 1149 } 1150 1151 // If we have an available version of this load, and if it is the right 1152 // generation or the load is known to be from an invariant location, 1153 // replace this instruction. 1154 // 1155 // If either the dominating load or the current load are invariant, then 1156 // we can assume the current load loads the same value as the dominating 1157 // load. 1158 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 1159 if (InVal.DefInst != nullptr && 1160 InVal.MatchingId == MemInst.getMatchingId() && 1161 // We don't yet handle removing loads with ordering of any kind. 1162 !MemInst.isVolatile() && MemInst.isUnordered() && 1163 // We can't replace an atomic load with one which isn't also atomic. 1164 InVal.IsAtomic >= MemInst.isAtomic() && 1165 (isOperatingOnInvariantMemAt(&Inst, InVal.Generation) || 1166 isSameMemGeneration(InVal.Generation, CurrentGeneration, 1167 InVal.DefInst, &Inst))) { 1168 Value *Op = getOrCreateResult(InVal.DefInst, Inst.getType()); 1169 if (Op != nullptr) { 1170 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst 1171 << " to: " << *InVal.DefInst << '\n'); 1172 if (!DebugCounter::shouldExecute(CSECounter)) { 1173 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1174 continue; 1175 } 1176 if (!Inst.use_empty()) 1177 Inst.replaceAllUsesWith(Op); 1178 salvageKnowledge(&Inst, &AC); 1179 removeMSSA(Inst); 1180 Inst.eraseFromParent(); 1181 Changed = true; 1182 ++NumCSELoad; 1183 continue; 1184 } 1185 } 1186 1187 // Otherwise, remember that we have this instruction. 1188 AvailableLoads.insert(MemInst.getPointerOperand(), 1189 LoadValue(&Inst, CurrentGeneration, 1190 MemInst.getMatchingId(), 1191 MemInst.isAtomic())); 1192 LastStore = nullptr; 1193 continue; 1194 } 1195 1196 // If this instruction may read from memory or throw (and potentially read 1197 // from memory in the exception handler), forget LastStore. Load/store 1198 // intrinsics will indicate both a read and a write to memory. The target 1199 // may override this (e.g. so that a store intrinsic does not read from 1200 // memory, and thus will be treated the same as a regular store for 1201 // commoning purposes). 1202 if ((Inst.mayReadFromMemory() || Inst.mayThrow()) && 1203 !(MemInst.isValid() && !MemInst.mayReadFromMemory())) 1204 LastStore = nullptr; 1205 1206 // If this is a read-only call, process it. 1207 if (CallValue::canHandle(&Inst)) { 1208 // If we have an available version of this call, and if it is the right 1209 // generation, replace this instruction. 1210 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst); 1211 if (InVal.first != nullptr && 1212 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first, 1213 &Inst)) { 1214 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst 1215 << " to: " << *InVal.first << '\n'); 1216 if (!DebugCounter::shouldExecute(CSECounter)) { 1217 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1218 continue; 1219 } 1220 if (!Inst.use_empty()) 1221 Inst.replaceAllUsesWith(InVal.first); 1222 salvageKnowledge(&Inst, &AC); 1223 removeMSSA(Inst); 1224 Inst.eraseFromParent(); 1225 Changed = true; 1226 ++NumCSECall; 1227 continue; 1228 } 1229 1230 // Otherwise, remember that we have this instruction. 1231 AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration)); 1232 continue; 1233 } 1234 1235 // A release fence requires that all stores complete before it, but does 1236 // not prevent the reordering of following loads 'before' the fence. As a 1237 // result, we don't need to consider it as writing to memory and don't need 1238 // to advance the generation. We do need to prevent DSE across the fence, 1239 // but that's handled above. 1240 if (auto *FI = dyn_cast<FenceInst>(&Inst)) 1241 if (FI->getOrdering() == AtomicOrdering::Release) { 1242 assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above"); 1243 continue; 1244 } 1245 1246 // write back DSE - If we write back the same value we just loaded from 1247 // the same location and haven't passed any intervening writes or ordering 1248 // operations, we can remove the write. The primary benefit is in allowing 1249 // the available load table to remain valid and value forward past where 1250 // the store originally was. 1251 if (MemInst.isValid() && MemInst.isStore()) { 1252 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 1253 if (InVal.DefInst && 1254 InVal.DefInst == getOrCreateResult(&Inst, InVal.DefInst->getType()) && 1255 InVal.MatchingId == MemInst.getMatchingId() && 1256 // We don't yet handle removing stores with ordering of any kind. 1257 !MemInst.isVolatile() && MemInst.isUnordered() && 1258 (isOperatingOnInvariantMemAt(&Inst, InVal.Generation) || 1259 isSameMemGeneration(InVal.Generation, CurrentGeneration, 1260 InVal.DefInst, &Inst))) { 1261 // It is okay to have a LastStore to a different pointer here if MemorySSA 1262 // tells us that the load and store are from the same memory generation. 1263 // In that case, LastStore should keep its present value since we're 1264 // removing the current store. 1265 assert((!LastStore || 1266 ParseMemoryInst(LastStore, TTI).getPointerOperand() == 1267 MemInst.getPointerOperand() || 1268 MSSA) && 1269 "can't have an intervening store if not using MemorySSA!"); 1270 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n'); 1271 if (!DebugCounter::shouldExecute(CSECounter)) { 1272 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1273 continue; 1274 } 1275 salvageKnowledge(&Inst, &AC); 1276 removeMSSA(Inst); 1277 Inst.eraseFromParent(); 1278 Changed = true; 1279 ++NumDSE; 1280 // We can avoid incrementing the generation count since we were able 1281 // to eliminate this store. 1282 continue; 1283 } 1284 } 1285 1286 // Okay, this isn't something we can CSE at all. Check to see if it is 1287 // something that could modify memory. If so, our available memory values 1288 // cannot be used so bump the generation count. 1289 if (Inst.mayWriteToMemory()) { 1290 ++CurrentGeneration; 1291 1292 if (MemInst.isValid() && MemInst.isStore()) { 1293 // We do a trivial form of DSE if there are two stores to the same 1294 // location with no intervening loads. Delete the earlier store. 1295 // At the moment, we don't remove ordered stores, but do remove 1296 // unordered atomic stores. There's no special requirement (for 1297 // unordered atomics) about removing atomic stores only in favor of 1298 // other atomic stores since we were going to execute the non-atomic 1299 // one anyway and the atomic one might never have become visible. 1300 if (LastStore) { 1301 ParseMemoryInst LastStoreMemInst(LastStore, TTI); 1302 assert(LastStoreMemInst.isUnordered() && 1303 !LastStoreMemInst.isVolatile() && 1304 "Violated invariant"); 1305 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) { 1306 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore 1307 << " due to: " << Inst << '\n'); 1308 if (!DebugCounter::shouldExecute(CSECounter)) { 1309 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1310 } else { 1311 salvageKnowledge(&Inst, &AC); 1312 removeMSSA(*LastStore); 1313 LastStore->eraseFromParent(); 1314 Changed = true; 1315 ++NumDSE; 1316 LastStore = nullptr; 1317 } 1318 } 1319 // fallthrough - we can exploit information about this store 1320 } 1321 1322 // Okay, we just invalidated anything we knew about loaded values. Try 1323 // to salvage *something* by remembering that the stored value is a live 1324 // version of the pointer. It is safe to forward from volatile stores 1325 // to non-volatile loads, so we don't have to check for volatility of 1326 // the store. 1327 AvailableLoads.insert(MemInst.getPointerOperand(), 1328 LoadValue(&Inst, CurrentGeneration, 1329 MemInst.getMatchingId(), 1330 MemInst.isAtomic())); 1331 1332 // Remember that this was the last unordered store we saw for DSE. We 1333 // don't yet handle DSE on ordered or volatile stores since we don't 1334 // have a good way to model the ordering requirement for following 1335 // passes once the store is removed. We could insert a fence, but 1336 // since fences are slightly stronger than stores in their ordering, 1337 // it's not clear this is a profitable transform. Another option would 1338 // be to merge the ordering with that of the post dominating store. 1339 if (MemInst.isUnordered() && !MemInst.isVolatile()) 1340 LastStore = &Inst; 1341 else 1342 LastStore = nullptr; 1343 } 1344 } 1345 } 1346 1347 return Changed; 1348 } 1349 1350 bool EarlyCSE::run() { 1351 // Note, deque is being used here because there is significant performance 1352 // gains over vector when the container becomes very large due to the 1353 // specific access patterns. For more information see the mailing list 1354 // discussion on this: 1355 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 1356 std::deque<StackNode *> nodesToProcess; 1357 1358 bool Changed = false; 1359 1360 // Process the root node. 1361 nodesToProcess.push_back(new StackNode( 1362 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls, 1363 CurrentGeneration, DT.getRootNode(), 1364 DT.getRootNode()->begin(), DT.getRootNode()->end())); 1365 1366 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it."); 1367 1368 // Process the stack. 1369 while (!nodesToProcess.empty()) { 1370 // Grab the first item off the stack. Set the current generation, remove 1371 // the node from the stack, and process it. 1372 StackNode *NodeToProcess = nodesToProcess.back(); 1373 1374 // Initialize class members. 1375 CurrentGeneration = NodeToProcess->currentGeneration(); 1376 1377 // Check if the node needs to be processed. 1378 if (!NodeToProcess->isProcessed()) { 1379 // Process the node. 1380 Changed |= processNode(NodeToProcess->node()); 1381 NodeToProcess->childGeneration(CurrentGeneration); 1382 NodeToProcess->process(); 1383 } else if (NodeToProcess->childIter() != NodeToProcess->end()) { 1384 // Push the next child onto the stack. 1385 DomTreeNode *child = NodeToProcess->nextChild(); 1386 nodesToProcess.push_back( 1387 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants, 1388 AvailableCalls, NodeToProcess->childGeneration(), 1389 child, child->begin(), child->end())); 1390 } else { 1391 // It has been processed, and there are no more children to process, 1392 // so delete it and pop it off the stack. 1393 delete NodeToProcess; 1394 nodesToProcess.pop_back(); 1395 } 1396 } // while (!nodes...) 1397 1398 return Changed; 1399 } 1400 1401 PreservedAnalyses EarlyCSEPass::run(Function &F, 1402 FunctionAnalysisManager &AM) { 1403 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1404 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 1405 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1406 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1407 auto *MSSA = 1408 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr; 1409 1410 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA); 1411 1412 if (!CSE.run()) 1413 return PreservedAnalyses::all(); 1414 1415 PreservedAnalyses PA; 1416 PA.preserveSet<CFGAnalyses>(); 1417 PA.preserve<GlobalsAA>(); 1418 if (UseMemorySSA) 1419 PA.preserve<MemorySSAAnalysis>(); 1420 return PA; 1421 } 1422 1423 namespace { 1424 1425 /// A simple and fast domtree-based CSE pass. 1426 /// 1427 /// This pass does a simple depth-first walk over the dominator tree, 1428 /// eliminating trivially redundant instructions and using instsimplify to 1429 /// canonicalize things as it goes. It is intended to be fast and catch obvious 1430 /// cases so that instcombine and other passes are more effective. It is 1431 /// expected that a later pass of GVN will catch the interesting/hard cases. 1432 template<bool UseMemorySSA> 1433 class EarlyCSELegacyCommonPass : public FunctionPass { 1434 public: 1435 static char ID; 1436 1437 EarlyCSELegacyCommonPass() : FunctionPass(ID) { 1438 if (UseMemorySSA) 1439 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry()); 1440 else 1441 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry()); 1442 } 1443 1444 bool runOnFunction(Function &F) override { 1445 if (skipFunction(F)) 1446 return false; 1447 1448 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1449 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1450 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1451 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1452 auto *MSSA = 1453 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr; 1454 1455 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA); 1456 1457 return CSE.run(); 1458 } 1459 1460 void getAnalysisUsage(AnalysisUsage &AU) const override { 1461 AU.addRequired<AssumptionCacheTracker>(); 1462 AU.addRequired<DominatorTreeWrapperPass>(); 1463 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1464 AU.addRequired<TargetTransformInfoWrapperPass>(); 1465 if (UseMemorySSA) { 1466 AU.addRequired<AAResultsWrapperPass>(); 1467 AU.addRequired<MemorySSAWrapperPass>(); 1468 AU.addPreserved<MemorySSAWrapperPass>(); 1469 } 1470 AU.addPreserved<GlobalsAAWrapperPass>(); 1471 AU.addPreserved<AAResultsWrapperPass>(); 1472 AU.setPreservesCFG(); 1473 } 1474 }; 1475 1476 } // end anonymous namespace 1477 1478 using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>; 1479 1480 template<> 1481 char EarlyCSELegacyPass::ID = 0; 1482 1483 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false, 1484 false) 1485 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1486 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1487 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1488 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1489 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false) 1490 1491 using EarlyCSEMemSSALegacyPass = 1492 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>; 1493 1494 template<> 1495 char EarlyCSEMemSSALegacyPass::ID = 0; 1496 1497 FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) { 1498 if (UseMemorySSA) 1499 return new EarlyCSEMemSSALegacyPass(); 1500 else 1501 return new EarlyCSELegacyPass(); 1502 } 1503 1504 INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa", 1505 "Early CSE w/ MemorySSA", false, false) 1506 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1507 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1508 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1509 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1510 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1511 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1512 INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa", 1513 "Early CSE w/ MemorySSA", false, false) 1514