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