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/BranchProbabilityInfo.h" 182 #include "llvm/Analysis/GuardUtils.h" 183 #include "llvm/Analysis/LoopInfo.h" 184 #include "llvm/Analysis/LoopPass.h" 185 #include "llvm/Analysis/ScalarEvolution.h" 186 #include "llvm/Analysis/ScalarEvolutionExpander.h" 187 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 188 #include "llvm/IR/Function.h" 189 #include "llvm/IR/GlobalValue.h" 190 #include "llvm/IR/IntrinsicInst.h" 191 #include "llvm/IR/Module.h" 192 #include "llvm/IR/PatternMatch.h" 193 #include "llvm/Pass.h" 194 #include "llvm/Support/Debug.h" 195 #include "llvm/Transforms/Scalar.h" 196 #include "llvm/Transforms/Utils/Local.h" 197 #include "llvm/Transforms/Utils/LoopUtils.h" 198 199 #define DEBUG_TYPE "loop-predication" 200 201 STATISTIC(TotalConsidered, "Number of guards considered"); 202 STATISTIC(TotalWidened, "Number of checks widened"); 203 204 using namespace llvm; 205 206 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation", 207 cl::Hidden, cl::init(true)); 208 209 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop", 210 cl::Hidden, cl::init(true)); 211 212 static cl::opt<bool> 213 SkipProfitabilityChecks("loop-predication-skip-profitability-checks", 214 cl::Hidden, cl::init(false)); 215 216 // This is the scale factor for the latch probability. We use this during 217 // profitability analysis to find other exiting blocks that have a much higher 218 // probability of exiting the loop instead of loop exiting via latch. 219 // This value should be greater than 1 for a sane profitability check. 220 static cl::opt<float> LatchExitProbabilityScale( 221 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0), 222 cl::desc("scale factor for the latch probability. Value should be greater " 223 "than 1. Lower values are ignored")); 224 225 static cl::opt<bool> PredicateWidenableBranchGuards( 226 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden, 227 cl::desc("Whether or not we should predicate guards " 228 "expressed as widenable branches to deoptimize blocks"), 229 cl::init(true)); 230 231 namespace { 232 class LoopPredication { 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 ScalarEvolution *SE; 250 BranchProbabilityInfo *BPI; 251 252 Loop *L; 253 const DataLayout *DL; 254 BasicBlock *Preheader; 255 LoopICmp LatchCheck; 256 257 bool isSupportedStep(const SCEV* Step); 258 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) { 259 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0), 260 ICI->getOperand(1)); 261 } 262 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 263 Value *RHS); 264 265 Optional<LoopICmp> parseLoopLatchICmp(); 266 267 bool CanExpand(const SCEV* S); 268 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder, 269 ICmpInst::Predicate Pred, const SCEV *LHS, 270 const SCEV *RHS); 271 272 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, 273 IRBuilder<> &Builder); 274 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, 275 LoopICmp RangeCheck, 276 SCEVExpander &Expander, 277 IRBuilder<> &Builder); 278 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, 279 LoopICmp RangeCheck, 280 SCEVExpander &Expander, 281 IRBuilder<> &Builder); 282 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition, 283 SCEVExpander &Expander, IRBuilder<> &Builder); 284 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); 285 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander); 286 // If the loop always exits through another block in the loop, we should not 287 // predicate based on the latch check. For example, the latch check can be a 288 // very coarse grained check and there can be more fine grained exit checks 289 // within the loop. We identify such unprofitable loops through BPI. 290 bool isLoopProfitableToPredicate(); 291 292 // When the IV type is wider than the range operand type, we can still do loop 293 // predication, by generating SCEVs for the range and latch that are of the 294 // same type. We achieve this by generating a SCEV truncate expression for the 295 // latch IV. This is done iff truncation of the IV is a safe operation, 296 // without loss of information. 297 // Another way to achieve this is by generating a wider type SCEV for the 298 // range check operand, however, this needs a more involved check that 299 // operands do not overflow. This can lead to loss of information when the 300 // range operand is of the form: add i32 %offset, %iv. We need to prove that 301 // sext(x + y) is same as sext(x) + sext(y). 302 // This function returns true if we can safely represent the IV type in 303 // the RangeCheckType without loss of information. 304 bool isSafeToTruncateWideIVType(Type *RangeCheckType); 305 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do 306 // so. 307 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType); 308 309 public: 310 LoopPredication(ScalarEvolution *SE, BranchProbabilityInfo *BPI) 311 : SE(SE), BPI(BPI){}; 312 bool runOnLoop(Loop *L); 313 }; 314 315 class LoopPredicationLegacyPass : public LoopPass { 316 public: 317 static char ID; 318 LoopPredicationLegacyPass() : LoopPass(ID) { 319 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); 320 } 321 322 void getAnalysisUsage(AnalysisUsage &AU) const override { 323 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 324 getLoopAnalysisUsage(AU); 325 } 326 327 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 328 if (skipLoop(L)) 329 return false; 330 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 331 BranchProbabilityInfo &BPI = 332 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 333 LoopPredication LP(SE, &BPI); 334 return LP.runOnLoop(L); 335 } 336 }; 337 338 char LoopPredicationLegacyPass::ID = 0; 339 } // end namespace llvm 340 341 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", 342 "Loop predication", false, false) 343 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 344 INITIALIZE_PASS_DEPENDENCY(LoopPass) 345 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", 346 "Loop predication", false, false) 347 348 Pass *llvm::createLoopPredicationPass() { 349 return new LoopPredicationLegacyPass(); 350 } 351 352 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, 353 LoopStandardAnalysisResults &AR, 354 LPMUpdater &U) { 355 const auto &FAM = 356 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 357 Function *F = L.getHeader()->getParent(); 358 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); 359 LoopPredication LP(&AR.SE, BPI); 360 if (!LP.runOnLoop(&L)) 361 return PreservedAnalyses::all(); 362 363 return getLoopPassPreservedAnalyses(); 364 } 365 366 Optional<LoopPredication::LoopICmp> 367 LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS, 368 Value *RHS) { 369 const SCEV *LHSS = SE->getSCEV(LHS); 370 if (isa<SCEVCouldNotCompute>(LHSS)) 371 return None; 372 const SCEV *RHSS = SE->getSCEV(RHS); 373 if (isa<SCEVCouldNotCompute>(RHSS)) 374 return None; 375 376 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV 377 if (SE->isLoopInvariant(LHSS, L)) { 378 std::swap(LHS, RHS); 379 std::swap(LHSS, RHSS); 380 Pred = ICmpInst::getSwappedPredicate(Pred); 381 } 382 383 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); 384 if (!AR || AR->getLoop() != L) 385 return None; 386 387 return LoopICmp(Pred, AR, RHSS); 388 } 389 390 Value *LoopPredication::expandCheck(SCEVExpander &Expander, 391 IRBuilder<> &Builder, 392 ICmpInst::Predicate Pred, const SCEV *LHS, 393 const SCEV *RHS) { 394 Type *Ty = LHS->getType(); 395 assert(Ty == RHS->getType() && "expandCheck operands have different types?"); 396 397 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS)) 398 return Builder.getTrue(); 399 400 Instruction *InsertAt = &*Builder.GetInsertPoint(); 401 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt); 402 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt); 403 return Builder.CreateICmp(Pred, LHSV, RHSV); 404 } 405 406 Optional<LoopPredication::LoopICmp> 407 LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) { 408 409 auto *LatchType = LatchCheck.IV->getType(); 410 if (RangeCheckType == LatchType) 411 return LatchCheck; 412 // For now, bail out if latch type is narrower than range type. 413 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType)) 414 return None; 415 if (!isSafeToTruncateWideIVType(RangeCheckType)) 416 return None; 417 // We can now safely identify the truncated version of the IV and limit for 418 // RangeCheckType. 419 LoopICmp NewLatchCheck; 420 NewLatchCheck.Pred = LatchCheck.Pred; 421 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>( 422 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType)); 423 if (!NewLatchCheck.IV) 424 return None; 425 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType); 426 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType 427 << "can be represented as range check type:" 428 << *RangeCheckType << "\n"); 429 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n"); 430 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n"); 431 return NewLatchCheck; 432 } 433 434 bool LoopPredication::isSupportedStep(const SCEV* Step) { 435 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop); 436 } 437 438 bool LoopPredication::CanExpand(const SCEV* S) { 439 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE); 440 } 441 442 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop( 443 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck, 444 SCEVExpander &Expander, IRBuilder<> &Builder) { 445 auto *Ty = RangeCheck.IV->getType(); 446 // Generate the widened condition for the forward loop: 447 // guardStart u< guardLimit && 448 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart 449 // where <pred> depends on the latch condition predicate. See the file 450 // header comment for the reasoning. 451 // guardLimit - guardStart + latchStart - 1 452 const SCEV *GuardStart = RangeCheck.IV->getStart(); 453 const SCEV *GuardLimit = RangeCheck.Limit; 454 const SCEV *LatchStart = LatchCheck.IV->getStart(); 455 const SCEV *LatchLimit = LatchCheck.Limit; 456 457 // guardLimit - guardStart + latchStart - 1 458 const SCEV *RHS = 459 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart), 460 SE->getMinusSCEV(LatchStart, SE->getOne(Ty))); 461 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) || 462 !CanExpand(LatchLimit) || !CanExpand(RHS)) { 463 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 464 return None; 465 } 466 auto LimitCheckPred = 467 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 468 469 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n"); 470 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n"); 471 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n"); 472 473 auto *LimitCheck = 474 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS); 475 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred, 476 GuardStart, GuardLimit); 477 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 478 } 479 480 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop( 481 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck, 482 SCEVExpander &Expander, IRBuilder<> &Builder) { 483 auto *Ty = RangeCheck.IV->getType(); 484 const SCEV *GuardStart = RangeCheck.IV->getStart(); 485 const SCEV *GuardLimit = RangeCheck.Limit; 486 const SCEV *LatchLimit = LatchCheck.Limit; 487 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) || 488 !CanExpand(LatchLimit)) { 489 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n"); 490 return None; 491 } 492 // The decrement of the latch check IV should be the same as the 493 // rangeCheckIV. 494 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE); 495 if (RangeCheck.IV != PostDecLatchCheckIV) { 496 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: " 497 << *PostDecLatchCheckIV 498 << " and RangeCheckIV: " << *RangeCheck.IV << "\n"); 499 return None; 500 } 501 502 // Generate the widened condition for CountDownLoop: 503 // guardStart u< guardLimit && 504 // latchLimit <pred> 1. 505 // See the header comment for reasoning of the checks. 506 auto LimitCheckPred = 507 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred); 508 auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT, 509 GuardStart, GuardLimit); 510 auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, 511 SE->getOne(Ty)); 512 return Builder.CreateAnd(FirstIterationCheck, LimitCheck); 513 } 514 515 /// If ICI can be widened to a loop invariant condition emits the loop 516 /// invariant condition in the loop preheader and return it, otherwise 517 /// returns None. 518 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, 519 SCEVExpander &Expander, 520 IRBuilder<> &Builder) { 521 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); 522 LLVM_DEBUG(ICI->dump()); 523 524 // parseLoopStructure guarantees that the latch condition is: 525 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=. 526 // We are looking for the range checks of the form: 527 // i u< guardLimit 528 auto RangeCheck = parseLoopICmp(ICI); 529 if (!RangeCheck) { 530 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 531 return None; 532 } 533 LLVM_DEBUG(dbgs() << "Guard check:\n"); 534 LLVM_DEBUG(RangeCheck->dump()); 535 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) { 536 LLVM_DEBUG(dbgs() << "Unsupported range check predicate(" 537 << RangeCheck->Pred << ")!\n"); 538 return None; 539 } 540 auto *RangeCheckIV = RangeCheck->IV; 541 if (!RangeCheckIV->isAffine()) { 542 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n"); 543 return None; 544 } 545 auto *Step = RangeCheckIV->getStepRecurrence(*SE); 546 // We cannot just compare with latch IV step because the latch and range IVs 547 // may have different types. 548 if (!isSupportedStep(Step)) { 549 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n"); 550 return None; 551 } 552 auto *Ty = RangeCheckIV->getType(); 553 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty); 554 if (!CurrLatchCheckOpt) { 555 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check " 556 "corresponding to range type: " 557 << *Ty << "\n"); 558 return None; 559 } 560 561 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt; 562 // At this point, the range and latch step should have the same type, but need 563 // not have the same value (we support both 1 and -1 steps). 564 assert(Step->getType() == 565 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() && 566 "Range and latch steps should be of same type!"); 567 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) { 568 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n"); 569 return None; 570 } 571 572 if (Step->isOne()) 573 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck, 574 Expander, Builder); 575 else { 576 assert(Step->isAllOnesValue() && "Step should be -1!"); 577 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck, 578 Expander, Builder); 579 } 580 } 581 582 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks, 583 Value *Condition, 584 SCEVExpander &Expander, 585 IRBuilder<> &Builder) { 586 unsigned NumWidened = 0; 587 // The guard condition is expected to be in form of: 588 // cond1 && cond2 && cond3 ... 589 // Iterate over subconditions looking for icmp conditions which can be 590 // widened across loop iterations. Widening these conditions remember the 591 // resulting list of subconditions in Checks vector. 592 SmallVector<Value *, 4> Worklist(1, Condition); 593 SmallPtrSet<Value *, 4> Visited; 594 do { 595 Value *Condition = Worklist.pop_back_val(); 596 if (!Visited.insert(Condition).second) 597 continue; 598 599 Value *LHS, *RHS; 600 using namespace llvm::PatternMatch; 601 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { 602 Worklist.push_back(LHS); 603 Worklist.push_back(RHS); 604 continue; 605 } 606 607 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { 608 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, 609 Builder)) { 610 Checks.push_back(NewRangeCheck.getValue()); 611 NumWidened++; 612 continue; 613 } 614 } 615 616 // Save the condition as is if we can't widen it 617 Checks.push_back(Condition); 618 } while (!Worklist.empty()); 619 return NumWidened; 620 } 621 622 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, 623 SCEVExpander &Expander) { 624 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 625 LLVM_DEBUG(Guard->dump()); 626 627 TotalConsidered++; 628 SmallVector<Value *, 4> Checks; 629 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); 630 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander, 631 Builder); 632 if (NumWidened == 0) 633 return false; 634 635 TotalWidened += NumWidened; 636 637 // Emit the new guard condition 638 Builder.SetInsertPoint(Guard); 639 Value *LastCheck = nullptr; 640 for (auto *Check : Checks) 641 if (!LastCheck) 642 LastCheck = Check; 643 else 644 LastCheck = Builder.CreateAnd(LastCheck, Check); 645 auto *OldCond = Guard->getOperand(0); 646 Guard->setOperand(0, LastCheck); 647 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 648 649 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 650 return true; 651 } 652 653 bool LoopPredication::widenWidenableBranchGuardConditions( 654 BranchInst *Guard, SCEVExpander &Expander) { 655 assert(isGuardAsWidenableBranch(Guard) && "Must be!"); 656 LLVM_DEBUG(dbgs() << "Processing guard:\n"); 657 LLVM_DEBUG(Guard->dump()); 658 659 TotalConsidered++; 660 SmallVector<Value *, 4> Checks; 661 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); 662 Value *Condition = nullptr, *WidenableCondition = nullptr; 663 BasicBlock *GBB = nullptr, *DBB = nullptr; 664 parseWidenableBranch(Guard, Condition, WidenableCondition, GBB, DBB); 665 unsigned NumWidened = collectChecks(Checks, Condition, Expander, Builder); 666 if (NumWidened == 0) 667 return false; 668 669 TotalWidened += NumWidened; 670 671 // Emit the new guard condition 672 Builder.SetInsertPoint(Guard); 673 Value *LastCheck = nullptr; 674 for (auto *Check : Checks) 675 if (!LastCheck) 676 LastCheck = Check; 677 else 678 LastCheck = Builder.CreateAnd(LastCheck, Check); 679 // Make sure that the check contains widenable condition and therefore can be 680 // further widened. 681 LastCheck = Builder.CreateAnd(LastCheck, WidenableCondition); 682 auto *OldCond = Guard->getOperand(0); 683 Guard->setOperand(0, LastCheck); 684 assert(isGuardAsWidenableBranch(Guard) && 685 "Stopped being a guard after transform?"); 686 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 687 688 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); 689 return true; 690 } 691 692 Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() { 693 using namespace PatternMatch; 694 695 BasicBlock *LoopLatch = L->getLoopLatch(); 696 if (!LoopLatch) { 697 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n"); 698 return None; 699 } 700 701 ICmpInst::Predicate Pred; 702 Value *LHS, *RHS; 703 BasicBlock *TrueDest, *FalseDest; 704 705 if (!match(LoopLatch->getTerminator(), 706 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest, 707 FalseDest))) { 708 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n"); 709 return None; 710 } 711 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) && 712 "One of the latch's destinations must be the header"); 713 if (TrueDest != L->getHeader()) 714 Pred = ICmpInst::getInversePredicate(Pred); 715 716 auto Result = parseLoopICmp(Pred, LHS, RHS); 717 if (!Result) { 718 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); 719 return None; 720 } 721 722 // Check affine first, so if it's not we don't try to compute the step 723 // recurrence. 724 if (!Result->IV->isAffine()) { 725 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n"); 726 return None; 727 } 728 729 auto *Step = Result->IV->getStepRecurrence(*SE); 730 if (!isSupportedStep(Step)) { 731 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n"); 732 return None; 733 } 734 735 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) { 736 if (Step->isOne()) { 737 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT && 738 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE; 739 } else { 740 assert(Step->isAllOnesValue() && "Step should be -1!"); 741 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT && 742 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE; 743 } 744 }; 745 746 if (IsUnsupportedPredicate(Step, Result->Pred)) { 747 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred 748 << ")!\n"); 749 return None; 750 } 751 return Result; 752 } 753 754 // Returns true if its safe to truncate the IV to RangeCheckType. 755 bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) { 756 if (!EnableIVTruncation) 757 return false; 758 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) > 759 DL->getTypeSizeInBits(RangeCheckType) && 760 "Expected latch check IV type to be larger than range check operand " 761 "type!"); 762 // The start and end values of the IV should be known. This is to guarantee 763 // that truncating the wide type will not lose information. 764 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit); 765 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart()); 766 if (!Limit || !Start) 767 return false; 768 // This check makes sure that the IV does not change sign during loop 769 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE, 770 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the 771 // IV wraps around, and the truncation of the IV would lose the range of 772 // iterations between 2^32 and 2^64. 773 bool Increasing; 774 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing)) 775 return false; 776 // The active bits should be less than the bits in the RangeCheckType. This 777 // guarantees that truncating the latch check to RangeCheckType is a safe 778 // operation. 779 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType); 780 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize && 781 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize; 782 } 783 784 bool LoopPredication::isLoopProfitableToPredicate() { 785 if (SkipProfitabilityChecks || !BPI) 786 return true; 787 788 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges; 789 L->getExitEdges(ExitEdges); 790 // If there is only one exiting edge in the loop, it is always profitable to 791 // predicate the loop. 792 if (ExitEdges.size() == 1) 793 return true; 794 795 // Calculate the exiting probabilities of all exiting edges from the loop, 796 // starting with the LatchExitProbability. 797 // Heuristic for profitability: If any of the exiting blocks' probability of 798 // exiting the loop is larger than exiting through the latch block, it's not 799 // profitable to predicate the loop. 800 auto *LatchBlock = L->getLoopLatch(); 801 assert(LatchBlock && "Should have a single latch at this point!"); 802 auto *LatchTerm = LatchBlock->getTerminator(); 803 assert(LatchTerm->getNumSuccessors() == 2 && 804 "expected to be an exiting block with 2 succs!"); 805 unsigned LatchBrExitIdx = 806 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0; 807 BranchProbability LatchExitProbability = 808 BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx); 809 810 // Protect against degenerate inputs provided by the user. Providing a value 811 // less than one, can invert the definition of profitable loop predication. 812 float ScaleFactor = LatchExitProbabilityScale; 813 if (ScaleFactor < 1) { 814 LLVM_DEBUG( 815 dbgs() 816 << "Ignored user setting for loop-predication-latch-probability-scale: " 817 << LatchExitProbabilityScale << "\n"); 818 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n"); 819 ScaleFactor = 1.0; 820 } 821 const auto LatchProbabilityThreshold = 822 LatchExitProbability * ScaleFactor; 823 824 for (const auto &ExitEdge : ExitEdges) { 825 BranchProbability ExitingBlockProbability = 826 BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second); 827 // Some exiting edge has higher probability than the latch exiting edge. 828 // No longer profitable to predicate. 829 if (ExitingBlockProbability > LatchProbabilityThreshold) 830 return false; 831 } 832 // Using BPI, we have concluded that the most probable way to exit from the 833 // loop is through the latch (or there's no profile information and all 834 // exits are equally likely). 835 return true; 836 } 837 838 bool LoopPredication::runOnLoop(Loop *Loop) { 839 L = Loop; 840 841 LLVM_DEBUG(dbgs() << "Analyzing "); 842 LLVM_DEBUG(L->dump()); 843 844 Module *M = L->getHeader()->getModule(); 845 846 // There is nothing to do if the module doesn't use guards 847 auto *GuardDecl = 848 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); 849 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty(); 850 auto *WCDecl = M->getFunction( 851 Intrinsic::getName(Intrinsic::experimental_widenable_condition)); 852 bool HasWidenableConditions = 853 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty(); 854 if (!HasIntrinsicGuards && !HasWidenableConditions) 855 return false; 856 857 DL = &M->getDataLayout(); 858 859 Preheader = L->getLoopPreheader(); 860 if (!Preheader) 861 return false; 862 863 auto LatchCheckOpt = parseLoopLatchICmp(); 864 if (!LatchCheckOpt) 865 return false; 866 LatchCheck = *LatchCheckOpt; 867 868 LLVM_DEBUG(dbgs() << "Latch check:\n"); 869 LLVM_DEBUG(LatchCheck.dump()); 870 871 if (!isLoopProfitableToPredicate()) { 872 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n"); 873 return false; 874 } 875 // Collect all the guards into a vector and process later, so as not 876 // to invalidate the instruction iterator. 877 SmallVector<IntrinsicInst *, 4> Guards; 878 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches; 879 for (const auto BB : L->blocks()) { 880 for (auto &I : *BB) 881 if (isGuard(&I)) 882 Guards.push_back(cast<IntrinsicInst>(&I)); 883 if (PredicateWidenableBranchGuards && 884 isGuardAsWidenableBranch(BB->getTerminator())) 885 GuardsAsWidenableBranches.push_back( 886 cast<BranchInst>(BB->getTerminator())); 887 } 888 889 if (Guards.empty() && GuardsAsWidenableBranches.empty()) 890 return false; 891 892 SCEVExpander Expander(*SE, *DL, "loop-predication"); 893 894 bool Changed = false; 895 for (auto *Guard : Guards) 896 Changed |= widenGuardConditions(Guard, Expander); 897 for (auto *Guard : GuardsAsWidenableBranches) 898 Changed |= widenWidenableBranchGuardConditions(Guard, Expander); 899 900 return Changed; 901 } 902