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