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 // The InductiveRangeCheckElimination pass splits a loop's iteration space into 10 // three disjoint ranges. It does that in a way such that the loop running in 11 // the middle loop provably does not need range checks. As an example, it will 12 // convert 13 // 14 // len = < known positive > 15 // for (i = 0; i < n; i++) { 16 // if (0 <= i && i < len) { 17 // do_something(); 18 // } else { 19 // throw_out_of_bounds(); 20 // } 21 // } 22 // 23 // to 24 // 25 // len = < known positive > 26 // limit = smin(n, len) 27 // // no first segment 28 // for (i = 0; i < limit; i++) { 29 // if (0 <= i && i < len) { // this check is fully redundant 30 // do_something(); 31 // } else { 32 // throw_out_of_bounds(); 33 // } 34 // } 35 // for (i = limit; i < n; i++) { 36 // if (0 <= i && i < len) { 37 // do_something(); 38 // } else { 39 // throw_out_of_bounds(); 40 // } 41 // } 42 //===----------------------------------------------------------------------===// 43 44 #include "llvm/ADT/Optional.h" 45 #include "llvm/Analysis/BranchProbabilityInfo.h" 46 #include "llvm/Analysis/InstructionSimplify.h" 47 #include "llvm/Analysis/LoopInfo.h" 48 #include "llvm/Analysis/LoopPass.h" 49 #include "llvm/Analysis/ScalarEvolution.h" 50 #include "llvm/Analysis/ScalarEvolutionExpander.h" 51 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 52 #include "llvm/Analysis/ValueTracking.h" 53 #include "llvm/IR/Dominators.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/IRBuilder.h" 56 #include "llvm/IR/Instructions.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/PatternMatch.h" 59 #include "llvm/IR/ValueHandle.h" 60 #include "llvm/IR/Verifier.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/Transforms/Scalar.h" 65 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 66 #include "llvm/Transforms/Utils/Cloning.h" 67 #include "llvm/Transforms/Utils/LoopUtils.h" 68 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 69 #include "llvm/Transforms/Utils/UnrollLoop.h" 70 71 using namespace llvm; 72 73 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, 74 cl::init(64)); 75 76 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, 77 cl::init(false)); 78 79 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden, 80 cl::init(false)); 81 82 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", 83 cl::Hidden, cl::init(10)); 84 85 static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks", 86 cl::Hidden, cl::init(false)); 87 88 #define DEBUG_TYPE "irce" 89 90 namespace { 91 92 /// An inductive range check is conditional branch in a loop with 93 /// 94 /// 1. a very cold successor (i.e. the branch jumps to that successor very 95 /// rarely) 96 /// 97 /// and 98 /// 99 /// 2. a condition that is provably true for some contiguous range of values 100 /// taken by the containing loop's induction variable. 101 /// 102 class InductiveRangeCheck { 103 // Classifies a range check 104 enum RangeCheckKind : unsigned { 105 // Range check of the form "0 <= I". 106 RANGE_CHECK_LOWER = 1, 107 108 // Range check of the form "I < L" where L is known positive. 109 RANGE_CHECK_UPPER = 2, 110 111 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER 112 // conditions. 113 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER, 114 115 // Unrecognized range check condition. 116 RANGE_CHECK_UNKNOWN = (unsigned)-1 117 }; 118 119 static StringRef rangeCheckKindToStr(RangeCheckKind); 120 121 const SCEV *Offset = nullptr; 122 const SCEV *Scale = nullptr; 123 Value *Length = nullptr; 124 Use *CheckUse = nullptr; 125 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN; 126 127 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI, 128 ScalarEvolution &SE, Value *&Index, 129 Value *&Length); 130 131 static void 132 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse, 133 SmallVectorImpl<InductiveRangeCheck> &Checks, 134 SmallPtrSetImpl<Value *> &Visited); 135 136 public: 137 const SCEV *getOffset() const { return Offset; } 138 const SCEV *getScale() const { return Scale; } 139 Value *getLength() const { return Length; } 140 141 void print(raw_ostream &OS) const { 142 OS << "InductiveRangeCheck:\n"; 143 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n"; 144 OS << " Offset: "; 145 Offset->print(OS); 146 OS << " Scale: "; 147 Scale->print(OS); 148 OS << " Length: "; 149 if (Length) 150 Length->print(OS); 151 else 152 OS << "(null)"; 153 OS << "\n CheckUse: "; 154 getCheckUse()->getUser()->print(OS); 155 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n"; 156 } 157 158 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 159 void dump() { 160 print(dbgs()); 161 } 162 #endif 163 164 Use *getCheckUse() const { return CheckUse; } 165 166 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If 167 /// R.getEnd() sle R.getBegin(), then R denotes the empty range. 168 169 class Range { 170 const SCEV *Begin; 171 const SCEV *End; 172 173 public: 174 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { 175 assert(Begin->getType() == End->getType() && "ill-typed range!"); 176 } 177 178 Type *getType() const { return Begin->getType(); } 179 const SCEV *getBegin() const { return Begin; } 180 const SCEV *getEnd() const { return End; } 181 }; 182 183 /// This is the value the condition of the branch needs to evaluate to for the 184 /// branch to take the hot successor (see (1) above). 185 bool getPassingDirection() { return true; } 186 187 /// Computes a range for the induction variable (IndVar) in which the range 188 /// check is redundant and can be constant-folded away. The induction 189 /// variable is not required to be the canonical {0,+,1} induction variable. 190 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, 191 const SCEVAddRecExpr *IndVar) const; 192 193 /// Parse out a set of inductive range checks from \p BI and append them to \p 194 /// Checks. 195 /// 196 /// NB! There may be conditions feeding into \p BI that aren't inductive range 197 /// checks, and hence don't end up in \p Checks. 198 static void 199 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE, 200 BranchProbabilityInfo &BPI, 201 SmallVectorImpl<InductiveRangeCheck> &Checks); 202 }; 203 204 class InductiveRangeCheckElimination : public LoopPass { 205 public: 206 static char ID; 207 InductiveRangeCheckElimination() : LoopPass(ID) { 208 initializeInductiveRangeCheckEliminationPass( 209 *PassRegistry::getPassRegistry()); 210 } 211 212 void getAnalysisUsage(AnalysisUsage &AU) const override { 213 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 214 getLoopAnalysisUsage(AU); 215 } 216 217 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 218 }; 219 220 char InductiveRangeCheckElimination::ID = 0; 221 } 222 223 INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce", 224 "Inductive range check elimination", false, false) 225 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 226 INITIALIZE_PASS_DEPENDENCY(LoopPass) 227 INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce", 228 "Inductive range check elimination", false, false) 229 230 StringRef InductiveRangeCheck::rangeCheckKindToStr( 231 InductiveRangeCheck::RangeCheckKind RCK) { 232 switch (RCK) { 233 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN: 234 return "RANGE_CHECK_UNKNOWN"; 235 236 case InductiveRangeCheck::RANGE_CHECK_UPPER: 237 return "RANGE_CHECK_UPPER"; 238 239 case InductiveRangeCheck::RANGE_CHECK_LOWER: 240 return "RANGE_CHECK_LOWER"; 241 242 case InductiveRangeCheck::RANGE_CHECK_BOTH: 243 return "RANGE_CHECK_BOTH"; 244 } 245 246 llvm_unreachable("unknown range check type!"); 247 } 248 249 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot 250 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set 251 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being 252 /// range checked, and set `Length` to the upper limit `Index` is being range 253 /// checked with if (and only if) the range check type is stronger or equal to 254 /// RANGE_CHECK_UPPER. 255 /// 256 InductiveRangeCheck::RangeCheckKind 257 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI, 258 ScalarEvolution &SE, Value *&Index, 259 Value *&Length) { 260 261 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) { 262 const SCEV *S = SE.getSCEV(V); 263 if (isa<SCEVCouldNotCompute>(S)) 264 return false; 265 266 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant && 267 SE.isKnownNonNegative(S); 268 }; 269 270 using namespace llvm::PatternMatch; 271 272 ICmpInst::Predicate Pred = ICI->getPredicate(); 273 Value *LHS = ICI->getOperand(0); 274 Value *RHS = ICI->getOperand(1); 275 276 switch (Pred) { 277 default: 278 return RANGE_CHECK_UNKNOWN; 279 280 case ICmpInst::ICMP_SLE: 281 std::swap(LHS, RHS); 282 // fallthrough 283 case ICmpInst::ICMP_SGE: 284 if (match(RHS, m_ConstantInt<0>())) { 285 Index = LHS; 286 return RANGE_CHECK_LOWER; 287 } 288 return RANGE_CHECK_UNKNOWN; 289 290 case ICmpInst::ICMP_SLT: 291 std::swap(LHS, RHS); 292 // fallthrough 293 case ICmpInst::ICMP_SGT: 294 if (match(RHS, m_ConstantInt<-1>())) { 295 Index = LHS; 296 return RANGE_CHECK_LOWER; 297 } 298 299 if (IsNonNegativeAndNotLoopVarying(LHS)) { 300 Index = RHS; 301 Length = LHS; 302 return RANGE_CHECK_UPPER; 303 } 304 return RANGE_CHECK_UNKNOWN; 305 306 case ICmpInst::ICMP_ULT: 307 std::swap(LHS, RHS); 308 // fallthrough 309 case ICmpInst::ICMP_UGT: 310 if (IsNonNegativeAndNotLoopVarying(LHS)) { 311 Index = RHS; 312 Length = LHS; 313 return RANGE_CHECK_BOTH; 314 } 315 return RANGE_CHECK_UNKNOWN; 316 } 317 318 llvm_unreachable("default clause returns!"); 319 } 320 321 void InductiveRangeCheck::extractRangeChecksFromCond( 322 Loop *L, ScalarEvolution &SE, Use &ConditionUse, 323 SmallVectorImpl<InductiveRangeCheck> &Checks, 324 SmallPtrSetImpl<Value *> &Visited) { 325 using namespace llvm::PatternMatch; 326 327 Value *Condition = ConditionUse.get(); 328 if (!Visited.insert(Condition).second) 329 return; 330 331 if (match(Condition, m_And(m_Value(), m_Value()))) { 332 SmallVector<InductiveRangeCheck, 8> SubChecks; 333 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0), 334 SubChecks, Visited); 335 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1), 336 SubChecks, Visited); 337 338 if (SubChecks.size() == 2) { 339 // Handle a special case where we know how to merge two checks separately 340 // checking the upper and lower bounds into a full range check. 341 const auto &RChkA = SubChecks[0]; 342 const auto &RChkB = SubChecks[1]; 343 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) && 344 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) { 345 346 // If RChkA.Kind == RChkB.Kind then we just found two identical checks. 347 // But if one of them is a RANGE_CHECK_LOWER and the other is a 348 // RANGE_CHECK_UPPER (only possibility if they're different) then 349 // together they form a RANGE_CHECK_BOTH. 350 SubChecks[0].Kind = 351 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind); 352 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length; 353 SubChecks[0].CheckUse = &ConditionUse; 354 355 // We updated one of the checks in place, now erase the other. 356 SubChecks.pop_back(); 357 } 358 } 359 360 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end()); 361 return; 362 } 363 364 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition); 365 if (!ICI) 366 return; 367 368 Value *Length = nullptr, *Index; 369 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length); 370 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN) 371 return; 372 373 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index)); 374 bool IsAffineIndex = 375 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); 376 377 if (!IsAffineIndex) 378 return; 379 380 InductiveRangeCheck IRC; 381 IRC.Length = Length; 382 IRC.Offset = IndexAddRec->getStart(); 383 IRC.Scale = IndexAddRec->getStepRecurrence(SE); 384 IRC.CheckUse = &ConditionUse; 385 IRC.Kind = RCKind; 386 Checks.push_back(IRC); 387 } 388 389 void InductiveRangeCheck::extractRangeChecksFromBranch( 390 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI, 391 SmallVectorImpl<InductiveRangeCheck> &Checks) { 392 393 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) 394 return; 395 396 BranchProbability LikelyTaken(15, 16); 397 398 if (!SkipProfitabilityChecks && 399 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken) 400 return; 401 402 SmallPtrSet<Value *, 8> Visited; 403 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0), 404 Checks, Visited); 405 } 406 407 namespace { 408 409 // Keeps track of the structure of a loop. This is similar to llvm::Loop, 410 // except that it is more lightweight and can track the state of a loop through 411 // changing and potentially invalid IR. This structure also formalizes the 412 // kinds of loops we can deal with -- ones that have a single latch that is also 413 // an exiting block *and* have a canonical induction variable. 414 struct LoopStructure { 415 const char *Tag; 416 417 BasicBlock *Header; 418 BasicBlock *Latch; 419 420 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th 421 // successor is `LatchExit', the exit block of the loop. 422 BranchInst *LatchBr; 423 BasicBlock *LatchExit; 424 unsigned LatchBrExitIdx; 425 426 Value *IndVarNext; 427 Value *IndVarStart; 428 Value *LoopExitAt; 429 bool IndVarIncreasing; 430 431 LoopStructure() 432 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr), 433 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr), 434 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {} 435 436 template <typename M> LoopStructure map(M Map) const { 437 LoopStructure Result; 438 Result.Tag = Tag; 439 Result.Header = cast<BasicBlock>(Map(Header)); 440 Result.Latch = cast<BasicBlock>(Map(Latch)); 441 Result.LatchBr = cast<BranchInst>(Map(LatchBr)); 442 Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); 443 Result.LatchBrExitIdx = LatchBrExitIdx; 444 Result.IndVarNext = Map(IndVarNext); 445 Result.IndVarStart = Map(IndVarStart); 446 Result.LoopExitAt = Map(LoopExitAt); 447 Result.IndVarIncreasing = IndVarIncreasing; 448 return Result; 449 } 450 451 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, 452 BranchProbabilityInfo &BPI, 453 Loop &, 454 const char *&); 455 }; 456 457 /// This class is used to constrain loops to run within a given iteration space. 458 /// The algorithm this class implements is given a Loop and a range [Begin, 459 /// End). The algorithm then tries to break out a "main loop" out of the loop 460 /// it is given in a way that the "main loop" runs with the induction variable 461 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post 462 /// loops to run any remaining iterations. The pre loop runs any iterations in 463 /// which the induction variable is < Begin, and the post loop runs any 464 /// iterations in which the induction variable is >= End. 465 /// 466 class LoopConstrainer { 467 // The representation of a clone of the original loop we started out with. 468 struct ClonedLoop { 469 // The cloned blocks 470 std::vector<BasicBlock *> Blocks; 471 472 // `Map` maps values in the clonee into values in the cloned version 473 ValueToValueMapTy Map; 474 475 // An instance of `LoopStructure` for the cloned loop 476 LoopStructure Structure; 477 }; 478 479 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for 480 // more details on what these fields mean. 481 struct RewrittenRangeInfo { 482 BasicBlock *PseudoExit; 483 BasicBlock *ExitSelector; 484 std::vector<PHINode *> PHIValuesAtPseudoExit; 485 PHINode *IndVarEnd; 486 487 RewrittenRangeInfo() 488 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {} 489 }; 490 491 // Calculated subranges we restrict the iteration space of the main loop to. 492 // See the implementation of `calculateSubRanges' for more details on how 493 // these fields are computed. `LowLimit` is None if there is no restriction 494 // on low end of the restricted iteration space of the main loop. `HighLimit` 495 // is None if there is no restriction on high end of the restricted iteration 496 // space of the main loop. 497 498 struct SubRanges { 499 Optional<const SCEV *> LowLimit; 500 Optional<const SCEV *> HighLimit; 501 }; 502 503 // A utility function that does a `replaceUsesOfWith' on the incoming block 504 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's 505 // incoming block list with `ReplaceBy'. 506 static void replacePHIBlock(PHINode *PN, BasicBlock *Block, 507 BasicBlock *ReplaceBy); 508 509 // Compute a safe set of limits for the main loop to run in -- effectively the 510 // intersection of `Range' and the iteration space of the original loop. 511 // Return None if unable to compute the set of subranges. 512 // 513 Optional<SubRanges> calculateSubRanges() const; 514 515 // Clone `OriginalLoop' and return the result in CLResult. The IR after 516 // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- 517 // the PHI nodes say that there is an incoming edge from `OriginalPreheader` 518 // but there is no such edge. 519 // 520 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; 521 522 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The 523 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the 524 // iteration space is not changed. `ExitLoopAt' is assumed to be slt 525 // `OriginalHeaderCount'. 526 // 527 // If there are iterations left to execute, control is made to jump to 528 // `ContinuationBlock', otherwise they take the normal loop exit. The 529 // returned `RewrittenRangeInfo' object is populated as follows: 530 // 531 // .PseudoExit is a basic block that unconditionally branches to 532 // `ContinuationBlock'. 533 // 534 // .ExitSelector is a basic block that decides, on exit from the loop, 535 // whether to branch to the "true" exit or to `PseudoExit'. 536 // 537 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value 538 // for each PHINode in the loop header on taking the pseudo exit. 539 // 540 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate 541 // preheader because it is made to branch to the loop header only 542 // conditionally. 543 // 544 RewrittenRangeInfo 545 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, 546 Value *ExitLoopAt, 547 BasicBlock *ContinuationBlock) const; 548 549 // The loop denoted by `LS' has `OldPreheader' as its preheader. This 550 // function creates a new preheader for `LS' and returns it. 551 // 552 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, 553 const char *Tag) const; 554 555 // `ContinuationBlockAndPreheader' was the continuation block for some call to 556 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. 557 // This function rewrites the PHI nodes in `LS.Header' to start with the 558 // correct value. 559 void rewriteIncomingValuesForPHIs( 560 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, 561 const LoopConstrainer::RewrittenRangeInfo &RRI) const; 562 563 // Even though we do not preserve any passes at this time, we at least need to 564 // keep the parent loop structure consistent. The `LPPassManager' seems to 565 // verify this after running a loop pass. This function adds the list of 566 // blocks denoted by BBs to this loops parent loop if required. 567 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); 568 569 // Some global state. 570 Function &F; 571 LLVMContext &Ctx; 572 ScalarEvolution &SE; 573 DominatorTree &DT; 574 575 // Information about the original loop we started out with. 576 Loop &OriginalLoop; 577 LoopInfo &LI; 578 const SCEV *LatchTakenCount; 579 BasicBlock *OriginalPreheader; 580 581 // The preheader of the main loop. This may or may not be different from 582 // `OriginalPreheader'. 583 BasicBlock *MainLoopPreheader; 584 585 // The range we need to run the main loop in. 586 InductiveRangeCheck::Range Range; 587 588 // The structure of the main loop (see comment at the beginning of this class 589 // for a definition) 590 LoopStructure MainLoopStructure; 591 592 public: 593 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS, 594 ScalarEvolution &SE, DominatorTree &DT, 595 InductiveRangeCheck::Range R) 596 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), 597 SE(SE), DT(DT), OriginalLoop(L), LI(LI), LatchTakenCount(nullptr), 598 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R), 599 MainLoopStructure(LS) {} 600 601 // Entry point for the algorithm. Returns true on success. 602 bool run(); 603 }; 604 605 } 606 607 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, 608 BasicBlock *ReplaceBy) { 609 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 610 if (PN->getIncomingBlock(i) == Block) 611 PN->setIncomingBlock(i, ReplaceBy); 612 } 613 614 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) { 615 APInt SMax = 616 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()); 617 return SE.getSignedRange(S).contains(SMax) && 618 SE.getUnsignedRange(S).contains(SMax); 619 } 620 621 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) { 622 APInt SMin = 623 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()); 624 return SE.getSignedRange(S).contains(SMin) && 625 SE.getUnsignedRange(S).contains(SMin); 626 } 627 628 Optional<LoopStructure> 629 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI, 630 Loop &L, const char *&FailureReason) { 631 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>"); 632 633 BasicBlock *Latch = L.getLoopLatch(); 634 if (!L.isLoopExiting(Latch)) { 635 FailureReason = "no loop latch"; 636 return None; 637 } 638 639 BasicBlock *Header = L.getHeader(); 640 BasicBlock *Preheader = L.getLoopPreheader(); 641 if (!Preheader) { 642 FailureReason = "no preheader"; 643 return None; 644 } 645 646 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); 647 if (!LatchBr || LatchBr->isUnconditional()) { 648 FailureReason = "latch terminator not conditional branch"; 649 return None; 650 } 651 652 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; 653 654 BranchProbability ExitProbability = 655 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx); 656 657 if (!SkipProfitabilityChecks && 658 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { 659 FailureReason = "short running loop, not profitable"; 660 return None; 661 } 662 663 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); 664 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { 665 FailureReason = "latch terminator branch not conditional on integral icmp"; 666 return None; 667 } 668 669 const SCEV *LatchCount = SE.getExitCount(&L, Latch); 670 if (isa<SCEVCouldNotCompute>(LatchCount)) { 671 FailureReason = "could not compute latch count"; 672 return None; 673 } 674 675 ICmpInst::Predicate Pred = ICI->getPredicate(); 676 Value *LeftValue = ICI->getOperand(0); 677 const SCEV *LeftSCEV = SE.getSCEV(LeftValue); 678 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); 679 680 Value *RightValue = ICI->getOperand(1); 681 const SCEV *RightSCEV = SE.getSCEV(RightValue); 682 683 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. 684 if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 685 if (isa<SCEVAddRecExpr>(RightSCEV)) { 686 std::swap(LeftSCEV, RightSCEV); 687 std::swap(LeftValue, RightValue); 688 Pred = ICmpInst::getSwappedPredicate(Pred); 689 } else { 690 FailureReason = "no add recurrences in the icmp"; 691 return None; 692 } 693 } 694 695 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) { 696 if (AR->getNoWrapFlags(SCEV::FlagNSW)) 697 return true; 698 699 IntegerType *Ty = cast<IntegerType>(AR->getType()); 700 IntegerType *WideTy = 701 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); 702 703 const SCEVAddRecExpr *ExtendAfterOp = 704 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); 705 if (ExtendAfterOp) { 706 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); 707 const SCEV *ExtendedStep = 708 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); 709 710 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && 711 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; 712 713 if (NoSignedWrap) 714 return true; 715 } 716 717 // We may have proved this when computing the sign extension above. 718 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap; 719 }; 720 721 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) { 722 if (!AR->isAffine()) 723 return false; 724 725 // Currently we only work with induction variables that have been proved to 726 // not wrap. This restriction can potentially be lifted in the future. 727 728 if (!HasNoSignedWrap(AR)) 729 return false; 730 731 if (const SCEVConstant *StepExpr = 732 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) { 733 ConstantInt *StepCI = StepExpr->getValue(); 734 if (StepCI->isOne() || StepCI->isMinusOne()) { 735 IsIncreasing = StepCI->isOne(); 736 return true; 737 } 738 } 739 740 return false; 741 }; 742 743 // `ICI` is interpreted as taking the backedge if the *next* value of the 744 // induction variable satisfies some constraint. 745 746 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV); 747 bool IsIncreasing = false; 748 if (!IsInductionVar(IndVarNext, IsIncreasing)) { 749 FailureReason = "LHS in icmp not induction variable"; 750 return None; 751 } 752 753 ConstantInt *One = ConstantInt::get(IndVarTy, 1); 754 // TODO: generalize the predicates here to also match their unsigned variants. 755 if (IsIncreasing) { 756 bool FoundExpectedPred = 757 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) || 758 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0); 759 760 if (!FoundExpectedPred) { 761 FailureReason = "expected icmp slt semantically, found something else"; 762 return None; 763 } 764 765 if (LatchBrExitIdx == 0) { 766 if (CanBeSMax(SE, RightSCEV)) { 767 // TODO: this restriction is easily removable -- we just have to 768 // remember that the icmp was an slt and not an sle. 769 FailureReason = "limit may overflow when coercing sle to slt"; 770 return None; 771 } 772 773 IRBuilder<> B(Preheader->getTerminator()); 774 RightValue = B.CreateAdd(RightValue, One); 775 } 776 777 } else { 778 bool FoundExpectedPred = 779 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) || 780 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0); 781 782 if (!FoundExpectedPred) { 783 FailureReason = "expected icmp sgt semantically, found something else"; 784 return None; 785 } 786 787 if (LatchBrExitIdx == 0) { 788 if (CanBeSMin(SE, RightSCEV)) { 789 // TODO: this restriction is easily removable -- we just have to 790 // remember that the icmp was an sgt and not an sge. 791 FailureReason = "limit may overflow when coercing sge to sgt"; 792 return None; 793 } 794 795 IRBuilder<> B(Preheader->getTerminator()); 796 RightValue = B.CreateSub(RightValue, One); 797 } 798 } 799 800 const SCEV *StartNext = IndVarNext->getStart(); 801 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE)); 802 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); 803 804 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); 805 806 assert(SE.getLoopDisposition(LatchCount, &L) == 807 ScalarEvolution::LoopInvariant && 808 "loop variant exit count doesn't make sense!"); 809 810 assert(!L.contains(LatchExit) && "expected an exit block!"); 811 const DataLayout &DL = Preheader->getModule()->getDataLayout(); 812 Value *IndVarStartV = 813 SCEVExpander(SE, DL, "irce") 814 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator()); 815 IndVarStartV->setName("indvar.start"); 816 817 LoopStructure Result; 818 819 Result.Tag = "main"; 820 Result.Header = Header; 821 Result.Latch = Latch; 822 Result.LatchBr = LatchBr; 823 Result.LatchExit = LatchExit; 824 Result.LatchBrExitIdx = LatchBrExitIdx; 825 Result.IndVarStart = IndVarStartV; 826 Result.IndVarNext = LeftValue; 827 Result.IndVarIncreasing = IsIncreasing; 828 Result.LoopExitAt = RightValue; 829 830 FailureReason = nullptr; 831 832 return Result; 833 } 834 835 Optional<LoopConstrainer::SubRanges> 836 LoopConstrainer::calculateSubRanges() const { 837 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); 838 839 if (Range.getType() != Ty) 840 return None; 841 842 LoopConstrainer::SubRanges Result; 843 844 // I think we can be more aggressive here and make this nuw / nsw if the 845 // addition that feeds into the icmp for the latch's terminating branch is nuw 846 // / nsw. In any case, a wrapping 2's complement addition is safe. 847 ConstantInt *One = ConstantInt::get(Ty, 1); 848 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); 849 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); 850 851 bool Increasing = MainLoopStructure.IndVarIncreasing; 852 853 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the 854 // range of values the induction variable takes. 855 856 const SCEV *Smallest = nullptr, *Greatest = nullptr; 857 858 if (Increasing) { 859 Smallest = Start; 860 Greatest = End; 861 } else { 862 // These two computations may sign-overflow. Here is why that is okay: 863 // 864 // We know that the induction variable does not sign-overflow on any 865 // iteration except the last one, and it starts at `Start` and ends at 866 // `End`, decrementing by one every time. 867 // 868 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the 869 // induction variable is decreasing we know that that the smallest value 870 // the loop body is actually executed with is `INT_SMIN` == `Smallest`. 871 // 872 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In 873 // that case, `Clamp` will always return `Smallest` and 874 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) 875 // will be an empty range. Returning an empty range is always safe. 876 // 877 878 Smallest = SE.getAddExpr(End, SE.getSCEV(One)); 879 Greatest = SE.getAddExpr(Start, SE.getSCEV(One)); 880 } 881 882 auto Clamp = [this, Smallest, Greatest](const SCEV *S) { 883 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)); 884 }; 885 886 // In some cases we can prove that we don't need a pre or post loop 887 888 bool ProvablyNoPreloop = 889 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest); 890 if (!ProvablyNoPreloop) 891 Result.LowLimit = Clamp(Range.getBegin()); 892 893 bool ProvablyNoPostLoop = 894 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd()); 895 if (!ProvablyNoPostLoop) 896 Result.HighLimit = Clamp(Range.getEnd()); 897 898 return Result; 899 } 900 901 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, 902 const char *Tag) const { 903 for (BasicBlock *BB : OriginalLoop.getBlocks()) { 904 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); 905 Result.Blocks.push_back(Clone); 906 Result.Map[BB] = Clone; 907 } 908 909 auto GetClonedValue = [&Result](Value *V) { 910 assert(V && "null values not in domain!"); 911 auto It = Result.Map.find(V); 912 if (It == Result.Map.end()) 913 return V; 914 return static_cast<Value *>(It->second); 915 }; 916 917 Result.Structure = MainLoopStructure.map(GetClonedValue); 918 Result.Structure.Tag = Tag; 919 920 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { 921 BasicBlock *ClonedBB = Result.Blocks[i]; 922 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; 923 924 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); 925 926 for (Instruction &I : *ClonedBB) 927 RemapInstruction(&I, Result.Map, 928 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 929 930 // Exit blocks will now have one more predecessor and their PHI nodes need 931 // to be edited to reflect that. No phi nodes need to be introduced because 932 // the loop is in LCSSA. 933 934 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB); 935 SBBI != SBBE; ++SBBI) { 936 937 if (OriginalLoop.contains(*SBBI)) 938 continue; // not an exit block 939 940 for (Instruction &I : **SBBI) { 941 if (!isa<PHINode>(&I)) 942 break; 943 944 PHINode *PN = cast<PHINode>(&I); 945 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB); 946 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB); 947 } 948 } 949 } 950 } 951 952 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( 953 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, 954 BasicBlock *ContinuationBlock) const { 955 956 // We start with a loop with a single latch: 957 // 958 // +--------------------+ 959 // | | 960 // | preheader | 961 // | | 962 // +--------+-----------+ 963 // | ----------------\ 964 // | / | 965 // +--------v----v------+ | 966 // | | | 967 // | header | | 968 // | | | 969 // +--------------------+ | 970 // | 971 // ..... | 972 // | 973 // +--------------------+ | 974 // | | | 975 // | latch >----------/ 976 // | | 977 // +-------v------------+ 978 // | 979 // | 980 // | +--------------------+ 981 // | | | 982 // +---> original exit | 983 // | | 984 // +--------------------+ 985 // 986 // We change the control flow to look like 987 // 988 // 989 // +--------------------+ 990 // | | 991 // | preheader >-------------------------+ 992 // | | | 993 // +--------v-----------+ | 994 // | /-------------+ | 995 // | / | | 996 // +--------v--v--------+ | | 997 // | | | | 998 // | header | | +--------+ | 999 // | | | | | | 1000 // +--------------------+ | | +-----v-----v-----------+ 1001 // | | | | 1002 // | | | .pseudo.exit | 1003 // | | | | 1004 // | | +-----------v-----------+ 1005 // | | | 1006 // ..... | | | 1007 // | | +--------v-------------+ 1008 // +--------------------+ | | | | 1009 // | | | | | ContinuationBlock | 1010 // | latch >------+ | | | 1011 // | | | +----------------------+ 1012 // +---------v----------+ | 1013 // | | 1014 // | | 1015 // | +---------------^-----+ 1016 // | | | 1017 // +-----> .exit.selector | 1018 // | | 1019 // +----------v----------+ 1020 // | 1021 // +--------------------+ | 1022 // | | | 1023 // | original exit <----+ 1024 // | | 1025 // +--------------------+ 1026 // 1027 1028 RewrittenRangeInfo RRI; 1029 1030 auto BBInsertLocation = std::next(Function::iterator(LS.Latch)); 1031 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", 1032 &F, &*BBInsertLocation); 1033 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, 1034 &*BBInsertLocation); 1035 1036 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator()); 1037 bool Increasing = LS.IndVarIncreasing; 1038 1039 IRBuilder<> B(PreheaderJump); 1040 1041 // EnterLoopCond - is it okay to start executing this `LS'? 1042 Value *EnterLoopCond = Increasing 1043 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) 1044 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt); 1045 1046 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); 1047 PreheaderJump->eraseFromParent(); 1048 1049 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); 1050 B.SetInsertPoint(LS.LatchBr); 1051 Value *TakeBackedgeLoopCond = 1052 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt) 1053 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt); 1054 Value *CondForBranch = LS.LatchBrExitIdx == 1 1055 ? TakeBackedgeLoopCond 1056 : B.CreateNot(TakeBackedgeLoopCond); 1057 1058 LS.LatchBr->setCondition(CondForBranch); 1059 1060 B.SetInsertPoint(RRI.ExitSelector); 1061 1062 // IterationsLeft - are there any more iterations left, given the original 1063 // upper bound on the induction variable? If not, we branch to the "real" 1064 // exit. 1065 Value *IterationsLeft = Increasing 1066 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt) 1067 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt); 1068 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); 1069 1070 BranchInst *BranchToContinuation = 1071 BranchInst::Create(ContinuationBlock, RRI.PseudoExit); 1072 1073 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of 1074 // each of the PHI nodes in the loop header. This feeds into the initial 1075 // value of the same PHI nodes if/when we continue execution. 1076 for (Instruction &I : *LS.Header) { 1077 if (!isa<PHINode>(&I)) 1078 break; 1079 1080 PHINode *PN = cast<PHINode>(&I); 1081 1082 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy", 1083 BranchToContinuation); 1084 1085 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader); 1086 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch), 1087 RRI.ExitSelector); 1088 RRI.PHIValuesAtPseudoExit.push_back(NewPHI); 1089 } 1090 1091 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end", 1092 BranchToContinuation); 1093 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); 1094 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector); 1095 1096 // The latch exit now has a branch from `RRI.ExitSelector' instead of 1097 // `LS.Latch'. The PHI nodes need to be updated to reflect that. 1098 for (Instruction &I : *LS.LatchExit) { 1099 if (PHINode *PN = dyn_cast<PHINode>(&I)) 1100 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector); 1101 else 1102 break; 1103 } 1104 1105 return RRI; 1106 } 1107 1108 void LoopConstrainer::rewriteIncomingValuesForPHIs( 1109 LoopStructure &LS, BasicBlock *ContinuationBlock, 1110 const LoopConstrainer::RewrittenRangeInfo &RRI) const { 1111 1112 unsigned PHIIndex = 0; 1113 for (Instruction &I : *LS.Header) { 1114 if (!isa<PHINode>(&I)) 1115 break; 1116 1117 PHINode *PN = cast<PHINode>(&I); 1118 1119 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) 1120 if (PN->getIncomingBlock(i) == ContinuationBlock) 1121 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); 1122 } 1123 1124 LS.IndVarStart = RRI.IndVarEnd; 1125 } 1126 1127 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, 1128 BasicBlock *OldPreheader, 1129 const char *Tag) const { 1130 1131 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); 1132 BranchInst::Create(LS.Header, Preheader); 1133 1134 for (Instruction &I : *LS.Header) { 1135 if (!isa<PHINode>(&I)) 1136 break; 1137 1138 PHINode *PN = cast<PHINode>(&I); 1139 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) 1140 replacePHIBlock(PN, OldPreheader, Preheader); 1141 } 1142 1143 return Preheader; 1144 } 1145 1146 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { 1147 Loop *ParentLoop = OriginalLoop.getParentLoop(); 1148 if (!ParentLoop) 1149 return; 1150 1151 for (BasicBlock *BB : BBs) 1152 ParentLoop->addBasicBlockToLoop(BB, LI); 1153 } 1154 1155 bool LoopConstrainer::run() { 1156 BasicBlock *Preheader = nullptr; 1157 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); 1158 Preheader = OriginalLoop.getLoopPreheader(); 1159 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && 1160 "preconditions!"); 1161 1162 OriginalPreheader = Preheader; 1163 MainLoopPreheader = Preheader; 1164 1165 Optional<SubRanges> MaybeSR = calculateSubRanges(); 1166 if (!MaybeSR.hasValue()) { 1167 DEBUG(dbgs() << "irce: could not compute subranges\n"); 1168 return false; 1169 } 1170 1171 SubRanges SR = MaybeSR.getValue(); 1172 bool Increasing = MainLoopStructure.IndVarIncreasing; 1173 IntegerType *IVTy = 1174 cast<IntegerType>(MainLoopStructure.IndVarNext->getType()); 1175 1176 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); 1177 Instruction *InsertPt = OriginalPreheader->getTerminator(); 1178 1179 // It would have been better to make `PreLoop' and `PostLoop' 1180 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy 1181 // constructor. 1182 ClonedLoop PreLoop, PostLoop; 1183 bool NeedsPreLoop = 1184 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); 1185 bool NeedsPostLoop = 1186 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); 1187 1188 Value *ExitPreLoopAt = nullptr; 1189 Value *ExitMainLoopAt = nullptr; 1190 const SCEVConstant *MinusOneS = 1191 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); 1192 1193 if (NeedsPreLoop) { 1194 const SCEV *ExitPreLoopAtSCEV = nullptr; 1195 1196 if (Increasing) 1197 ExitPreLoopAtSCEV = *SR.LowLimit; 1198 else { 1199 if (CanBeSMin(SE, *SR.HighLimit)) { 1200 DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1201 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit) 1202 << "\n"); 1203 return false; 1204 } 1205 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); 1206 } 1207 1208 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); 1209 ExitPreLoopAt->setName("exit.preloop.at"); 1210 } 1211 1212 if (NeedsPostLoop) { 1213 const SCEV *ExitMainLoopAtSCEV = nullptr; 1214 1215 if (Increasing) 1216 ExitMainLoopAtSCEV = *SR.HighLimit; 1217 else { 1218 if (CanBeSMin(SE, *SR.LowLimit)) { 1219 DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1220 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit) 1221 << "\n"); 1222 return false; 1223 } 1224 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); 1225 } 1226 1227 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); 1228 ExitMainLoopAt->setName("exit.mainloop.at"); 1229 } 1230 1231 // We clone these ahead of time so that we don't have to deal with changing 1232 // and temporarily invalid IR as we transform the loops. 1233 if (NeedsPreLoop) 1234 cloneLoop(PreLoop, "preloop"); 1235 if (NeedsPostLoop) 1236 cloneLoop(PostLoop, "postloop"); 1237 1238 RewrittenRangeInfo PreLoopRRI; 1239 1240 if (NeedsPreLoop) { 1241 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, 1242 PreLoop.Structure.Header); 1243 1244 MainLoopPreheader = 1245 createPreheader(MainLoopStructure, Preheader, "mainloop"); 1246 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, 1247 ExitPreLoopAt, MainLoopPreheader); 1248 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, 1249 PreLoopRRI); 1250 } 1251 1252 BasicBlock *PostLoopPreheader = nullptr; 1253 RewrittenRangeInfo PostLoopRRI; 1254 1255 if (NeedsPostLoop) { 1256 PostLoopPreheader = 1257 createPreheader(PostLoop.Structure, Preheader, "postloop"); 1258 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, 1259 ExitMainLoopAt, PostLoopPreheader); 1260 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, 1261 PostLoopRRI); 1262 } 1263 1264 BasicBlock *NewMainLoopPreheader = 1265 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; 1266 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, 1267 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, 1268 PostLoopRRI.ExitSelector, NewMainLoopPreheader}; 1269 1270 // Some of the above may be nullptr, filter them out before passing to 1271 // addToParentLoopIfNeeded. 1272 auto NewBlocksEnd = 1273 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); 1274 1275 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); 1276 addToParentLoopIfNeeded(PreLoop.Blocks); 1277 addToParentLoopIfNeeded(PostLoop.Blocks); 1278 1279 DT.recalculate(F); 1280 formLCSSARecursively(OriginalLoop, DT, &LI, &SE); 1281 1282 return true; 1283 } 1284 1285 /// Computes and returns a range of values for the induction variable (IndVar) 1286 /// in which the range check can be safely elided. If it cannot compute such a 1287 /// range, returns None. 1288 Optional<InductiveRangeCheck::Range> 1289 InductiveRangeCheck::computeSafeIterationSpace( 1290 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const { 1291 // IndVar is of the form "A + B * I" (where "I" is the canonical induction 1292 // variable, that may or may not exist as a real llvm::Value in the loop) and 1293 // this inductive range check is a range check on the "C + D * I" ("C" is 1294 // getOffset() and "D" is getScale()). We rewrite the value being range 1295 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". 1296 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code 1297 // can be generalized as needed. 1298 // 1299 // The actual inequalities we solve are of the form 1300 // 1301 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) 1302 // 1303 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions 1304 // and subtractions are twos-complement wrapping and comparisons are signed. 1305 // 1306 // Proof: 1307 // 1308 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows 1309 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows 1310 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have 1311 // overflown. 1312 // 1313 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t. 1314 // Hence 0 <= (IndVar + M) < L 1315 1316 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M = 1317 // 127, IndVar = 126 and L = -2 in an i8 world. 1318 1319 if (!IndVar->isAffine()) 1320 return None; 1321 1322 const SCEV *A = IndVar->getStart(); 1323 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); 1324 if (!B) 1325 return None; 1326 1327 const SCEV *C = getOffset(); 1328 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale()); 1329 if (D != B) 1330 return None; 1331 1332 ConstantInt *ConstD = D->getValue(); 1333 if (!(ConstD->isMinusOne() || ConstD->isOne())) 1334 return None; 1335 1336 const SCEV *M = SE.getMinusSCEV(C, A); 1337 1338 const SCEV *Begin = SE.getNegativeSCEV(M); 1339 const SCEV *UpperLimit = nullptr; 1340 1341 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L". 1342 // We can potentially do much better here. 1343 if (Value *V = getLength()) { 1344 UpperLimit = SE.getSCEV(V); 1345 } else { 1346 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!"); 1347 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth(); 1348 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); 1349 } 1350 1351 const SCEV *End = SE.getMinusSCEV(UpperLimit, M); 1352 return InductiveRangeCheck::Range(Begin, End); 1353 } 1354 1355 static Optional<InductiveRangeCheck::Range> 1356 IntersectRange(ScalarEvolution &SE, 1357 const Optional<InductiveRangeCheck::Range> &R1, 1358 const InductiveRangeCheck::Range &R2) { 1359 if (!R1.hasValue()) 1360 return R2; 1361 auto &R1Value = R1.getValue(); 1362 1363 // TODO: we could widen the smaller range and have this work; but for now we 1364 // bail out to keep things simple. 1365 if (R1Value.getType() != R2.getType()) 1366 return None; 1367 1368 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); 1369 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); 1370 1371 return InductiveRangeCheck::Range(NewBegin, NewEnd); 1372 } 1373 1374 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) { 1375 if (skipLoop(L)) 1376 return false; 1377 1378 if (L->getBlocks().size() >= LoopSizeCutoff) { 1379 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";); 1380 return false; 1381 } 1382 1383 BasicBlock *Preheader = L->getLoopPreheader(); 1384 if (!Preheader) { 1385 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); 1386 return false; 1387 } 1388 1389 LLVMContext &Context = Preheader->getContext(); 1390 SmallVector<InductiveRangeCheck, 16> RangeChecks; 1391 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1392 BranchProbabilityInfo &BPI = 1393 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 1394 1395 for (auto BBI : L->getBlocks()) 1396 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) 1397 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, 1398 RangeChecks); 1399 1400 if (RangeChecks.empty()) 1401 return false; 1402 1403 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { 1404 OS << "irce: looking at loop "; L->print(OS); 1405 OS << "irce: loop has " << RangeChecks.size() 1406 << " inductive range checks: \n"; 1407 for (InductiveRangeCheck &IRC : RangeChecks) 1408 IRC.print(OS); 1409 }; 1410 1411 DEBUG(PrintRecognizedRangeChecks(dbgs())); 1412 1413 if (PrintRangeChecks) 1414 PrintRecognizedRangeChecks(errs()); 1415 1416 const char *FailureReason = nullptr; 1417 Optional<LoopStructure> MaybeLoopStructure = 1418 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); 1419 if (!MaybeLoopStructure.hasValue()) { 1420 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason 1421 << "\n";); 1422 return false; 1423 } 1424 LoopStructure LS = MaybeLoopStructure.getValue(); 1425 bool Increasing = LS.IndVarIncreasing; 1426 const SCEV *MinusOne = 1427 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true); 1428 const SCEVAddRecExpr *IndVar = 1429 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne)); 1430 1431 Optional<InductiveRangeCheck::Range> SafeIterRange; 1432 Instruction *ExprInsertPt = Preheader->getTerminator(); 1433 1434 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; 1435 1436 IRBuilder<> B(ExprInsertPt); 1437 for (InductiveRangeCheck &IRC : RangeChecks) { 1438 auto Result = IRC.computeSafeIterationSpace(SE, IndVar); 1439 if (Result.hasValue()) { 1440 auto MaybeSafeIterRange = 1441 IntersectRange(SE, SafeIterRange, Result.getValue()); 1442 if (MaybeSafeIterRange.hasValue()) { 1443 RangeChecksToEliminate.push_back(IRC); 1444 SafeIterRange = MaybeSafeIterRange.getValue(); 1445 } 1446 } 1447 } 1448 1449 if (!SafeIterRange.hasValue()) 1450 return false; 1451 1452 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1453 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS, 1454 SE, DT, SafeIterRange.getValue()); 1455 bool Changed = LC.run(); 1456 1457 if (Changed) { 1458 auto PrintConstrainedLoopInfo = [L]() { 1459 dbgs() << "irce: in function "; 1460 dbgs() << L->getHeader()->getParent()->getName() << ": "; 1461 dbgs() << "constrained "; 1462 L->print(dbgs()); 1463 }; 1464 1465 DEBUG(PrintConstrainedLoopInfo()); 1466 1467 if (PrintChangedLoops) 1468 PrintConstrainedLoopInfo(); 1469 1470 // Optimize away the now-redundant range checks. 1471 1472 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { 1473 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() 1474 ? ConstantInt::getTrue(Context) 1475 : ConstantInt::getFalse(Context); 1476 IRC.getCheckUse()->set(FoldedRangeCheck); 1477 } 1478 } 1479 1480 return Changed; 1481 } 1482 1483 Pass *llvm::createInductiveRangeCheckEliminationPass() { 1484 return new InductiveRangeCheckElimination; 1485 } 1486