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