1 //===- InductiveRangeCheckElimination.cpp - -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The InductiveRangeCheckElimination pass splits a loop's iteration space into 11 // three disjoint ranges. It does that in a way such that the loop running in 12 // the middle loop provably does not need range checks. As an example, it will 13 // convert 14 // 15 // len = < known positive > 16 // for (i = 0; i < n; i++) { 17 // if (0 <= i && i < len) { 18 // do_something(); 19 // } else { 20 // throw_out_of_bounds(); 21 // } 22 // } 23 // 24 // to 25 // 26 // len = < known positive > 27 // limit = smin(n, len) 28 // // no first segment 29 // for (i = 0; i < limit; i++) { 30 // if (0 <= i && i < len) { // this check is fully redundant 31 // do_something(); 32 // } else { 33 // throw_out_of_bounds(); 34 // } 35 // } 36 // for (i = limit; i < n; i++) { 37 // if (0 <= i && i < len) { 38 // do_something(); 39 // } else { 40 // throw_out_of_bounds(); 41 // } 42 // } 43 // 44 //===----------------------------------------------------------------------===// 45 46 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h" 47 #include "llvm/ADT/APInt.h" 48 #include "llvm/ADT/ArrayRef.h" 49 #include "llvm/ADT/None.h" 50 #include "llvm/ADT/Optional.h" 51 #include "llvm/ADT/SmallPtrSet.h" 52 #include "llvm/ADT/SmallVector.h" 53 #include "llvm/ADT/StringRef.h" 54 #include "llvm/ADT/Twine.h" 55 #include "llvm/Analysis/BranchProbabilityInfo.h" 56 #include "llvm/Analysis/LoopAnalysisManager.h" 57 #include "llvm/Analysis/LoopInfo.h" 58 #include "llvm/Analysis/LoopPass.h" 59 #include "llvm/Analysis/ScalarEvolution.h" 60 #include "llvm/Analysis/ScalarEvolutionExpander.h" 61 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 62 #include "llvm/IR/BasicBlock.h" 63 #include "llvm/IR/CFG.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DerivedTypes.h" 66 #include "llvm/IR/Dominators.h" 67 #include "llvm/IR/Function.h" 68 #include "llvm/IR/IRBuilder.h" 69 #include "llvm/IR/InstrTypes.h" 70 #include "llvm/IR/Instructions.h" 71 #include "llvm/IR/Metadata.h" 72 #include "llvm/IR/Module.h" 73 #include "llvm/IR/PatternMatch.h" 74 #include "llvm/IR/Type.h" 75 #include "llvm/IR/Use.h" 76 #include "llvm/IR/User.h" 77 #include "llvm/IR/Value.h" 78 #include "llvm/Pass.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/raw_ostream.h" 86 #include "llvm/Transforms/Scalar.h" 87 #include "llvm/Transforms/Utils/Cloning.h" 88 #include "llvm/Transforms/Utils/LoopSimplify.h" 89 #include "llvm/Transforms/Utils/LoopUtils.h" 90 #include "llvm/Transforms/Utils/ValueMapper.h" 91 #include <algorithm> 92 #include <cassert> 93 #include <iterator> 94 #include <limits> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 using namespace llvm::PatternMatch; 100 101 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, 102 cl::init(64)); 103 104 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, 105 cl::init(false)); 106 107 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden, 108 cl::init(false)); 109 110 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", 111 cl::Hidden, cl::init(10)); 112 113 static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks", 114 cl::Hidden, cl::init(false)); 115 116 static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch", 117 cl::Hidden, cl::init(true)); 118 119 static const char *ClonedLoopTag = "irce.loop.clone"; 120 121 #define DEBUG_TYPE "irce" 122 123 namespace { 124 125 /// An inductive range check is conditional branch in a loop with 126 /// 127 /// 1. a very cold successor (i.e. the branch jumps to that successor very 128 /// rarely) 129 /// 130 /// and 131 /// 132 /// 2. a condition that is provably true for some contiguous range of values 133 /// taken by the containing loop's induction variable. 134 /// 135 class InductiveRangeCheck { 136 // Classifies a range check 137 enum RangeCheckKind : unsigned { 138 // Range check of the form "0 <= I". 139 RANGE_CHECK_LOWER = 1, 140 141 // Range check of the form "I < L" where L is known positive. 142 RANGE_CHECK_UPPER = 2, 143 144 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER 145 // conditions. 146 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER, 147 148 // Unrecognized range check condition. 149 RANGE_CHECK_UNKNOWN = (unsigned)-1 150 }; 151 152 static StringRef rangeCheckKindToStr(RangeCheckKind); 153 154 const SCEV *Begin = nullptr; 155 const SCEV *Step = nullptr; 156 const SCEV *End = nullptr; 157 Use *CheckUse = nullptr; 158 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN; 159 bool IsSigned = true; 160 161 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI, 162 ScalarEvolution &SE, Value *&Index, 163 Value *&Length, bool &IsSigned); 164 165 static void 166 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse, 167 SmallVectorImpl<InductiveRangeCheck> &Checks, 168 SmallPtrSetImpl<Value *> &Visited); 169 170 public: 171 const SCEV *getBegin() const { return Begin; } 172 const SCEV *getStep() const { return Step; } 173 const SCEV *getEnd() const { return End; } 174 bool isSigned() const { return IsSigned; } 175 176 void print(raw_ostream &OS) const { 177 OS << "InductiveRangeCheck:\n"; 178 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n"; 179 OS << " Begin: "; 180 Begin->print(OS); 181 OS << " Step: "; 182 Step->print(OS); 183 OS << " End: "; 184 End->print(OS); 185 OS << "\n CheckUse: "; 186 getCheckUse()->getUser()->print(OS); 187 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n"; 188 } 189 190 LLVM_DUMP_METHOD 191 void dump() { 192 print(dbgs()); 193 } 194 195 Use *getCheckUse() const { return CheckUse; } 196 197 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If 198 /// R.getEnd() le R.getBegin(), then R denotes the empty range. 199 200 class Range { 201 const SCEV *Begin; 202 const SCEV *End; 203 204 public: 205 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { 206 assert(Begin->getType() == End->getType() && "ill-typed range!"); 207 } 208 209 Type *getType() const { return Begin->getType(); } 210 const SCEV *getBegin() const { return Begin; } 211 const SCEV *getEnd() const { return End; } 212 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const { 213 if (Begin == End) 214 return true; 215 if (IsSigned) 216 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End); 217 else 218 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End); 219 } 220 }; 221 222 /// This is the value the condition of the branch needs to evaluate to for the 223 /// branch to take the hot successor (see (1) above). 224 bool getPassingDirection() { return true; } 225 226 /// Computes a range for the induction variable (IndVar) in which the range 227 /// check is redundant and can be constant-folded away. The induction 228 /// variable is not required to be the canonical {0,+,1} induction variable. 229 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, 230 const SCEVAddRecExpr *IndVar, 231 bool IsLatchSigned) const; 232 233 /// Parse out a set of inductive range checks from \p BI and append them to \p 234 /// Checks. 235 /// 236 /// NB! There may be conditions feeding into \p BI that aren't inductive range 237 /// checks, and hence don't end up in \p Checks. 238 static void 239 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE, 240 BranchProbabilityInfo *BPI, 241 SmallVectorImpl<InductiveRangeCheck> &Checks); 242 }; 243 244 class InductiveRangeCheckElimination { 245 ScalarEvolution &SE; 246 BranchProbabilityInfo *BPI; 247 DominatorTree &DT; 248 LoopInfo &LI; 249 250 public: 251 InductiveRangeCheckElimination(ScalarEvolution &SE, 252 BranchProbabilityInfo *BPI, DominatorTree &DT, 253 LoopInfo &LI) 254 : SE(SE), BPI(BPI), DT(DT), LI(LI) {} 255 256 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop); 257 }; 258 259 class IRCELegacyPass : public LoopPass { 260 public: 261 static char ID; 262 263 IRCELegacyPass() : LoopPass(ID) { 264 initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry()); 265 } 266 267 void getAnalysisUsage(AnalysisUsage &AU) const override { 268 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 269 getLoopAnalysisUsage(AU); 270 } 271 272 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 273 }; 274 275 } // end anonymous namespace 276 277 char IRCELegacyPass::ID = 0; 278 279 INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce", 280 "Inductive range check elimination", false, false) 281 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 282 INITIALIZE_PASS_DEPENDENCY(LoopPass) 283 INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination", 284 false, false) 285 286 StringRef InductiveRangeCheck::rangeCheckKindToStr( 287 InductiveRangeCheck::RangeCheckKind RCK) { 288 switch (RCK) { 289 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN: 290 return "RANGE_CHECK_UNKNOWN"; 291 292 case InductiveRangeCheck::RANGE_CHECK_UPPER: 293 return "RANGE_CHECK_UPPER"; 294 295 case InductiveRangeCheck::RANGE_CHECK_LOWER: 296 return "RANGE_CHECK_LOWER"; 297 298 case InductiveRangeCheck::RANGE_CHECK_BOTH: 299 return "RANGE_CHECK_BOTH"; 300 } 301 302 llvm_unreachable("unknown range check type!"); 303 } 304 305 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot 306 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set 307 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being 308 /// range checked, and set `Length` to the upper limit `Index` is being range 309 /// checked with if (and only if) the range check type is stronger or equal to 310 /// RANGE_CHECK_UPPER. 311 InductiveRangeCheck::RangeCheckKind 312 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI, 313 ScalarEvolution &SE, Value *&Index, 314 Value *&Length, bool &IsSigned) { 315 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) { 316 const SCEV *S = SE.getSCEV(V); 317 if (isa<SCEVCouldNotCompute>(S)) 318 return false; 319 320 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant && 321 SE.isKnownNonNegative(S); 322 }; 323 324 ICmpInst::Predicate Pred = ICI->getPredicate(); 325 Value *LHS = ICI->getOperand(0); 326 Value *RHS = ICI->getOperand(1); 327 328 switch (Pred) { 329 default: 330 return RANGE_CHECK_UNKNOWN; 331 332 case ICmpInst::ICMP_SLE: 333 std::swap(LHS, RHS); 334 LLVM_FALLTHROUGH; 335 case ICmpInst::ICMP_SGE: 336 IsSigned = true; 337 if (match(RHS, m_ConstantInt<0>())) { 338 Index = LHS; 339 return RANGE_CHECK_LOWER; 340 } 341 return RANGE_CHECK_UNKNOWN; 342 343 case ICmpInst::ICMP_SLT: 344 std::swap(LHS, RHS); 345 LLVM_FALLTHROUGH; 346 case ICmpInst::ICMP_SGT: 347 IsSigned = true; 348 if (match(RHS, m_ConstantInt<-1>())) { 349 Index = LHS; 350 return RANGE_CHECK_LOWER; 351 } 352 353 if (IsNonNegativeAndNotLoopVarying(LHS)) { 354 Index = RHS; 355 Length = LHS; 356 return RANGE_CHECK_UPPER; 357 } 358 return RANGE_CHECK_UNKNOWN; 359 360 case ICmpInst::ICMP_ULT: 361 std::swap(LHS, RHS); 362 LLVM_FALLTHROUGH; 363 case ICmpInst::ICMP_UGT: 364 IsSigned = false; 365 if (IsNonNegativeAndNotLoopVarying(LHS)) { 366 Index = RHS; 367 Length = LHS; 368 return RANGE_CHECK_BOTH; 369 } 370 return RANGE_CHECK_UNKNOWN; 371 } 372 373 llvm_unreachable("default clause returns!"); 374 } 375 376 void InductiveRangeCheck::extractRangeChecksFromCond( 377 Loop *L, ScalarEvolution &SE, Use &ConditionUse, 378 SmallVectorImpl<InductiveRangeCheck> &Checks, 379 SmallPtrSetImpl<Value *> &Visited) { 380 Value *Condition = ConditionUse.get(); 381 if (!Visited.insert(Condition).second) 382 return; 383 384 // TODO: Do the same for OR, XOR, NOT etc? 385 if (match(Condition, m_And(m_Value(), m_Value()))) { 386 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0), 387 Checks, Visited); 388 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1), 389 Checks, Visited); 390 return; 391 } 392 393 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition); 394 if (!ICI) 395 return; 396 397 Value *Length = nullptr, *Index; 398 bool IsSigned; 399 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned); 400 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN) 401 return; 402 403 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index)); 404 bool IsAffineIndex = 405 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); 406 407 if (!IsAffineIndex) 408 return; 409 410 const SCEV *End = nullptr; 411 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L". 412 // We can potentially do much better here. 413 if (Length) 414 End = SE.getSCEV(Length); 415 else { 416 assert(RCKind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!"); 417 // So far we can only reach this point for Signed range check. This may 418 // change in future. In this case we will need to pick Unsigned max for the 419 // unsigned range check. 420 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth(); 421 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); 422 End = SIntMax; 423 } 424 425 InductiveRangeCheck IRC; 426 IRC.End = End; 427 IRC.Begin = IndexAddRec->getStart(); 428 IRC.Step = IndexAddRec->getStepRecurrence(SE); 429 IRC.CheckUse = &ConditionUse; 430 IRC.Kind = RCKind; 431 IRC.IsSigned = IsSigned; 432 Checks.push_back(IRC); 433 } 434 435 void InductiveRangeCheck::extractRangeChecksFromBranch( 436 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI, 437 SmallVectorImpl<InductiveRangeCheck> &Checks) { 438 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) 439 return; 440 441 BranchProbability LikelyTaken(15, 16); 442 443 if (!SkipProfitabilityChecks && BPI && 444 BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken) 445 return; 446 447 SmallPtrSet<Value *, 8> Visited; 448 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0), 449 Checks, Visited); 450 } 451 452 // Add metadata to the loop L to disable loop optimizations. Callers need to 453 // confirm that optimizing loop L is not beneficial. 454 static void DisableAllLoopOptsOnLoop(Loop &L) { 455 // We do not care about any existing loopID related metadata for L, since we 456 // are setting all loop metadata to false. 457 LLVMContext &Context = L.getHeader()->getContext(); 458 // Reserve first location for self reference to the LoopID metadata node. 459 MDNode *Dummy = MDNode::get(Context, {}); 460 MDNode *DisableUnroll = MDNode::get( 461 Context, {MDString::get(Context, "llvm.loop.unroll.disable")}); 462 Metadata *FalseVal = 463 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0)); 464 MDNode *DisableVectorize = MDNode::get( 465 Context, 466 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal}); 467 MDNode *DisableLICMVersioning = MDNode::get( 468 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")}); 469 MDNode *DisableDistribution= MDNode::get( 470 Context, 471 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal}); 472 MDNode *NewLoopID = 473 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize, 474 DisableLICMVersioning, DisableDistribution}); 475 // Set operand 0 to refer to the loop id itself. 476 NewLoopID->replaceOperandWith(0, NewLoopID); 477 L.setLoopID(NewLoopID); 478 } 479 480 namespace { 481 482 // Keeps track of the structure of a loop. This is similar to llvm::Loop, 483 // except that it is more lightweight and can track the state of a loop through 484 // changing and potentially invalid IR. This structure also formalizes the 485 // kinds of loops we can deal with -- ones that have a single latch that is also 486 // an exiting block *and* have a canonical induction variable. 487 struct LoopStructure { 488 const char *Tag = ""; 489 490 BasicBlock *Header = nullptr; 491 BasicBlock *Latch = nullptr; 492 493 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th 494 // successor is `LatchExit', the exit block of the loop. 495 BranchInst *LatchBr = nullptr; 496 BasicBlock *LatchExit = nullptr; 497 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max(); 498 499 // The loop represented by this instance of LoopStructure is semantically 500 // equivalent to: 501 // 502 // intN_ty inc = IndVarIncreasing ? 1 : -1; 503 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT; 504 // 505 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase) 506 // ... body ... 507 508 Value *IndVarBase = nullptr; 509 Value *IndVarStart = nullptr; 510 Value *IndVarStep = nullptr; 511 Value *LoopExitAt = nullptr; 512 bool IndVarIncreasing = false; 513 bool IsSignedPredicate = true; 514 515 LoopStructure() = default; 516 517 template <typename M> LoopStructure map(M Map) const { 518 LoopStructure Result; 519 Result.Tag = Tag; 520 Result.Header = cast<BasicBlock>(Map(Header)); 521 Result.Latch = cast<BasicBlock>(Map(Latch)); 522 Result.LatchBr = cast<BranchInst>(Map(LatchBr)); 523 Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); 524 Result.LatchBrExitIdx = LatchBrExitIdx; 525 Result.IndVarBase = Map(IndVarBase); 526 Result.IndVarStart = Map(IndVarStart); 527 Result.IndVarStep = Map(IndVarStep); 528 Result.LoopExitAt = Map(LoopExitAt); 529 Result.IndVarIncreasing = IndVarIncreasing; 530 Result.IsSignedPredicate = IsSignedPredicate; 531 return Result; 532 } 533 534 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, 535 BranchProbabilityInfo *BPI, 536 Loop &, const char *&); 537 }; 538 539 /// This class is used to constrain loops to run within a given iteration space. 540 /// The algorithm this class implements is given a Loop and a range [Begin, 541 /// End). The algorithm then tries to break out a "main loop" out of the loop 542 /// it is given in a way that the "main loop" runs with the induction variable 543 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post 544 /// loops to run any remaining iterations. The pre loop runs any iterations in 545 /// which the induction variable is < Begin, and the post loop runs any 546 /// iterations in which the induction variable is >= End. 547 class LoopConstrainer { 548 // The representation of a clone of the original loop we started out with. 549 struct ClonedLoop { 550 // The cloned blocks 551 std::vector<BasicBlock *> Blocks; 552 553 // `Map` maps values in the clonee into values in the cloned version 554 ValueToValueMapTy Map; 555 556 // An instance of `LoopStructure` for the cloned loop 557 LoopStructure Structure; 558 }; 559 560 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for 561 // more details on what these fields mean. 562 struct RewrittenRangeInfo { 563 BasicBlock *PseudoExit = nullptr; 564 BasicBlock *ExitSelector = nullptr; 565 std::vector<PHINode *> PHIValuesAtPseudoExit; 566 PHINode *IndVarEnd = nullptr; 567 568 RewrittenRangeInfo() = default; 569 }; 570 571 // Calculated subranges we restrict the iteration space of the main loop to. 572 // See the implementation of `calculateSubRanges' for more details on how 573 // these fields are computed. `LowLimit` is None if there is no restriction 574 // on low end of the restricted iteration space of the main loop. `HighLimit` 575 // is None if there is no restriction on high end of the restricted iteration 576 // space of the main loop. 577 578 struct SubRanges { 579 Optional<const SCEV *> LowLimit; 580 Optional<const SCEV *> HighLimit; 581 }; 582 583 // A utility function that does a `replaceUsesOfWith' on the incoming block 584 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's 585 // incoming block list with `ReplaceBy'. 586 static void replacePHIBlock(PHINode *PN, BasicBlock *Block, 587 BasicBlock *ReplaceBy); 588 589 // Compute a safe set of limits for the main loop to run in -- effectively the 590 // intersection of `Range' and the iteration space of the original loop. 591 // Return None if unable to compute the set of subranges. 592 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const; 593 594 // Clone `OriginalLoop' and return the result in CLResult. The IR after 595 // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- 596 // the PHI nodes say that there is an incoming edge from `OriginalPreheader` 597 // but there is no such edge. 598 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; 599 600 // Create the appropriate loop structure needed to describe a cloned copy of 601 // `Original`. The clone is described by `VM`. 602 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent, 603 ValueToValueMapTy &VM, bool IsSubloop); 604 605 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The 606 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the 607 // iteration space is not changed. `ExitLoopAt' is assumed to be slt 608 // `OriginalHeaderCount'. 609 // 610 // If there are iterations left to execute, control is made to jump to 611 // `ContinuationBlock', otherwise they take the normal loop exit. The 612 // returned `RewrittenRangeInfo' object is populated as follows: 613 // 614 // .PseudoExit is a basic block that unconditionally branches to 615 // `ContinuationBlock'. 616 // 617 // .ExitSelector is a basic block that decides, on exit from the loop, 618 // whether to branch to the "true" exit or to `PseudoExit'. 619 // 620 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value 621 // for each PHINode in the loop header on taking the pseudo exit. 622 // 623 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate 624 // preheader because it is made to branch to the loop header only 625 // conditionally. 626 RewrittenRangeInfo 627 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, 628 Value *ExitLoopAt, 629 BasicBlock *ContinuationBlock) const; 630 631 // The loop denoted by `LS' has `OldPreheader' as its preheader. This 632 // function creates a new preheader for `LS' and returns it. 633 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, 634 const char *Tag) const; 635 636 // `ContinuationBlockAndPreheader' was the continuation block for some call to 637 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. 638 // This function rewrites the PHI nodes in `LS.Header' to start with the 639 // correct value. 640 void rewriteIncomingValuesForPHIs( 641 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, 642 const LoopConstrainer::RewrittenRangeInfo &RRI) const; 643 644 // Even though we do not preserve any passes at this time, we at least need to 645 // keep the parent loop structure consistent. The `LPPassManager' seems to 646 // verify this after running a loop pass. This function adds the list of 647 // blocks denoted by BBs to this loops parent loop if required. 648 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); 649 650 // Some global state. 651 Function &F; 652 LLVMContext &Ctx; 653 ScalarEvolution &SE; 654 DominatorTree &DT; 655 LoopInfo &LI; 656 function_ref<void(Loop *, bool)> LPMAddNewLoop; 657 658 // Information about the original loop we started out with. 659 Loop &OriginalLoop; 660 661 const SCEV *LatchTakenCount = nullptr; 662 BasicBlock *OriginalPreheader = nullptr; 663 664 // The preheader of the main loop. This may or may not be different from 665 // `OriginalPreheader'. 666 BasicBlock *MainLoopPreheader = nullptr; 667 668 // The range we need to run the main loop in. 669 InductiveRangeCheck::Range Range; 670 671 // The structure of the main loop (see comment at the beginning of this class 672 // for a definition) 673 LoopStructure MainLoopStructure; 674 675 public: 676 LoopConstrainer(Loop &L, LoopInfo &LI, 677 function_ref<void(Loop *, bool)> LPMAddNewLoop, 678 const LoopStructure &LS, ScalarEvolution &SE, 679 DominatorTree &DT, InductiveRangeCheck::Range R) 680 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), 681 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L), 682 Range(R), MainLoopStructure(LS) {} 683 684 // Entry point for the algorithm. Returns true on success. 685 bool run(); 686 }; 687 688 } // end anonymous namespace 689 690 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, 691 BasicBlock *ReplaceBy) { 692 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 693 if (PN->getIncomingBlock(i) == Block) 694 PN->setIncomingBlock(i, ReplaceBy); 695 } 696 697 static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) { 698 APInt Max = Signed ? 699 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) : 700 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth()); 701 return SE.getSignedRange(S).contains(Max) && 702 SE.getUnsignedRange(S).contains(Max); 703 } 704 705 /// Given a loop with an increasing induction variable, is it possible to 706 /// safely calculate the bounds of a new loop using the given Predicate. 707 static bool isSafeIncreasingBound(const SCEV *Start, 708 const SCEV *BoundSCEV, const SCEV *Step, 709 ICmpInst::Predicate Pred, 710 unsigned LatchBrExitIdx, 711 Loop *L, ScalarEvolution &SE) { 712 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT && 713 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT) 714 return false; 715 716 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L)) 717 return false; 718 719 DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n"); 720 DEBUG(dbgs() << "irce: Start: " << *Start); 721 DEBUG(dbgs() << "irce: Step: " << *Step); 722 DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV); 723 DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred) << "\n"); 724 DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n"); 725 726 bool IsSigned = ICmpInst::isSigned(Pred); 727 // The predicate that we need to check that the induction variable lies 728 // within bounds. 729 ICmpInst::Predicate BoundPred = 730 IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT; 731 732 if (LatchBrExitIdx == 1) 733 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV); 734 735 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1"); 736 737 const SCEV *StepMinusOne = 738 SE.getMinusSCEV(Step, SE.getOne(Step->getType())); 739 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth(); 740 APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) : 741 APInt::getMaxValue(BitWidth); 742 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne); 743 744 return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start, 745 SE.getAddExpr(BoundSCEV, Step)) && 746 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit)); 747 } 748 749 static bool CannotBeMinInLoop(const SCEV *BoundSCEV, Loop *L, 750 ScalarEvolution &SE, bool Signed) { 751 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth(); 752 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) : 753 APInt::getMinValue(BitWidth); 754 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 755 return SE.isAvailableAtLoopEntry(BoundSCEV, L) && 756 SE.isLoopEntryGuardedByCond(L, Predicate, BoundSCEV, 757 SE.getConstant(Min)); 758 } 759 760 static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2, 761 bool Signed) { 762 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN. 763 assert(SE.isKnownNonPositive(S2) && 764 "We expected the 2nd arg to be non-positive!"); 765 const SCEV *Max = SE.getConstant( 766 Signed ? APInt::getSignedMinValue( 767 cast<IntegerType>(S1->getType())->getBitWidth()) 768 : APInt::getMinValue( 769 cast<IntegerType>(S1->getType())->getBitWidth())); 770 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2); 771 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, 772 S1, CapForS1); 773 } 774 775 Optional<LoopStructure> 776 LoopStructure::parseLoopStructure(ScalarEvolution &SE, 777 BranchProbabilityInfo *BPI, Loop &L, 778 const char *&FailureReason) { 779 if (!L.isLoopSimplifyForm()) { 780 FailureReason = "loop not in LoopSimplify form"; 781 return None; 782 } 783 784 BasicBlock *Latch = L.getLoopLatch(); 785 assert(Latch && "Simplified loops only have one latch!"); 786 787 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) { 788 FailureReason = "loop has already been cloned"; 789 return None; 790 } 791 792 if (!L.isLoopExiting(Latch)) { 793 FailureReason = "no loop latch"; 794 return None; 795 } 796 797 BasicBlock *Header = L.getHeader(); 798 BasicBlock *Preheader = L.getLoopPreheader(); 799 if (!Preheader) { 800 FailureReason = "no preheader"; 801 return None; 802 } 803 804 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); 805 if (!LatchBr || LatchBr->isUnconditional()) { 806 FailureReason = "latch terminator not conditional branch"; 807 return None; 808 } 809 810 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; 811 812 BranchProbability ExitProbability = 813 BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx) 814 : BranchProbability::getZero(); 815 816 if (!SkipProfitabilityChecks && 817 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { 818 FailureReason = "short running loop, not profitable"; 819 return None; 820 } 821 822 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); 823 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { 824 FailureReason = "latch terminator branch not conditional on integral icmp"; 825 return None; 826 } 827 828 const SCEV *LatchCount = SE.getExitCount(&L, Latch); 829 if (isa<SCEVCouldNotCompute>(LatchCount)) { 830 FailureReason = "could not compute latch count"; 831 return None; 832 } 833 834 ICmpInst::Predicate Pred = ICI->getPredicate(); 835 Value *LeftValue = ICI->getOperand(0); 836 const SCEV *LeftSCEV = SE.getSCEV(LeftValue); 837 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); 838 839 Value *RightValue = ICI->getOperand(1); 840 const SCEV *RightSCEV = SE.getSCEV(RightValue); 841 842 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. 843 if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 844 if (isa<SCEVAddRecExpr>(RightSCEV)) { 845 std::swap(LeftSCEV, RightSCEV); 846 std::swap(LeftValue, RightValue); 847 Pred = ICmpInst::getSwappedPredicate(Pred); 848 } else { 849 FailureReason = "no add recurrences in the icmp"; 850 return None; 851 } 852 } 853 854 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) { 855 if (AR->getNoWrapFlags(SCEV::FlagNSW)) 856 return true; 857 858 IntegerType *Ty = cast<IntegerType>(AR->getType()); 859 IntegerType *WideTy = 860 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); 861 862 const SCEVAddRecExpr *ExtendAfterOp = 863 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); 864 if (ExtendAfterOp) { 865 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); 866 const SCEV *ExtendedStep = 867 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); 868 869 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && 870 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; 871 872 if (NoSignedWrap) 873 return true; 874 } 875 876 // We may have proved this when computing the sign extension above. 877 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap; 878 }; 879 880 // Here we check whether the suggested AddRec is an induction variable that 881 // can be handled (i.e. with known constant step), and if yes, calculate its 882 // step and identify whether it is increasing or decreasing. 883 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing, 884 ConstantInt *&StepCI) { 885 if (!AR->isAffine()) 886 return false; 887 888 // Currently we only work with induction variables that have been proved to 889 // not wrap. This restriction can potentially be lifted in the future. 890 891 if (!HasNoSignedWrap(AR)) 892 return false; 893 894 if (const SCEVConstant *StepExpr = 895 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) { 896 StepCI = StepExpr->getValue(); 897 assert(!StepCI->isZero() && "Zero step?"); 898 IsIncreasing = !StepCI->isNegative(); 899 return true; 900 } 901 902 return false; 903 }; 904 905 // `ICI` is interpreted as taking the backedge if the *next* value of the 906 // induction variable satisfies some constraint. 907 908 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV); 909 bool IsIncreasing = false; 910 bool IsSignedPredicate = true; 911 ConstantInt *StepCI; 912 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) { 913 FailureReason = "LHS in icmp not induction variable"; 914 return None; 915 } 916 917 const SCEV *StartNext = IndVarBase->getStart(); 918 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE)); 919 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); 920 const SCEV *Step = SE.getSCEV(StepCI); 921 922 ConstantInt *One = ConstantInt::get(IndVarTy, 1); 923 if (IsIncreasing) { 924 bool DecreasedRightValueByOne = false; 925 if (StepCI->isOne()) { 926 // Try to turn eq/ne predicates to those we can work with. 927 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) 928 // while (++i != len) { while (++i < len) { 929 // ... ---> ... 930 // } } 931 // If both parts are known non-negative, it is profitable to use 932 // unsigned comparison in increasing loop. This allows us to make the 933 // comparison check against "RightSCEV + 1" more optimistic. 934 if (SE.isKnownNonNegative(IndVarStart) && 935 SE.isKnownNonNegative(RightSCEV)) 936 Pred = ICmpInst::ICMP_ULT; 937 else 938 Pred = ICmpInst::ICMP_SLT; 939 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) { 940 // while (true) { while (true) { 941 // if (++i == len) ---> if (++i > len - 1) 942 // break; break; 943 // ... ... 944 // } } 945 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) && 946 CannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) { 947 Pred = ICmpInst::ICMP_UGT; 948 RightSCEV = SE.getMinusSCEV(RightSCEV, 949 SE.getOne(RightSCEV->getType())); 950 DecreasedRightValueByOne = true; 951 } else if (CannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) { 952 Pred = ICmpInst::ICMP_SGT; 953 RightSCEV = SE.getMinusSCEV(RightSCEV, 954 SE.getOne(RightSCEV->getType())); 955 DecreasedRightValueByOne = true; 956 } 957 } 958 } 959 960 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); 961 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); 962 bool FoundExpectedPred = 963 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0); 964 965 if (!FoundExpectedPred) { 966 FailureReason = "expected icmp slt semantically, found something else"; 967 return None; 968 } 969 970 IsSignedPredicate = ICmpInst::isSigned(Pred); 971 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { 972 FailureReason = "unsigned latch conditions are explicitly prohibited"; 973 return None; 974 } 975 976 if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred, 977 LatchBrExitIdx, &L, SE)) { 978 FailureReason = "Unsafe loop bounds"; 979 return None; 980 } 981 if (LatchBrExitIdx == 0) { 982 // We need to increase the right value unless we have already decreased 983 // it virtually when we replaced EQ with SGT. 984 if (!DecreasedRightValueByOne) { 985 IRBuilder<> B(Preheader->getTerminator()); 986 RightValue = B.CreateAdd(RightValue, One); 987 } 988 } else { 989 assert(!DecreasedRightValueByOne && 990 "Right value can be decreased only for LatchBrExitIdx == 0!"); 991 } 992 } else { 993 bool IncreasedRightValueByOne = false; 994 if (StepCI->isMinusOne()) { 995 // Try to turn eq/ne predicates to those we can work with. 996 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) 997 // while (--i != len) { while (--i > len) { 998 // ... ---> ... 999 // } } 1000 // We intentionally don't turn the predicate into UGT even if we know 1001 // that both operands are non-negative, because it will only pessimize 1002 // our check against "RightSCEV - 1". 1003 Pred = ICmpInst::ICMP_SGT; 1004 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 && 1005 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) { 1006 // while (true) { while (true) { 1007 // if (--i == len) ---> if (--i < len + 1) 1008 // break; break; 1009 // ... ... 1010 // } } 1011 // TODO: Insert ICMP_ULT if both are non-negative? 1012 Pred = ICmpInst::ICMP_SLT; 1013 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType())); 1014 IncreasedRightValueByOne = true; 1015 } 1016 } 1017 1018 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); 1019 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); 1020 1021 bool FoundExpectedPred = 1022 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0); 1023 1024 if (!FoundExpectedPred) { 1025 FailureReason = "expected icmp sgt semantically, found something else"; 1026 return None; 1027 } 1028 1029 IsSignedPredicate = 1030 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT; 1031 1032 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { 1033 FailureReason = "unsigned latch conditions are explicitly prohibited"; 1034 return None; 1035 } 1036 1037 // The predicate that we need to check that the induction variable lies 1038 // within bounds. 1039 ICmpInst::Predicate BoundPred = 1040 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT; 1041 1042 if (LatchBrExitIdx == 0) { 1043 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType())); 1044 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) { 1045 // TODO: this restriction is easily removable -- we just have to 1046 // remember that the icmp was an sgt and not an sge. 1047 FailureReason = "limit may overflow when coercing ge to gt"; 1048 return None; 1049 } 1050 1051 if (!SE.isAvailableAtLoopEntry(RightSCEV, &L) || 1052 !SE.isLoopEntryGuardedByCond( 1053 &L, BoundPred, IndVarStart, 1054 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) { 1055 FailureReason = "Induction variable start not bounded by lower limit"; 1056 return None; 1057 } 1058 1059 // We need to decrease the right value unless we have already increased 1060 // it virtually when we replaced EQ with SLT. 1061 if (!IncreasedRightValueByOne) { 1062 IRBuilder<> B(Preheader->getTerminator()); 1063 RightValue = B.CreateSub(RightValue, One); 1064 } 1065 } else { 1066 if (!SE.isAvailableAtLoopEntry(RightSCEV, &L) || 1067 !SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) { 1068 FailureReason = "Induction variable start not bounded by lower limit"; 1069 return None; 1070 } 1071 assert(!IncreasedRightValueByOne && 1072 "Right value can be increased only for LatchBrExitIdx == 0!"); 1073 } 1074 } 1075 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); 1076 1077 assert(SE.getLoopDisposition(LatchCount, &L) == 1078 ScalarEvolution::LoopInvariant && 1079 "loop variant exit count doesn't make sense!"); 1080 1081 assert(!L.contains(LatchExit) && "expected an exit block!"); 1082 const DataLayout &DL = Preheader->getModule()->getDataLayout(); 1083 Value *IndVarStartV = 1084 SCEVExpander(SE, DL, "irce") 1085 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator()); 1086 IndVarStartV->setName("indvar.start"); 1087 1088 LoopStructure Result; 1089 1090 Result.Tag = "main"; 1091 Result.Header = Header; 1092 Result.Latch = Latch; 1093 Result.LatchBr = LatchBr; 1094 Result.LatchExit = LatchExit; 1095 Result.LatchBrExitIdx = LatchBrExitIdx; 1096 Result.IndVarStart = IndVarStartV; 1097 Result.IndVarStep = StepCI; 1098 Result.IndVarBase = LeftValue; 1099 Result.IndVarIncreasing = IsIncreasing; 1100 Result.LoopExitAt = RightValue; 1101 Result.IsSignedPredicate = IsSignedPredicate; 1102 1103 FailureReason = nullptr; 1104 1105 return Result; 1106 } 1107 1108 Optional<LoopConstrainer::SubRanges> 1109 LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const { 1110 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); 1111 1112 if (Range.getType() != Ty) 1113 return None; 1114 1115 LoopConstrainer::SubRanges Result; 1116 1117 // I think we can be more aggressive here and make this nuw / nsw if the 1118 // addition that feeds into the icmp for the latch's terminating branch is nuw 1119 // / nsw. In any case, a wrapping 2's complement addition is safe. 1120 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); 1121 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); 1122 1123 bool Increasing = MainLoopStructure.IndVarIncreasing; 1124 1125 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or 1126 // [Smallest, GreatestSeen] is the range of values the induction variable 1127 // takes. 1128 1129 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr; 1130 1131 const SCEV *One = SE.getOne(Ty); 1132 if (Increasing) { 1133 Smallest = Start; 1134 Greatest = End; 1135 // No overflow, because the range [Smallest, GreatestSeen] is not empty. 1136 GreatestSeen = SE.getMinusSCEV(End, One); 1137 } else { 1138 // These two computations may sign-overflow. Here is why that is okay: 1139 // 1140 // We know that the induction variable does not sign-overflow on any 1141 // iteration except the last one, and it starts at `Start` and ends at 1142 // `End`, decrementing by one every time. 1143 // 1144 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the 1145 // induction variable is decreasing we know that that the smallest value 1146 // the loop body is actually executed with is `INT_SMIN` == `Smallest`. 1147 // 1148 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In 1149 // that case, `Clamp` will always return `Smallest` and 1150 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) 1151 // will be an empty range. Returning an empty range is always safe. 1152 1153 Smallest = SE.getAddExpr(End, One); 1154 Greatest = SE.getAddExpr(Start, One); 1155 GreatestSeen = Start; 1156 } 1157 1158 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) { 1159 return IsSignedPredicate 1160 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)) 1161 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S)); 1162 }; 1163 1164 // In some cases we can prove that we don't need a pre or post loop. 1165 ICmpInst::Predicate PredLE = 1166 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1167 ICmpInst::Predicate PredLT = 1168 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1169 1170 bool ProvablyNoPreloop = 1171 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest); 1172 if (!ProvablyNoPreloop) 1173 Result.LowLimit = Clamp(Range.getBegin()); 1174 1175 bool ProvablyNoPostLoop = 1176 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd()); 1177 if (!ProvablyNoPostLoop) 1178 Result.HighLimit = Clamp(Range.getEnd()); 1179 1180 return Result; 1181 } 1182 1183 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, 1184 const char *Tag) const { 1185 for (BasicBlock *BB : OriginalLoop.getBlocks()) { 1186 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); 1187 Result.Blocks.push_back(Clone); 1188 Result.Map[BB] = Clone; 1189 } 1190 1191 auto GetClonedValue = [&Result](Value *V) { 1192 assert(V && "null values not in domain!"); 1193 auto It = Result.Map.find(V); 1194 if (It == Result.Map.end()) 1195 return V; 1196 return static_cast<Value *>(It->second); 1197 }; 1198 1199 auto *ClonedLatch = 1200 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch())); 1201 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag, 1202 MDNode::get(Ctx, {})); 1203 1204 Result.Structure = MainLoopStructure.map(GetClonedValue); 1205 Result.Structure.Tag = Tag; 1206 1207 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { 1208 BasicBlock *ClonedBB = Result.Blocks[i]; 1209 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; 1210 1211 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); 1212 1213 for (Instruction &I : *ClonedBB) 1214 RemapInstruction(&I, Result.Map, 1215 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1216 1217 // Exit blocks will now have one more predecessor and their PHI nodes need 1218 // to be edited to reflect that. No phi nodes need to be introduced because 1219 // the loop is in LCSSA. 1220 1221 for (auto *SBB : successors(OriginalBB)) { 1222 if (OriginalLoop.contains(SBB)) 1223 continue; // not an exit block 1224 1225 for (PHINode &PN : SBB->phis()) { 1226 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB); 1227 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB); 1228 } 1229 } 1230 } 1231 } 1232 1233 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( 1234 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, 1235 BasicBlock *ContinuationBlock) const { 1236 // We start with a loop with a single latch: 1237 // 1238 // +--------------------+ 1239 // | | 1240 // | preheader | 1241 // | | 1242 // +--------+-----------+ 1243 // | ----------------\ 1244 // | / | 1245 // +--------v----v------+ | 1246 // | | | 1247 // | header | | 1248 // | | | 1249 // +--------------------+ | 1250 // | 1251 // ..... | 1252 // | 1253 // +--------------------+ | 1254 // | | | 1255 // | latch >----------/ 1256 // | | 1257 // +-------v------------+ 1258 // | 1259 // | 1260 // | +--------------------+ 1261 // | | | 1262 // +---> original exit | 1263 // | | 1264 // +--------------------+ 1265 // 1266 // We change the control flow to look like 1267 // 1268 // 1269 // +--------------------+ 1270 // | | 1271 // | preheader >-------------------------+ 1272 // | | | 1273 // +--------v-----------+ | 1274 // | /-------------+ | 1275 // | / | | 1276 // +--------v--v--------+ | | 1277 // | | | | 1278 // | header | | +--------+ | 1279 // | | | | | | 1280 // +--------------------+ | | +-----v-----v-----------+ 1281 // | | | | 1282 // | | | .pseudo.exit | 1283 // | | | | 1284 // | | +-----------v-----------+ 1285 // | | | 1286 // ..... | | | 1287 // | | +--------v-------------+ 1288 // +--------------------+ | | | | 1289 // | | | | | ContinuationBlock | 1290 // | latch >------+ | | | 1291 // | | | +----------------------+ 1292 // +---------v----------+ | 1293 // | | 1294 // | | 1295 // | +---------------^-----+ 1296 // | | | 1297 // +-----> .exit.selector | 1298 // | | 1299 // +----------v----------+ 1300 // | 1301 // +--------------------+ | 1302 // | | | 1303 // | original exit <----+ 1304 // | | 1305 // +--------------------+ 1306 1307 RewrittenRangeInfo RRI; 1308 1309 BasicBlock *BBInsertLocation = LS.Latch->getNextNode(); 1310 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", 1311 &F, BBInsertLocation); 1312 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, 1313 BBInsertLocation); 1314 1315 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator()); 1316 bool Increasing = LS.IndVarIncreasing; 1317 bool IsSignedPredicate = LS.IsSignedPredicate; 1318 1319 IRBuilder<> B(PreheaderJump); 1320 1321 // EnterLoopCond - is it okay to start executing this `LS'? 1322 Value *EnterLoopCond = nullptr; 1323 if (Increasing) 1324 EnterLoopCond = IsSignedPredicate 1325 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) 1326 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt); 1327 else 1328 EnterLoopCond = IsSignedPredicate 1329 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt) 1330 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt); 1331 1332 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); 1333 PreheaderJump->eraseFromParent(); 1334 1335 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); 1336 B.SetInsertPoint(LS.LatchBr); 1337 Value *TakeBackedgeLoopCond = nullptr; 1338 if (Increasing) 1339 TakeBackedgeLoopCond = IsSignedPredicate 1340 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt) 1341 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt); 1342 else 1343 TakeBackedgeLoopCond = IsSignedPredicate 1344 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt) 1345 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt); 1346 Value *CondForBranch = LS.LatchBrExitIdx == 1 1347 ? TakeBackedgeLoopCond 1348 : B.CreateNot(TakeBackedgeLoopCond); 1349 1350 LS.LatchBr->setCondition(CondForBranch); 1351 1352 B.SetInsertPoint(RRI.ExitSelector); 1353 1354 // IterationsLeft - are there any more iterations left, given the original 1355 // upper bound on the induction variable? If not, we branch to the "real" 1356 // exit. 1357 Value *IterationsLeft = nullptr; 1358 if (Increasing) 1359 IterationsLeft = IsSignedPredicate 1360 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt) 1361 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt); 1362 else 1363 IterationsLeft = IsSignedPredicate 1364 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt) 1365 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt); 1366 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); 1367 1368 BranchInst *BranchToContinuation = 1369 BranchInst::Create(ContinuationBlock, RRI.PseudoExit); 1370 1371 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of 1372 // each of the PHI nodes in the loop header. This feeds into the initial 1373 // value of the same PHI nodes if/when we continue execution. 1374 for (PHINode &PN : LS.Header->phis()) { 1375 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy", 1376 BranchToContinuation); 1377 1378 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader); 1379 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch), 1380 RRI.ExitSelector); 1381 RRI.PHIValuesAtPseudoExit.push_back(NewPHI); 1382 } 1383 1384 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end", 1385 BranchToContinuation); 1386 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); 1387 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector); 1388 1389 // The latch exit now has a branch from `RRI.ExitSelector' instead of 1390 // `LS.Latch'. The PHI nodes need to be updated to reflect that. 1391 for (PHINode &PN : LS.LatchExit->phis()) 1392 replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector); 1393 1394 return RRI; 1395 } 1396 1397 void LoopConstrainer::rewriteIncomingValuesForPHIs( 1398 LoopStructure &LS, BasicBlock *ContinuationBlock, 1399 const LoopConstrainer::RewrittenRangeInfo &RRI) const { 1400 unsigned PHIIndex = 0; 1401 for (PHINode &PN : LS.Header->phis()) 1402 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i) 1403 if (PN.getIncomingBlock(i) == ContinuationBlock) 1404 PN.setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); 1405 1406 LS.IndVarStart = RRI.IndVarEnd; 1407 } 1408 1409 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, 1410 BasicBlock *OldPreheader, 1411 const char *Tag) const { 1412 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); 1413 BranchInst::Create(LS.Header, Preheader); 1414 1415 for (PHINode &PN : LS.Header->phis()) 1416 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i) 1417 replacePHIBlock(&PN, OldPreheader, Preheader); 1418 1419 return Preheader; 1420 } 1421 1422 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { 1423 Loop *ParentLoop = OriginalLoop.getParentLoop(); 1424 if (!ParentLoop) 1425 return; 1426 1427 for (BasicBlock *BB : BBs) 1428 ParentLoop->addBasicBlockToLoop(BB, LI); 1429 } 1430 1431 Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent, 1432 ValueToValueMapTy &VM, 1433 bool IsSubloop) { 1434 Loop &New = *LI.AllocateLoop(); 1435 if (Parent) 1436 Parent->addChildLoop(&New); 1437 else 1438 LI.addTopLevelLoop(&New); 1439 LPMAddNewLoop(&New, IsSubloop); 1440 1441 // Add all of the blocks in Original to the new loop. 1442 for (auto *BB : Original->blocks()) 1443 if (LI.getLoopFor(BB) == Original) 1444 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI); 1445 1446 // Add all of the subloops to the new loop. 1447 for (Loop *SubLoop : *Original) 1448 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true); 1449 1450 return &New; 1451 } 1452 1453 bool LoopConstrainer::run() { 1454 BasicBlock *Preheader = nullptr; 1455 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); 1456 Preheader = OriginalLoop.getLoopPreheader(); 1457 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && 1458 "preconditions!"); 1459 1460 OriginalPreheader = Preheader; 1461 MainLoopPreheader = Preheader; 1462 1463 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate; 1464 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate); 1465 if (!MaybeSR.hasValue()) { 1466 DEBUG(dbgs() << "irce: could not compute subranges\n"); 1467 return false; 1468 } 1469 1470 SubRanges SR = MaybeSR.getValue(); 1471 bool Increasing = MainLoopStructure.IndVarIncreasing; 1472 IntegerType *IVTy = 1473 cast<IntegerType>(MainLoopStructure.IndVarBase->getType()); 1474 1475 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); 1476 Instruction *InsertPt = OriginalPreheader->getTerminator(); 1477 1478 // It would have been better to make `PreLoop' and `PostLoop' 1479 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy 1480 // constructor. 1481 ClonedLoop PreLoop, PostLoop; 1482 bool NeedsPreLoop = 1483 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); 1484 bool NeedsPostLoop = 1485 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); 1486 1487 Value *ExitPreLoopAt = nullptr; 1488 Value *ExitMainLoopAt = nullptr; 1489 const SCEVConstant *MinusOneS = 1490 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); 1491 1492 if (NeedsPreLoop) { 1493 const SCEV *ExitPreLoopAtSCEV = nullptr; 1494 1495 if (Increasing) 1496 ExitPreLoopAtSCEV = *SR.LowLimit; 1497 else { 1498 if (CannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE, 1499 IsSignedPredicate)) 1500 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); 1501 else { 1502 DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1503 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit) 1504 << "\n"); 1505 return false; 1506 } 1507 } 1508 1509 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) { 1510 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" 1511 << " preloop exit limit " << *ExitPreLoopAtSCEV 1512 << " at block " << InsertPt->getParent()->getName() << "\n"); 1513 return false; 1514 } 1515 1516 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); 1517 ExitPreLoopAt->setName("exit.preloop.at"); 1518 } 1519 1520 if (NeedsPostLoop) { 1521 const SCEV *ExitMainLoopAtSCEV = nullptr; 1522 1523 if (Increasing) 1524 ExitMainLoopAtSCEV = *SR.HighLimit; 1525 else { 1526 if (CannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE, 1527 IsSignedPredicate)) 1528 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); 1529 else { 1530 DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1531 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit) 1532 << "\n"); 1533 return false; 1534 } 1535 } 1536 1537 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) { 1538 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" 1539 << " main loop exit limit " << *ExitMainLoopAtSCEV 1540 << " at block " << InsertPt->getParent()->getName() << "\n"); 1541 return false; 1542 } 1543 1544 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); 1545 ExitMainLoopAt->setName("exit.mainloop.at"); 1546 } 1547 1548 // We clone these ahead of time so that we don't have to deal with changing 1549 // and temporarily invalid IR as we transform the loops. 1550 if (NeedsPreLoop) 1551 cloneLoop(PreLoop, "preloop"); 1552 if (NeedsPostLoop) 1553 cloneLoop(PostLoop, "postloop"); 1554 1555 RewrittenRangeInfo PreLoopRRI; 1556 1557 if (NeedsPreLoop) { 1558 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, 1559 PreLoop.Structure.Header); 1560 1561 MainLoopPreheader = 1562 createPreheader(MainLoopStructure, Preheader, "mainloop"); 1563 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, 1564 ExitPreLoopAt, MainLoopPreheader); 1565 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, 1566 PreLoopRRI); 1567 } 1568 1569 BasicBlock *PostLoopPreheader = nullptr; 1570 RewrittenRangeInfo PostLoopRRI; 1571 1572 if (NeedsPostLoop) { 1573 PostLoopPreheader = 1574 createPreheader(PostLoop.Structure, Preheader, "postloop"); 1575 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, 1576 ExitMainLoopAt, PostLoopPreheader); 1577 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, 1578 PostLoopRRI); 1579 } 1580 1581 BasicBlock *NewMainLoopPreheader = 1582 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; 1583 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, 1584 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, 1585 PostLoopRRI.ExitSelector, NewMainLoopPreheader}; 1586 1587 // Some of the above may be nullptr, filter them out before passing to 1588 // addToParentLoopIfNeeded. 1589 auto NewBlocksEnd = 1590 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); 1591 1592 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); 1593 1594 DT.recalculate(F); 1595 1596 // We need to first add all the pre and post loop blocks into the loop 1597 // structures (as part of createClonedLoopStructure), and then update the 1598 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating 1599 // LI when LoopSimplifyForm is generated. 1600 Loop *PreL = nullptr, *PostL = nullptr; 1601 if (!PreLoop.Blocks.empty()) { 1602 PreL = createClonedLoopStructure(&OriginalLoop, 1603 OriginalLoop.getParentLoop(), PreLoop.Map, 1604 /* IsSubLoop */ false); 1605 } 1606 1607 if (!PostLoop.Blocks.empty()) { 1608 PostL = 1609 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(), 1610 PostLoop.Map, /* IsSubLoop */ false); 1611 } 1612 1613 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms. 1614 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) { 1615 formLCSSARecursively(*L, DT, &LI, &SE); 1616 simplifyLoop(L, &DT, &LI, &SE, nullptr, true); 1617 // Pre/post loops are slow paths, we do not need to perform any loop 1618 // optimizations on them. 1619 if (!IsOriginalLoop) 1620 DisableAllLoopOptsOnLoop(*L); 1621 }; 1622 if (PreL) 1623 CanonicalizeLoop(PreL, false); 1624 if (PostL) 1625 CanonicalizeLoop(PostL, false); 1626 CanonicalizeLoop(&OriginalLoop, true); 1627 1628 return true; 1629 } 1630 1631 /// Computes and returns a range of values for the induction variable (IndVar) 1632 /// in which the range check can be safely elided. If it cannot compute such a 1633 /// range, returns None. 1634 Optional<InductiveRangeCheck::Range> 1635 InductiveRangeCheck::computeSafeIterationSpace( 1636 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar, 1637 bool IsLatchSigned) const { 1638 // IndVar is of the form "A + B * I" (where "I" is the canonical induction 1639 // variable, that may or may not exist as a real llvm::Value in the loop) and 1640 // this inductive range check is a range check on the "C + D * I" ("C" is 1641 // getBegin() and "D" is getStep()). We rewrite the value being range 1642 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". 1643 // 1644 // The actual inequalities we solve are of the form 1645 // 1646 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) 1647 // 1648 // Here L stands for upper limit of the safe iteration space. 1649 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid 1650 // overflows when calculating (0 - M) and (L - M) we, depending on type of 1651 // IV's iteration space, limit the calculations by borders of the iteration 1652 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0. 1653 // If we figured out that "anything greater than (-M) is safe", we strengthen 1654 // this to "everything greater than 0 is safe", assuming that values between 1655 // -M and 0 just do not exist in unsigned iteration space, and we don't want 1656 // to deal with overflown values. 1657 1658 if (!IndVar->isAffine()) 1659 return None; 1660 1661 const SCEV *A = IndVar->getStart(); 1662 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); 1663 if (!B) 1664 return None; 1665 assert(!B->isZero() && "Recurrence with zero step?"); 1666 1667 const SCEV *C = getBegin(); 1668 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep()); 1669 if (D != B) 1670 return None; 1671 1672 assert(!D->getValue()->isZero() && "Recurrence with zero step?"); 1673 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth(); 1674 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); 1675 1676 // Subtract Y from X so that it does not go through border of the IV 1677 // iteration space. Mathematically, it is equivalent to: 1678 // 1679 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1] 1680 // 1681 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to 1682 // any width of bit grid). But after we take min/max, the result is 1683 // guaranteed to be within [INT_MIN, INT_MAX]. 1684 // 1685 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min 1686 // values, depending on type of latch condition that defines IV iteration 1687 // space. 1688 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) { 1689 if (IsLatchSigned) { 1690 // X is a number from signed range, Y is interpreted as signed. 1691 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only 1692 // thing we should care about is that we didn't cross SINT_MAX. 1693 // So, if Y is positive, we subtract Y safely. 1694 // Rule 1: Y > 0 ---> Y. 1695 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely. 1696 // Rule 2: Y >=s (X - SINT_MAX) ---> Y. 1697 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX). 1698 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX). 1699 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases. 1700 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax); 1701 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax), 1702 SCEV::FlagNSW); 1703 } else 1704 // X is a number from unsigned range, Y is interpreted as signed. 1705 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only 1706 // thing we should care about is that we didn't cross zero. 1707 // So, if Y is negative, we subtract Y safely. 1708 // Rule 1: Y <s 0 ---> Y. 1709 // If 0 <= Y <= X, we subtract Y safely. 1710 // Rule 2: Y <=s X ---> Y. 1711 // If 0 <= X < Y, we should stop at 0 and can only subtract X. 1712 // Rule 3: Y >s X ---> X. 1713 // It gives us smin(X, Y) to subtract in all cases. 1714 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW); 1715 }; 1716 const SCEV *M = SE.getMinusSCEV(C, A); 1717 const SCEV *Zero = SE.getZero(M->getType()); 1718 const SCEV *Begin = ClampedSubtract(Zero, M); 1719 const SCEV *End = ClampedSubtract(getEnd(), M); 1720 return InductiveRangeCheck::Range(Begin, End); 1721 } 1722 1723 static Optional<InductiveRangeCheck::Range> 1724 IntersectSignedRange(ScalarEvolution &SE, 1725 const Optional<InductiveRangeCheck::Range> &R1, 1726 const InductiveRangeCheck::Range &R2) { 1727 if (R2.isEmpty(SE, /* IsSigned */ true)) 1728 return None; 1729 if (!R1.hasValue()) 1730 return R2; 1731 auto &R1Value = R1.getValue(); 1732 // We never return empty ranges from this function, and R1 is supposed to be 1733 // a result of intersection. Thus, R1 is never empty. 1734 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) && 1735 "We should never have empty R1!"); 1736 1737 // TODO: we could widen the smaller range and have this work; but for now we 1738 // bail out to keep things simple. 1739 if (R1Value.getType() != R2.getType()) 1740 return None; 1741 1742 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); 1743 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); 1744 1745 // If the resulting range is empty, just return None. 1746 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); 1747 if (Ret.isEmpty(SE, /* IsSigned */ true)) 1748 return None; 1749 return Ret; 1750 } 1751 1752 static Optional<InductiveRangeCheck::Range> 1753 IntersectUnsignedRange(ScalarEvolution &SE, 1754 const Optional<InductiveRangeCheck::Range> &R1, 1755 const InductiveRangeCheck::Range &R2) { 1756 if (R2.isEmpty(SE, /* IsSigned */ false)) 1757 return None; 1758 if (!R1.hasValue()) 1759 return R2; 1760 auto &R1Value = R1.getValue(); 1761 // We never return empty ranges from this function, and R1 is supposed to be 1762 // a result of intersection. Thus, R1 is never empty. 1763 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) && 1764 "We should never have empty R1!"); 1765 1766 // TODO: we could widen the smaller range and have this work; but for now we 1767 // bail out to keep things simple. 1768 if (R1Value.getType() != R2.getType()) 1769 return None; 1770 1771 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin()); 1772 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd()); 1773 1774 // If the resulting range is empty, just return None. 1775 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); 1776 if (Ret.isEmpty(SE, /* IsSigned */ false)) 1777 return None; 1778 return Ret; 1779 } 1780 1781 PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM, 1782 LoopStandardAnalysisResults &AR, 1783 LPMUpdater &U) { 1784 Function *F = L.getHeader()->getParent(); 1785 const auto &FAM = 1786 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); 1787 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F); 1788 InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI); 1789 auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) { 1790 if (!IsSubloop) 1791 U.addSiblingLoops(NL); 1792 }; 1793 bool Changed = IRCE.run(&L, LPMAddNewLoop); 1794 if (!Changed) 1795 return PreservedAnalyses::all(); 1796 1797 return getLoopPassPreservedAnalyses(); 1798 } 1799 1800 bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 1801 if (skipLoop(L)) 1802 return false; 1803 1804 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1805 BranchProbabilityInfo &BPI = 1806 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 1807 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1808 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1809 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI); 1810 auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) { 1811 LPM.addLoop(*NL); 1812 }; 1813 return IRCE.run(L, LPMAddNewLoop); 1814 } 1815 1816 bool InductiveRangeCheckElimination::run( 1817 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) { 1818 if (L->getBlocks().size() >= LoopSizeCutoff) { 1819 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n"); 1820 return false; 1821 } 1822 1823 BasicBlock *Preheader = L->getLoopPreheader(); 1824 if (!Preheader) { 1825 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); 1826 return false; 1827 } 1828 1829 LLVMContext &Context = Preheader->getContext(); 1830 SmallVector<InductiveRangeCheck, 16> RangeChecks; 1831 1832 for (auto BBI : L->getBlocks()) 1833 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) 1834 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, 1835 RangeChecks); 1836 1837 if (RangeChecks.empty()) 1838 return false; 1839 1840 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { 1841 OS << "irce: looking at loop "; L->print(OS); 1842 OS << "irce: loop has " << RangeChecks.size() 1843 << " inductive range checks: \n"; 1844 for (InductiveRangeCheck &IRC : RangeChecks) 1845 IRC.print(OS); 1846 }; 1847 1848 DEBUG(PrintRecognizedRangeChecks(dbgs())); 1849 1850 if (PrintRangeChecks) 1851 PrintRecognizedRangeChecks(errs()); 1852 1853 const char *FailureReason = nullptr; 1854 Optional<LoopStructure> MaybeLoopStructure = 1855 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); 1856 if (!MaybeLoopStructure.hasValue()) { 1857 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason 1858 << "\n";); 1859 return false; 1860 } 1861 LoopStructure LS = MaybeLoopStructure.getValue(); 1862 const SCEVAddRecExpr *IndVar = 1863 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep))); 1864 1865 Optional<InductiveRangeCheck::Range> SafeIterRange; 1866 Instruction *ExprInsertPt = Preheader->getTerminator(); 1867 1868 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; 1869 // Basing on the type of latch predicate, we interpret the IV iteration range 1870 // as signed or unsigned range. We use different min/max functions (signed or 1871 // unsigned) when intersecting this range with safe iteration ranges implied 1872 // by range checks. 1873 auto IntersectRange = 1874 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange; 1875 1876 IRBuilder<> B(ExprInsertPt); 1877 for (InductiveRangeCheck &IRC : RangeChecks) { 1878 auto Result = IRC.computeSafeIterationSpace(SE, IndVar, 1879 LS.IsSignedPredicate); 1880 if (Result.hasValue()) { 1881 auto MaybeSafeIterRange = 1882 IntersectRange(SE, SafeIterRange, Result.getValue()); 1883 if (MaybeSafeIterRange.hasValue()) { 1884 assert( 1885 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) && 1886 "We should never return empty ranges!"); 1887 RangeChecksToEliminate.push_back(IRC); 1888 SafeIterRange = MaybeSafeIterRange.getValue(); 1889 } 1890 } 1891 } 1892 1893 if (!SafeIterRange.hasValue()) 1894 return false; 1895 1896 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, 1897 SafeIterRange.getValue()); 1898 bool Changed = LC.run(); 1899 1900 if (Changed) { 1901 auto PrintConstrainedLoopInfo = [L]() { 1902 dbgs() << "irce: in function "; 1903 dbgs() << L->getHeader()->getParent()->getName() << ": "; 1904 dbgs() << "constrained "; 1905 L->print(dbgs()); 1906 }; 1907 1908 DEBUG(PrintConstrainedLoopInfo()); 1909 1910 if (PrintChangedLoops) 1911 PrintConstrainedLoopInfo(); 1912 1913 // Optimize away the now-redundant range checks. 1914 1915 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { 1916 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() 1917 ? ConstantInt::getTrue(Context) 1918 : ConstantInt::getFalse(Context); 1919 IRC.getCheckUse()->set(FoldedRangeCheck); 1920 } 1921 } 1922 1923 return Changed; 1924 } 1925 1926 Pass *llvm::createInductiveRangeCheckEliminationPass() { 1927 return new IRCELegacyPass(); 1928 } 1929