1 //===-- LoopPredication.cpp - Guard based loop predication 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 // The LoopPredication pass tries to convert loop variant range checks to loop 10 // invariant by widening checks across loop iterations. For example, it will 11 // convert 12 // 13 // for (i = 0; i < n; i++) { 14 // guard(i < len); 15 // ... 16 // } 17 // 18 // to 19 // 20 // for (i = 0; i < n; i++) { 21 // guard(n - 1 < len); 22 // ... 23 // } 24 // 25 // After this transformation the condition of the guard is loop invariant, so 26 // loop-unswitch can later unswitch the loop by this condition which basically 27 // predicates the loop by the widened condition: 28 // 29 // if (n - 1 < len) 30 // for (i = 0; i < n; i++) { 31 // ... 32 // } 33 // else 34 // deoptimize 35 // 36 // It's tempting to rely on SCEV here, but it has proven to be problematic. 37 // Generally the facts SCEV provides about the increment step of add 38 // recurrences are true if the backedge of the loop is taken, which implicitly 39 // assumes that the guard doesn't fail. Using these facts to optimize the 40 // guard results in a circular logic where the guard is optimized under the 41 // assumption that it never fails. 42 // 43 // For example, in the loop below the induction variable will be marked as nuw 44 // basing on the guard. Basing on nuw the guard predicate will be considered 45 // monotonic. Given a monotonic condition it's tempting to replace the induction 46 // variable in the condition with its value on the last iteration. But this 47 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop. 48 // 49 // for (int i = b; i != e; i++) 50 // guard(i u< len) 51 // 52 // One of the ways to reason about this problem is to use an inductive proof 53 // approach. Given the loop: 54 // 55 // if (B(0)) { 56 // do { 57 // I = PHI(0, I.INC) 58 // I.INC = I + Step 59 // guard(G(I)); 60 // } while (B(I)); 61 // } 62 // 63 // where B(x) and G(x) are predicates that map integers to booleans, we want a 64 // loop invariant expression M such the following program has the same semantics 65 // as the above: 66 // 67 // if (B(0)) { 68 // do { 69 // I = PHI(0, I.INC) 70 // I.INC = I + Step 71 // guard(G(0) && M); 72 // } while (B(I)); 73 // } 74 // 75 // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step) 76 // 77 // Informal proof that the transformation above is correct: 78 // 79 // By the definition of guards we can rewrite the guard condition to: 80 // G(I) && G(0) && M 81 // 82 // Let's prove that for each iteration of the loop: 83 // G(0) && M => G(I) 84 // And the condition above can be simplified to G(Start) && M. 85 // 86 // Induction base. 87 // G(0) && M => G(0) 88 // 89 // Induction step. Assuming G(0) && M => G(I) on the subsequent 90 // iteration: 91 // 92 // B(I) is true because it's the backedge condition. 93 // G(I) is true because the backedge is guarded by this condition. 94 // 95 // So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step). 96 // 97 // Note that we can use anything stronger than M, i.e. any condition which 98 // implies M. 99 // 100 // When S = 1 (i.e. forward iterating loop), the transformation is supported 101 // when: 102 // * The loop has a single latch with the condition of the form: 103 // B(X) = latchStart + X <pred> latchLimit, 104 // where <pred> is u<, u<=, s<, or s<=. 105 // * The guard condition is of the form 106 // G(X) = guardStart + X u< guardLimit 107 // 108 // For the ult latch comparison case M is: 109 // forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit => 110 // guardStart + X + 1 u< guardLimit 111 // 112 // The only way the antecedent can be true and the consequent can be false is 113 // if 114 // X == guardLimit - 1 - guardStart 115 // (and guardLimit is non-zero, but we won't use this latter fact). 116 // If X == guardLimit - 1 - guardStart then the second half of the antecedent is 117 // latchStart + guardLimit - 1 - guardStart u< latchLimit 118 // and its negation is 119 // latchStart + guardLimit - 1 - guardStart u>= latchLimit 120 // 121 // In other words, if 122 // latchLimit u<= latchStart + guardLimit - 1 - guardStart 123 // then: 124 // (the ranges below are written in ConstantRange notation, where [A, B) is the 125 // set for (I = A; I != B; I++ /*maywrap*/) yield(I);) 126 // 127 // forall X . guardStart + X u< guardLimit && 128 // latchStart + X u< latchLimit => 129 // guardStart + X + 1 u< guardLimit 130 // == forall X . guardStart + X u< guardLimit && 131 // latchStart + X u< latchStart + guardLimit - 1 - guardStart => 132 // guardStart + X + 1 u< guardLimit 133 // == forall X . (guardStart + X) in [0, guardLimit) && 134 // (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) => 135 // (guardStart + X + 1) in [0, guardLimit) 136 // == forall X . X in [-guardStart, guardLimit - guardStart) && 137 // X in [-latchStart, guardLimit - 1 - guardStart) => 138 // X in [-guardStart - 1, guardLimit - guardStart - 1) 139 // == true 140 // 141 // So the widened condition is: 142 // guardStart u< guardLimit && 143 // latchStart + guardLimit - 1 - guardStart u>= latchLimit 144 // Similarly for ule condition the widened condition is: 145 // guardStart u< guardLimit && 146 // latchStart + guardLimit - 1 - guardStart u> latchLimit 147 // For slt condition the widened condition is: 148 // guardStart u< guardLimit && 149 // latchStart + guardLimit - 1 - guardStart s>= latchLimit 150 // For sle condition the widened condition is: 151 // guardStart u< guardLimit && 152 // latchStart + guardLimit - 1 - guardStart s> latchLimit 153 // 154 // When S = -1 (i.e. reverse iterating loop), the transformation is supported 155 // when: 156 // * The loop has a single latch with the condition of the form: 157 // B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=. 158 // * The guard condition is of the form 159 // G(X) = X - 1 u< guardLimit 160 // 161 // For the ugt latch comparison case M is: 162 // forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit 163 // 164 // The only way the antecedent can be true and the consequent can be false is if 165 // X == 1. 166 // If X == 1 then the second half of the antecedent is 167 // 1 u> latchLimit, and its negation is latchLimit u>= 1. 168 // 169 // So the widened condition is: 170 // guardStart u< guardLimit && latchLimit u>= 1. 171 // Similarly for sgt condition the widened condition is: 172 // guardStart u< guardLimit && latchLimit s>= 1. 173 // For uge condition the widened condition is: 174 // guardStart u< guardLimit && latchLimit u> 1. 175 // For sge condition the widened condition is: 176 // guardStart u< guardLimit && latchLimit s> 1. 177 //===----------------------------------------------------------------------===// 178 179 #include "llvm/Transforms/Scalar/LoopPredication.h" 180 #include "llvm/ADT/Statistic.h" 181 #include "llvm/Analysis/AliasAnalysis.h" 182 #include "llvm/Analysis/BranchProbabilityInfo.h" 183 #include "llvm/Analysis/GuardUtils.h" 184 #include "llvm/Analysis/LoopInfo.h" 185 #include "llvm/Analysis/LoopPass.h" 186 #include "llvm/Analysis/ScalarEvolution.h" 187 #include "llvm/Analysis/ScalarEvolutionExpander.h" 188 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 189 #include "llvm/IR/Function.h" 190 #include "llvm/IR/GlobalValue.h" 191 #include "llvm/IR/IntrinsicInst.h" 192 #include "llvm/IR/Module.h" 193 #include "llvm/IR/PatternMatch.h" 194 #include "llvm/Pass.h" 195 #include "llvm/Support/Debug.h" 196 #include "llvm/Transforms/Scalar.h" 197 #include "llvm/Transforms/Utils/Local.h" 198 #include "llvm/Transforms/Utils/LoopUtils.h" 199 200 #define DEBUG_TYPE "loop-predication" 201 202 STATISTIC(TotalConsidered, "Number of guards considered"); 203 STATISTIC(TotalWidened, "Number of checks widened"); 204 205 using namespace llvm; 206 207 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation", 208 cl::Hidden, cl::init(true)); 209 210 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop", 211 cl::Hidden, cl::init(true)); 212 213 static cl::opt<bool> 214 SkipProfitabilityChecks("loop-predication-skip-profitability-checks", 215 cl::Hidden, cl::init(false)); 216 217 // This is the scale factor for the latch probability. We use this during 218 // profitability analysis to find other exiting blocks that have a much higher 219 // probability of exiting the loop instead of loop exiting via latch. 220 // This value should be greater than 1 for a sane profitability check. 221 static cl::opt<float> LatchExitProbabilityScale( 222 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), 223 cl::desc("scale factor for the latch probability. Value should be greater " 224 "than 1. Lower values are ignored")); 225 226 static cl::opt<bool> PredicateWidenableBranchGuards( 227 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden, 228 cl::desc("Whether or not we should predicate guards " 229 "expressed as widenable branches to deoptimize blocks"), 230 cl::init(true)); 231 232 namespace { 233 /// Represents an induction variable check: 234 /// icmp Pred, <induction variable>, <loop invariant limit> 235 struct LoopICmp { 236 ICmpInst::Predicate Pred; 237 const SCEVAddRecExpr *IV; 238 const SCEV *Limit; 239 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, 240 const SCEV *Limit) 241 : Pred(Pred), IV(IV), Limit(Limit) {} 242 LoopICmp() {} 243 void dump() { 244 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV 245 << ", Limit = " << *Limit << "\n"; 246 } 247 }; 248 249 class LoopPredication { 250 AliasAnalysis *AA; 251 ScalarEvolution *SE; 252 BranchProbabilityInfo *BPI; 253 254 Loop *L; 255 const DataLayout *DL; 256 BasicBlock *Preheader; 257 LoopICmp LatchCheck; 258 259 bool isSupportedStep(const SCEV* Step); 260 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI); 261 Optional<LoopICmp> parseLoopLatchICmp(); 262 263 /// Return an insertion point suitable for inserting a safe to speculate 264 /// instruction whose only user will be 'User' which has operands 'Ops'. A 265 /// trivial result would be the at the User itself, but we try to return a 266 /// loop invariant location if possible. 267 Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops); 268 /// Same as above, *except* that this uses the SCEV definition of invariant 269 /// which is that an expression *can be made* invariant via SCEVExpander. 270 /// Thus, this version is only suitable for finding an insert point to be be 271 /// passed to SCEVExpander! 272 Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops); 273 274 /// Return true if the value is known to produce a single fixed value across 275 /// all iterations on which it executes. Note that this does not imply 276 /// speculation safety. That must be established seperately. 277 bool isLoopInvariantValue(const SCEV* S); 278 279 Value *expandCheck(SCEVExpander &Expander, Instruction *Guard, 280 ICmpInst::Predicate Pred, const SCEV *LHS, 281 const SCEV *RHS); 282 283 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 284 Instruction *Guard); 285 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, 286 LoopICmp RangeCheck, 287 SCEVExpander &Expander, 288 Instruction *Guard); 289 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, 290 LoopICmp RangeCheck, 291 SCEVExpander &Expander, 292 Instruction *Guard); 293 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition, 294 SCEVExpander &Expander, Instruction *Guard); 295 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 296 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander); 297 // If the loop always exits through another block in the loop, we should not 298 // predicate based on the latch check. For example, the latch check can be a 299 // very coarse grained check and there can be more fine grained exit checks 300 // within the loop. We identify such unprofitable loops through BPI. 301 bool isLoopProfitableToPredicate(); 302 303 // When the IV type is wider than the range operand type, we can still do loop 304 // predication, by generating SCEVs for the range and latch that are of the 305 // same type. We achieve this by generating a SCEV truncate expression for the 306 // latch IV. This is done iff truncation of the IV is a safe operation, 307 // without loss of information. 308 // Another way to achieve this is by generating a wider type SCEV for the 309 // range check operand, however, this needs a more involved check that 310 // operands do not overflow. This can lead to loss of information when the 311 // range operand is of the form: add i32 %offset, %iv. We need to prove that 312 // sext(x + y) is same as sext(x) + sext(y). 313 // This function returns true if we can safely represent the IV type in 314 // the RangeCheckType without loss of information. 315 bool isSafeToTruncateWideIVType(Type *RangeCheckType); 316 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do 317 // so. 318 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType); 319 320 public: 321 LoopPredication(AliasAnalysis *AA, ScalarEvolution *SE, 322 BranchProbabilityInfo *BPI) 323 : AA(AA), SE(SE), BPI(BPI){}; 324 bool runOnLoop(Loop *L); 325 }; 326 327 class LoopPredicationLegacyPass : public LoopPass { 328 public: 329 static char ID; 330 LoopPredicationLegacyPass() : LoopPass(ID) { 331 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 332 } 333 334 void getAnalysisUsage(AnalysisUsage &AU) const override { 335 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 336 getLoopAnalysisUsage(AU); 337 } 338 339 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 340 if (skipLoop(L)) 341 return false; 342 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 343 BranchProbabilityInfo &BPI = 344 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 345 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 346 LoopPredication LP(AA, SE, &BPI); 347 return LP.runOnLoop(L); 348 } 349 }; 350 351 char LoopPredicationLegacyPass::ID = 0; 352 } // end namespace llvm 353 354 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 355 "Loop predication", false, false) 356 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 357 INITIALIZE_PASS_DEPENDENCY(LoopPass) 358 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 359 "Loop predication", false, false) 360 361 Pass *llvm::createLoopPredicationPass() { 362 return new LoopPredicationLegacyPass(); 363 } 364 365 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 366 LoopStandardAnalysisResults &AR, 367 LPMUpdater &U) { 368 const auto &FAM = 369 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 370 Function *F = L.getHeader()->getParent(); 371 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); 372 LoopPredication LP(&AR.AA, &AR.SE, BPI); 373 if (!LP.runOnLoop(&L)) 374 return PreservedAnalyses::all(); 375 376 return getLoopPassPreservedAnalyses(); 377 } 378 379 Optional<LoopICmp> 380 LoopPredication::parseLoopICmp(ICmpInst *ICI) { 381 auto Pred = ICI->getPredicate(); 382 auto *LHS = ICI->getOperand(0); 383 auto *RHS = ICI->getOperand(1); 384 385 const SCEV *LHSS = SE->getSCEV(LHS); 386 if (isa<SCEVCouldNotCompute>(LHSS)) 387 return None; 388 const SCEV *RHSS = SE->getSCEV(RHS); 389 if (isa<SCEVCouldNotCompute>(RHSS)) 390 return None; 391 392 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV 393 if (SE->isLoopInvariant(LHSS, L)) { 394 std::swap(LHS, RHS); 395 std::swap(LHSS, RHSS); 396 Pred = ICmpInst::getSwappedPredicate(Pred); 397 } 398 399 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); 400 if (!AR || AR->getLoop() != L) 401 return None; 402 403 return LoopICmp(Pred, AR, RHSS); 404 } 405 406 Value *LoopPredication::expandCheck(SCEVExpander &Expander, 407 Instruction *Guard, 408 ICmpInst::Predicate Pred, const SCEV *LHS, 409 const SCEV *RHS) { 410 Type *Ty = LHS->getType(); 411 assert(Ty == RHS->getType() && "expandCheck operands have different types?"); 412 413 if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) { 414 IRBuilder<> Builder(Guard); 415 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS)) 416 return Builder.getTrue(); 417 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred), 418 LHS, RHS)) 419 return Builder.getFalse(); 420 } 421 422 Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS})); 423 Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS})); 424 IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV})); 425 return Builder.CreateICmp(Pred, LHSV, RHSV); 426 } 427 428 Optional<LoopICmp> 429 LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) { 430 431 auto *LatchType = LatchCheck.IV->getType(); 432 if (RangeCheckType == LatchType) 433 return LatchCheck; 434 // For now, bail out if latch type is narrower than range type. 435 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType)) 436 return None; 437 if (!isSafeToTruncateWideIVType(RangeCheckType)) 438 return None; 439 // We can now safely identify the truncated version of the IV and limit for 440 // RangeCheckType. 441 LoopICmp NewLatchCheck; 442 NewLatchCheck.Pred = LatchCheck.Pred; 443 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>( 444 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType)); 445 if (!NewLatchCheck.IV) 446 return None; 447 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType); 448 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType 449 << "can be represented as range check type:" 450 << *RangeCheckType << "\n"); 451 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n"); 452 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n"); 453 return NewLatchCheck; 454 } 455 456 bool LoopPredication::isSupportedStep(const SCEV* Step) { 457 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop); 458 } 459 460 Instruction *LoopPredication::findInsertPt(Instruction *Use, 461 ArrayRef<Value*> Ops) { 462 for (Value *Op : Ops) 463 if (!L->isLoopInvariant(Op)) 464 return Use; 465 return Preheader->getTerminator(); 466 } 467 468 Instruction *LoopPredication::findInsertPt(Instruction *Use, 469 ArrayRef<const SCEV*> Ops) { 470 // Subtlety: SCEV considers things to be invariant if the value produced is 471 // the same across iterations. This is not the same as being able to 472 // evaluate outside the loop, which is what we actually need here. 473 for (const SCEV *Op : Ops) 474 if (!SE->isLoopInvariant(Op, L) || 475 !isSafeToExpandAt(Op, Preheader->getTerminator(), *SE)) 476 return Use; 477 return Preheader->getTerminator(); 478 } 479 480 bool LoopPredication::isLoopInvariantValue(const SCEV* S) { 481 // Handling expressions which produce invariant results, but *haven't* yet 482 // been removed from the loop serves two important purposes. 483 // 1) Most importantly, it resolves a pass ordering cycle which would 484 // otherwise need us to iteration licm, loop-predication, and either 485 // loop-unswitch or loop-peeling to make progress on examples with lots of 486 // predicable range checks in a row. (Since, in the general case, we can't 487 // hoist the length checks until the dominating checks have been discharged 488 // as we can't prove doing so is safe.) 489 // 2) As a nice side effect, this exposes the value of peeling or unswitching 490 // much more obviously in the IR. Otherwise, the cost modeling for other 491 // transforms would end up needing to duplicate all of this logic to model a 492 // check which becomes predictable based on a modeled peel or unswitch. 493 // 494 // The cost of doing so in the worst case is an extra fill from the stack in 495 // the loop to materialize the loop invariant test value instead of checking 496 // against the original IV which is presumable in a register inside the loop. 497 // Such cases are presumably rare, and hint at missing oppurtunities for 498 // other passes. 499 500 if (SE->isLoopInvariant(S, L)) 501 // Note: This the SCEV variant, so the original Value* may be within the 502 // loop even though SCEV has proven it is loop invariant. 503 return true; 504 505 // Handle a particular important case which SCEV doesn't yet know about which 506 // shows up in range checks on arrays with immutable lengths. 507 // TODO: This should be sunk inside SCEV. 508 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) 509 if (const auto *LI = dyn_cast<LoadInst>(U->getValue())) 510 if (LI->isUnordered() && L->hasLoopInvariantOperands(LI)) 511 if (AA->pointsToConstantMemory(LI->getOperand(0)) || 512 LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr) 513 return true; 514 return false; 515 } 516 517 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop( 518 LoopICmp LatchCheck, LoopICmp RangeCheck, 519 SCEVExpander &Expander, Instruction *Guard) { 520 auto *Ty = RangeCheck.IV->getType(); 521 // Generate the widened condition for the forward loop: 522 // guardStart u< guardLimit && 523 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart 524 // where <pred> depends on the latch condition predicate. See the file 525 // header comment for the reasoning. 526 // guardLimit - guardStart + latchStart - 1 527 const SCEV *GuardStart = RangeCheck.IV->getStart(); 528 const SCEV *GuardLimit = RangeCheck.Limit; 529 const SCEV *LatchStart = LatchCheck.IV->getStart(); 530 const SCEV *LatchLimit = LatchCheck.Limit; 531 // Subtlety: We need all the values to be *invariant* across all iterations, 532 // but we only need to check expansion safety for those which *aren't* 533 // already guaranteed to dominate the guard. 534 if (!isLoopInvariantValue(GuardStart) || 535 !isLoopInvariantValue(GuardLimit) || 536 !isLoopInvariantValue(LatchStart) || 537 !isLoopInvariantValue(LatchLimit)) { 538 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 539 return None; 540 } 541 if (!isSafeToExpandAt(LatchStart, Guard, *SE) || 542 !isSafeToExpandAt(LatchLimit, Guard, *SE)) { 543 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 544 return None; 545 } 546 547 // guardLimit - guardStart + latchStart - 1 548 const SCEV *RHS = 549 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart), 550 SE->getMinusSCEV(LatchStart, SE->getOne(Ty))); 551 auto LimitCheckPred = 552 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 553 554 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n"); 555 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n"); 556 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n"); 557 558 auto *LimitCheck = 559 expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS); 560 auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred, 561 GuardStart, GuardLimit); 562 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck})); 563 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 564 } 565 566 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop( 567 LoopICmp LatchCheck, LoopICmp RangeCheck, 568 SCEVExpander &Expander, Instruction *Guard) { 569 auto *Ty = RangeCheck.IV->getType(); 570 const SCEV *GuardStart = RangeCheck.IV->getStart(); 571 const SCEV *GuardLimit = RangeCheck.Limit; 572 const SCEV *LatchStart = LatchCheck.IV->getStart(); 573 const SCEV *LatchLimit = LatchCheck.Limit; 574 // Subtlety: We need all the values to be *invariant* across all iterations, 575 // but we only need to check expansion safety for those which *aren't* 576 // already guaranteed to dominate the guard. 577 if (!isLoopInvariantValue(GuardStart) || 578 !isLoopInvariantValue(GuardLimit) || 579 !isLoopInvariantValue(LatchStart) || 580 !isLoopInvariantValue(LatchLimit)) { 581 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 582 return None; 583 } 584 if (!isSafeToExpandAt(LatchStart, Guard, *SE) || 585 !isSafeToExpandAt(LatchLimit, Guard, *SE)) { 586 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 587 return None; 588 } 589 // The decrement of the latch check IV should be the same as the 590 // rangeCheckIV. 591 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE); 592 if (RangeCheck.IV != PostDecLatchCheckIV) { 593 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: " 594 << *PostDecLatchCheckIV 595 << " and RangeCheckIV: " << *RangeCheck.IV << "\n"); 596 return None; 597 } 598 599 // Generate the widened condition for CountDownLoop: 600 // guardStart u< guardLimit && 601 // latchLimit <pred> 1. 602 // See the header comment for reasoning of the checks. 603 auto LimitCheckPred = 604 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 605 auto *FirstIterationCheck = expandCheck(Expander, Guard, 606 ICmpInst::ICMP_ULT, 607 GuardStart, GuardLimit); 608 auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, 609 SE->getOne(Ty)); 610 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck})); 611 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 612 } 613 614 static void normalizePredicate(ScalarEvolution *SE, Loop *L, 615 LoopICmp& RC) { 616 // LFTR canonicalizes checks to the ICMP_NE form instead of an ULT/SLT form. 617 // Normalize back to the ULT/SLT form for ease of handling. 618 if (RC.Pred == ICmpInst::ICMP_NE && 619 RC.IV->getStepRecurrence(*SE)->isOne() && 620 SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit)) 621 RC.Pred = ICmpInst::ICMP_ULT; 622 } 623 624 625 /// If ICI can be widened to a loop invariant condition emits the loop 626 /// invariant condition in the loop preheader and return it, otherwise 627 /// returns None. 628 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 629 SCEVExpander &Expander, 630 Instruction *Guard) { 631 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 632 LLVM_DEBUG(ICI->dump()); 633 634 // parseLoopStructure guarantees that the latch condition is: 635 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=. 636 // We are looking for the range checks of the form: 637 // i u< guardLimit 638 auto RangeCheck = parseLoopICmp(ICI); 639 if (!RangeCheck) { 640 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 641 return None; 642 } 643 LLVM_DEBUG(dbgs() << "Guard check:\n"); 644 LLVM_DEBUG(RangeCheck->dump()); 645 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { 646 LLVM_DEBUG(dbgs() << "Unsupported range check predicate(" 647 << RangeCheck->Pred << ")!\n"); 648 return None; 649 } 650 auto *RangeCheckIV = RangeCheck->IV; 651 if (!RangeCheckIV->isAffine()) { 652 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n"); 653 return None; 654 } 655 auto *Step = RangeCheckIV->getStepRecurrence(*SE); 656 // We cannot just compare with latch IV step because the latch and range IVs 657 // may have different types. 658 if (!isSupportedStep(Step)) { 659 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n"); 660 return None; 661 } 662 auto *Ty = RangeCheckIV->getType(); 663 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty); 664 if (!CurrLatchCheckOpt) { 665 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check " 666 "corresponding to range type: " 667 << *Ty << "\n"); 668 return None; 669 } 670 671 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt; 672 // At this point, the range and latch step should have the same type, but need 673 // not have the same value (we support both 1 and -1 steps). 674 assert(Step->getType() == 675 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() && 676 "Range and latch steps should be of same type!"); 677 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) { 678 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n"); 679 return None; 680 } 681 682 if (Step->isOne()) 683 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck, 684 Expander, Guard); 685 else { 686 assert(Step->isAllOnesValue() && "Step should be -1!"); 687 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck, 688 Expander, Guard); 689 } 690 } 691 692 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks, 693 Value *Condition, 694 SCEVExpander &Expander, 695 Instruction *Guard) { 696 unsigned NumWidened = 0; 697 // The guard condition is expected to be in form of: 698 // cond1 && cond2 && cond3 ... 699 // Iterate over subconditions looking for icmp conditions which can be 700 // widened across loop iterations. Widening these conditions remember the 701 // resulting list of subconditions in Checks vector. 702 SmallVector<Value *, 4> Worklist(1, Condition); 703 SmallPtrSet<Value *, 4> Visited; 704 Value *WideableCond = nullptr; 705 do { 706 Value *Condition = Worklist.pop_back_val(); 707 if (!Visited.insert(Condition).second) 708 continue; 709 710 Value *LHS, *RHS; 711 using namespace llvm::PatternMatch; 712 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 713 Worklist.push_back(LHS); 714 Worklist.push_back(RHS); 715 continue; 716 } 717 718 if (match(Condition, 719 m_Intrinsic<Intrinsic::experimental_widenable_condition>())) { 720 // Pick any, we don't care which 721 WideableCond = Condition; 722 continue; 723 } 724 725 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 726 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, 727 Guard)) { 728 Checks.push_back(NewRangeCheck.getValue()); 729 NumWidened++; 730 continue; 731 } 732 } 733 734 // Save the condition as is if we can't widen it 735 Checks.push_back(Condition); 736 } while (!Worklist.empty()); 737 // At the moment, our matching logic for wideable conditions implicitly 738 // assumes we preserve the form: (br (and Cond, WC())). FIXME 739 // Note that if there were multiple calls to wideable condition in the 740 // traversal, we only need to keep one, and which one is arbitrary. 741 if (WideableCond) 742 Checks.push_back(WideableCond); 743 return NumWidened; 744 } 745 746 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 747 SCEVExpander &Expander) { 748 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 749 LLVM_DEBUG(Guard->dump()); 750 751 TotalConsidered++; 752 SmallVector<Value *, 4> Checks; 753 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander, 754 Guard); 755 if (NumWidened == 0) 756 return false; 757 758 TotalWidened += NumWidened; 759 760 // Emit the new guard condition 761 IRBuilder<> Builder(findInsertPt(Guard, Checks)); 762 Value *LastCheck = nullptr; 763 for (auto *Check : Checks) 764 if (!LastCheck) 765 LastCheck = Check; 766 else 767 LastCheck = Builder.CreateAnd(LastCheck, Check); 768 auto *OldCond = Guard->getOperand(0); 769 Guard->setOperand(0, LastCheck); 770 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 771 772 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 773 return true; 774 } 775 776 bool LoopPredication::widenWidenableBranchGuardConditions( 777 BranchInst *BI, SCEVExpander &Expander) { 778 assert(isGuardAsWidenableBranch(BI) && "Must be!"); 779 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 780 LLVM_DEBUG(BI->dump()); 781 782 TotalConsidered++; 783 SmallVector<Value *, 4> Checks; 784 unsigned NumWidened = collectChecks(Checks, BI->getCondition(), 785 Expander, BI); 786 if (NumWidened == 0) 787 return false; 788 789 TotalWidened += NumWidened; 790 791 // Emit the new guard condition 792 IRBuilder<> Builder(findInsertPt(BI, Checks)); 793 Value *LastCheck = nullptr; 794 for (auto *Check : Checks) 795 if (!LastCheck) 796 LastCheck = Check; 797 else 798 LastCheck = Builder.CreateAnd(LastCheck, Check); 799 auto *OldCond = BI->getCondition(); 800 BI->setCondition(LastCheck); 801 assert(isGuardAsWidenableBranch(BI) && 802 "Stopped being a guard after transform?"); 803 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 804 805 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 806 return true; 807 } 808 809 Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() { 810 using namespace PatternMatch; 811 812 BasicBlock *LoopLatch = L->getLoopLatch(); 813 if (!LoopLatch) { 814 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); 815 return None; 816 } 817 818 auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator()); 819 if (!BI) { 820 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n"); 821 return None; 822 } 823 BasicBlock *TrueDest = BI->getSuccessor(0); 824 BasicBlock *FalseDest = BI->getSuccessor(1); 825 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) && 826 "One of the latch's destinations must be the header"); 827 828 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition()); 829 if (!ICI || !BI->isConditional()) { 830 LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n"); 831 return None; 832 } 833 auto Result = parseLoopICmp(ICI); 834 if (!Result) { 835 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 836 return None; 837 } 838 839 if (TrueDest != L->getHeader()) 840 Result->Pred = ICmpInst::getInversePredicate(Result->Pred); 841 842 // Check affine first, so if it's not we don't try to compute the step 843 // recurrence. 844 if (!Result->IV->isAffine()) { 845 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n"); 846 return None; 847 } 848 849 auto *Step = Result->IV->getStepRecurrence(*SE); 850 if (!isSupportedStep(Step)) { 851 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); 852 return None; 853 } 854 855 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) { 856 if (Step->isOne()) { 857 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT && 858 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE; 859 } else { 860 assert(Step->isAllOnesValue() && "Step should be -1!"); 861 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT && 862 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE; 863 } 864 }; 865 866 normalizePredicate(SE, L, *Result); 867 if (IsUnsupportedPredicate(Step, Result->Pred)) { 868 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred 869 << ")!\n"); 870 return None; 871 } 872 873 return Result; 874 } 875 876 // Returns true if its safe to truncate the IV to RangeCheckType. 877 bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) { 878 if (!EnableIVTruncation) 879 return false; 880 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) > 881 DL->getTypeSizeInBits(RangeCheckType) && 882 "Expected latch check IV type to be larger than range check operand " 883 "type!"); 884 // The start and end values of the IV should be known. This is to guarantee 885 // that truncating the wide type will not lose information. 886 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit); 887 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart()); 888 if (!Limit || !Start) 889 return false; 890 // This check makes sure that the IV does not change sign during loop 891 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE, 892 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the 893 // IV wraps around, and the truncation of the IV would lose the range of 894 // iterations between 2^32 and 2^64. 895 bool Increasing; 896 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing)) 897 return false; 898 // The active bits should be less than the bits in the RangeCheckType. This 899 // guarantees that truncating the latch check to RangeCheckType is a safe 900 // operation. 901 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType); 902 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize && 903 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize; 904 } 905 906 bool LoopPredication::isLoopProfitableToPredicate() { 907 if (SkipProfitabilityChecks || !BPI) 908 return true; 909 910 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges; 911 L->getExitEdges(ExitEdges); 912 // If there is only one exiting edge in the loop, it is always profitable to 913 // predicate the loop. 914 if (ExitEdges.size() == 1) 915 return true; 916 917 // Calculate the exiting probabilities of all exiting edges from the loop, 918 // starting with the LatchExitProbability. 919 // Heuristic for profitability: If any of the exiting blocks' probability of 920 // exiting the loop is larger than exiting through the latch block, it's not 921 // profitable to predicate the loop. 922 auto *LatchBlock = L->getLoopLatch(); 923 assert(LatchBlock && "Should have a single latch at this point!"); 924 auto *LatchTerm = LatchBlock->getTerminator(); 925 assert(LatchTerm->getNumSuccessors() == 2 && 926 "expected to be an exiting block with 2 succs!"); 927 unsigned LatchBrExitIdx = 928 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0; 929 BranchProbability LatchExitProbability = 930 BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx); 931 932 // Protect against degenerate inputs provided by the user. Providing a value 933 // less than one, can invert the definition of profitable loop predication. 934 float ScaleFactor = LatchExitProbabilityScale; 935 if (ScaleFactor < 1) { 936 LLVM_DEBUG( 937 dbgs() 938 << "Ignored user setting for loop-predication-latch-probability-scale: " 939 << LatchExitProbabilityScale << "\n"); 940 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n"); 941 ScaleFactor = 1.0; 942 } 943 const auto LatchProbabilityThreshold = 944 LatchExitProbability * ScaleFactor; 945 946 for (const auto &ExitEdge : ExitEdges) { 947 BranchProbability ExitingBlockProbability = 948 BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second); 949 // Some exiting edge has higher probability than the latch exiting edge. 950 // No longer profitable to predicate. 951 if (ExitingBlockProbability > LatchProbabilityThreshold) 952 return false; 953 } 954 // Using BPI, we have concluded that the most probable way to exit from the 955 // loop is through the latch (or there's no profile information and all 956 // exits are equally likely). 957 return true; 958 } 959 960 bool LoopPredication::runOnLoop(Loop *Loop) { 961 L = Loop; 962 963 LLVM_DEBUG(dbgs() << "Analyzing "); 964 LLVM_DEBUG(L->dump()); 965 966 Module *M = L->getHeader()->getModule(); 967 968 // There is nothing to do if the module doesn't use guards 969 auto *GuardDecl = 970 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 971 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty(); 972 auto *WCDecl = M->getFunction( 973 Intrinsic::getName(Intrinsic::experimental_widenable_condition)); 974 bool HasWidenableConditions = 975 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty(); 976 if (!HasIntrinsicGuards && !HasWidenableConditions) 977 return false; 978 979 DL = &M->getDataLayout(); 980 981 Preheader = L->getLoopPreheader(); 982 if (!Preheader) 983 return false; 984 985 auto LatchCheckOpt = parseLoopLatchICmp(); 986 if (!LatchCheckOpt) 987 return false; 988 LatchCheck = *LatchCheckOpt; 989 990 LLVM_DEBUG(dbgs() << "Latch check:\n"); 991 LLVM_DEBUG(LatchCheck.dump()); 992 993 if (!isLoopProfitableToPredicate()) { 994 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n"); 995 return false; 996 } 997 // Collect all the guards into a vector and process later, so as not 998 // to invalidate the instruction iterator. 999 SmallVector<IntrinsicInst *, 4> Guards; 1000 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches; 1001 for (const auto BB : L->blocks()) { 1002 for (auto &I : *BB) 1003 if (isGuard(&I)) 1004 Guards.push_back(cast<IntrinsicInst>(&I)); 1005 if (PredicateWidenableBranchGuards && 1006 isGuardAsWidenableBranch(BB->getTerminator())) 1007 GuardsAsWidenableBranches.push_back( 1008 cast<BranchInst>(BB->getTerminator())); 1009 } 1010 1011 if (Guards.empty() && GuardsAsWidenableBranches.empty()) 1012 return false; 1013 1014 SCEVExpander Expander(*SE, *DL, "loop-predication"); 1015 1016 bool Changed = false; 1017 for (auto *Guard : Guards) 1018 Changed |= widenGuardConditions(Guard, Expander); 1019 for (auto *Guard : GuardsAsWidenableBranches) 1020 Changed |= widenWidenableBranchGuardConditions(Guard, Expander); 1021 1022 return Changed; 1023 } 1024