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 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 /// If the type of \p S matches with \p Ty, return \p S. Otherwise, return 1048 /// signed or unsigned extension of \p S to type \p Ty. 1049 static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE, 1050 bool Signed) { 1051 return Signed ? SE.getNoopOrSignExtend(S, Ty) : SE.getNoopOrZeroExtend(S, Ty); 1052 } 1053 1054 Optional<LoopConstrainer::SubRanges> 1055 LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const { 1056 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); 1057 1058 auto *RTy = cast<IntegerType>(Range.getType()); 1059 1060 // We only support wide range checks and narrow latches. 1061 if (!AllowNarrowLatchCondition && RTy != Ty) 1062 return None; 1063 if (RTy->getBitWidth() < Ty->getBitWidth()) 1064 return None; 1065 1066 LoopConstrainer::SubRanges Result; 1067 1068 // I think we can be more aggressive here and make this nuw / nsw if the 1069 // addition that feeds into the icmp for the latch's terminating branch is nuw 1070 // / nsw. In any case, a wrapping 2's complement addition is safe. 1071 const SCEV *Start = NoopOrExtend(SE.getSCEV(MainLoopStructure.IndVarStart), 1072 RTy, SE, IsSignedPredicate); 1073 const SCEV *End = NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy, 1074 SE, IsSignedPredicate); 1075 1076 bool Increasing = MainLoopStructure.IndVarIncreasing; 1077 1078 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or 1079 // [Smallest, GreatestSeen] is the range of values the induction variable 1080 // takes. 1081 1082 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr; 1083 1084 const SCEV *One = SE.getOne(RTy); 1085 if (Increasing) { 1086 Smallest = Start; 1087 Greatest = End; 1088 // No overflow, because the range [Smallest, GreatestSeen] is not empty. 1089 GreatestSeen = SE.getMinusSCEV(End, One); 1090 } else { 1091 // These two computations may sign-overflow. Here is why that is okay: 1092 // 1093 // We know that the induction variable does not sign-overflow on any 1094 // iteration except the last one, and it starts at `Start` and ends at 1095 // `End`, decrementing by one every time. 1096 // 1097 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the 1098 // induction variable is decreasing we know that that the smallest value 1099 // the loop body is actually executed with is `INT_SMIN` == `Smallest`. 1100 // 1101 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In 1102 // that case, `Clamp` will always return `Smallest` and 1103 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) 1104 // will be an empty range. Returning an empty range is always safe. 1105 1106 Smallest = SE.getAddExpr(End, One); 1107 Greatest = SE.getAddExpr(Start, One); 1108 GreatestSeen = Start; 1109 } 1110 1111 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) { 1112 return IsSignedPredicate 1113 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)) 1114 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S)); 1115 }; 1116 1117 // In some cases we can prove that we don't need a pre or post loop. 1118 ICmpInst::Predicate PredLE = 1119 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1120 ICmpInst::Predicate PredLT = 1121 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1122 1123 bool ProvablyNoPreloop = 1124 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest); 1125 if (!ProvablyNoPreloop) 1126 Result.LowLimit = Clamp(Range.getBegin()); 1127 1128 bool ProvablyNoPostLoop = 1129 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd()); 1130 if (!ProvablyNoPostLoop) 1131 Result.HighLimit = Clamp(Range.getEnd()); 1132 1133 return Result; 1134 } 1135 1136 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, 1137 const char *Tag) const { 1138 for (BasicBlock *BB : OriginalLoop.getBlocks()) { 1139 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); 1140 Result.Blocks.push_back(Clone); 1141 Result.Map[BB] = Clone; 1142 } 1143 1144 auto GetClonedValue = [&Result](Value *V) { 1145 assert(V && "null values not in domain!"); 1146 auto It = Result.Map.find(V); 1147 if (It == Result.Map.end()) 1148 return V; 1149 return static_cast<Value *>(It->second); 1150 }; 1151 1152 auto *ClonedLatch = 1153 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch())); 1154 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag, 1155 MDNode::get(Ctx, {})); 1156 1157 Result.Structure = MainLoopStructure.map(GetClonedValue); 1158 Result.Structure.Tag = Tag; 1159 1160 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { 1161 BasicBlock *ClonedBB = Result.Blocks[i]; 1162 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; 1163 1164 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); 1165 1166 for (Instruction &I : *ClonedBB) 1167 RemapInstruction(&I, Result.Map, 1168 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1169 1170 // Exit blocks will now have one more predecessor and their PHI nodes need 1171 // to be edited to reflect that. No phi nodes need to be introduced because 1172 // the loop is in LCSSA. 1173 1174 for (auto *SBB : successors(OriginalBB)) { 1175 if (OriginalLoop.contains(SBB)) 1176 continue; // not an exit block 1177 1178 for (PHINode &PN : SBB->phis()) { 1179 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB); 1180 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB); 1181 } 1182 } 1183 } 1184 } 1185 1186 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( 1187 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, 1188 BasicBlock *ContinuationBlock) const { 1189 // We start with a loop with a single latch: 1190 // 1191 // +--------------------+ 1192 // | | 1193 // | preheader | 1194 // | | 1195 // +--------+-----------+ 1196 // | ----------------\ 1197 // | / | 1198 // +--------v----v------+ | 1199 // | | | 1200 // | header | | 1201 // | | | 1202 // +--------------------+ | 1203 // | 1204 // ..... | 1205 // | 1206 // +--------------------+ | 1207 // | | | 1208 // | latch >----------/ 1209 // | | 1210 // +-------v------------+ 1211 // | 1212 // | 1213 // | +--------------------+ 1214 // | | | 1215 // +---> original exit | 1216 // | | 1217 // +--------------------+ 1218 // 1219 // We change the control flow to look like 1220 // 1221 // 1222 // +--------------------+ 1223 // | | 1224 // | preheader >-------------------------+ 1225 // | | | 1226 // +--------v-----------+ | 1227 // | /-------------+ | 1228 // | / | | 1229 // +--------v--v--------+ | | 1230 // | | | | 1231 // | header | | +--------+ | 1232 // | | | | | | 1233 // +--------------------+ | | +-----v-----v-----------+ 1234 // | | | | 1235 // | | | .pseudo.exit | 1236 // | | | | 1237 // | | +-----------v-----------+ 1238 // | | | 1239 // ..... | | | 1240 // | | +--------v-------------+ 1241 // +--------------------+ | | | | 1242 // | | | | | ContinuationBlock | 1243 // | latch >------+ | | | 1244 // | | | +----------------------+ 1245 // +---------v----------+ | 1246 // | | 1247 // | | 1248 // | +---------------^-----+ 1249 // | | | 1250 // +-----> .exit.selector | 1251 // | | 1252 // +----------v----------+ 1253 // | 1254 // +--------------------+ | 1255 // | | | 1256 // | original exit <----+ 1257 // | | 1258 // +--------------------+ 1259 1260 RewrittenRangeInfo RRI; 1261 1262 BasicBlock *BBInsertLocation = LS.Latch->getNextNode(); 1263 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", 1264 &F, BBInsertLocation); 1265 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, 1266 BBInsertLocation); 1267 1268 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator()); 1269 bool Increasing = LS.IndVarIncreasing; 1270 bool IsSignedPredicate = LS.IsSignedPredicate; 1271 1272 IRBuilder<> B(PreheaderJump); 1273 auto *RangeTy = Range.getBegin()->getType(); 1274 auto NoopOrExt = [&](Value *V) { 1275 if (V->getType() == RangeTy) 1276 return V; 1277 return IsSignedPredicate ? B.CreateSExt(V, RangeTy, "wide." + V->getName()) 1278 : B.CreateZExt(V, RangeTy, "wide." + V->getName()); 1279 }; 1280 1281 // EnterLoopCond - is it okay to start executing this `LS'? 1282 Value *EnterLoopCond = nullptr; 1283 auto Pred = 1284 Increasing 1285 ? (IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT) 1286 : (IsSignedPredicate ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT); 1287 Value *IndVarStart = NoopOrExt(LS.IndVarStart); 1288 EnterLoopCond = B.CreateICmp(Pred, IndVarStart, ExitSubloopAt); 1289 1290 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); 1291 PreheaderJump->eraseFromParent(); 1292 1293 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); 1294 B.SetInsertPoint(LS.LatchBr); 1295 Value *IndVarBase = NoopOrExt(LS.IndVarBase); 1296 Value *TakeBackedgeLoopCond = B.CreateICmp(Pred, IndVarBase, ExitSubloopAt); 1297 1298 Value *CondForBranch = LS.LatchBrExitIdx == 1 1299 ? TakeBackedgeLoopCond 1300 : B.CreateNot(TakeBackedgeLoopCond); 1301 1302 LS.LatchBr->setCondition(CondForBranch); 1303 1304 B.SetInsertPoint(RRI.ExitSelector); 1305 1306 // IterationsLeft - are there any more iterations left, given the original 1307 // upper bound on the induction variable? If not, we branch to the "real" 1308 // exit. 1309 Value *LoopExitAt = NoopOrExt(LS.LoopExitAt); 1310 Value *IterationsLeft = B.CreateICmp(Pred, IndVarBase, LoopExitAt); 1311 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); 1312 1313 BranchInst *BranchToContinuation = 1314 BranchInst::Create(ContinuationBlock, RRI.PseudoExit); 1315 1316 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of 1317 // each of the PHI nodes in the loop header. This feeds into the initial 1318 // value of the same PHI nodes if/when we continue execution. 1319 for (PHINode &PN : LS.Header->phis()) { 1320 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy", 1321 BranchToContinuation); 1322 1323 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader); 1324 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch), 1325 RRI.ExitSelector); 1326 RRI.PHIValuesAtPseudoExit.push_back(NewPHI); 1327 } 1328 1329 RRI.IndVarEnd = PHINode::Create(IndVarBase->getType(), 2, "indvar.end", 1330 BranchToContinuation); 1331 RRI.IndVarEnd->addIncoming(IndVarStart, Preheader); 1332 RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector); 1333 1334 // The latch exit now has a branch from `RRI.ExitSelector' instead of 1335 // `LS.Latch'. The PHI nodes need to be updated to reflect that. 1336 LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector); 1337 1338 return RRI; 1339 } 1340 1341 void LoopConstrainer::rewriteIncomingValuesForPHIs( 1342 LoopStructure &LS, BasicBlock *ContinuationBlock, 1343 const LoopConstrainer::RewrittenRangeInfo &RRI) const { 1344 unsigned PHIIndex = 0; 1345 for (PHINode &PN : LS.Header->phis()) 1346 PN.setIncomingValueForBlock(ContinuationBlock, 1347 RRI.PHIValuesAtPseudoExit[PHIIndex++]); 1348 1349 LS.IndVarStart = RRI.IndVarEnd; 1350 } 1351 1352 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, 1353 BasicBlock *OldPreheader, 1354 const char *Tag) const { 1355 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); 1356 BranchInst::Create(LS.Header, Preheader); 1357 1358 LS.Header->replacePhiUsesWith(OldPreheader, Preheader); 1359 1360 return Preheader; 1361 } 1362 1363 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { 1364 Loop *ParentLoop = OriginalLoop.getParentLoop(); 1365 if (!ParentLoop) 1366 return; 1367 1368 for (BasicBlock *BB : BBs) 1369 ParentLoop->addBasicBlockToLoop(BB, LI); 1370 } 1371 1372 Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent, 1373 ValueToValueMapTy &VM, 1374 bool IsSubloop) { 1375 Loop &New = *LI.AllocateLoop(); 1376 if (Parent) 1377 Parent->addChildLoop(&New); 1378 else 1379 LI.addTopLevelLoop(&New); 1380 LPMAddNewLoop(&New, IsSubloop); 1381 1382 // Add all of the blocks in Original to the new loop. 1383 for (auto *BB : Original->blocks()) 1384 if (LI.getLoopFor(BB) == Original) 1385 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI); 1386 1387 // Add all of the subloops to the new loop. 1388 for (Loop *SubLoop : *Original) 1389 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true); 1390 1391 return &New; 1392 } 1393 1394 bool LoopConstrainer::run() { 1395 BasicBlock *Preheader = nullptr; 1396 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); 1397 Preheader = OriginalLoop.getLoopPreheader(); 1398 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && 1399 "preconditions!"); 1400 1401 OriginalPreheader = Preheader; 1402 MainLoopPreheader = Preheader; 1403 1404 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate; 1405 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate); 1406 if (!MaybeSR.hasValue()) { 1407 LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n"); 1408 return false; 1409 } 1410 1411 SubRanges SR = MaybeSR.getValue(); 1412 bool Increasing = MainLoopStructure.IndVarIncreasing; 1413 IntegerType *IVTy = 1414 cast<IntegerType>(Range.getBegin()->getType()); 1415 1416 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); 1417 Instruction *InsertPt = OriginalPreheader->getTerminator(); 1418 1419 // It would have been better to make `PreLoop' and `PostLoop' 1420 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy 1421 // constructor. 1422 ClonedLoop PreLoop, PostLoop; 1423 bool NeedsPreLoop = 1424 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); 1425 bool NeedsPostLoop = 1426 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); 1427 1428 Value *ExitPreLoopAt = nullptr; 1429 Value *ExitMainLoopAt = nullptr; 1430 const SCEVConstant *MinusOneS = 1431 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); 1432 1433 if (NeedsPreLoop) { 1434 const SCEV *ExitPreLoopAtSCEV = nullptr; 1435 1436 if (Increasing) 1437 ExitPreLoopAtSCEV = *SR.LowLimit; 1438 else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE, 1439 IsSignedPredicate)) 1440 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); 1441 else { 1442 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1443 << "preloop exit limit. HighLimit = " 1444 << *(*SR.HighLimit) << "\n"); 1445 return false; 1446 } 1447 1448 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) { 1449 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" 1450 << " preloop exit limit " << *ExitPreLoopAtSCEV 1451 << " at block " << InsertPt->getParent()->getName() 1452 << "\n"); 1453 return false; 1454 } 1455 1456 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); 1457 ExitPreLoopAt->setName("exit.preloop.at"); 1458 } 1459 1460 if (NeedsPostLoop) { 1461 const SCEV *ExitMainLoopAtSCEV = nullptr; 1462 1463 if (Increasing) 1464 ExitMainLoopAtSCEV = *SR.HighLimit; 1465 else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE, 1466 IsSignedPredicate)) 1467 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); 1468 else { 1469 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing " 1470 << "mainloop exit limit. LowLimit = " 1471 << *(*SR.LowLimit) << "\n"); 1472 return false; 1473 } 1474 1475 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) { 1476 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" 1477 << " main loop exit limit " << *ExitMainLoopAtSCEV 1478 << " at block " << InsertPt->getParent()->getName() 1479 << "\n"); 1480 return false; 1481 } 1482 1483 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); 1484 ExitMainLoopAt->setName("exit.mainloop.at"); 1485 } 1486 1487 // We clone these ahead of time so that we don't have to deal with changing 1488 // and temporarily invalid IR as we transform the loops. 1489 if (NeedsPreLoop) 1490 cloneLoop(PreLoop, "preloop"); 1491 if (NeedsPostLoop) 1492 cloneLoop(PostLoop, "postloop"); 1493 1494 RewrittenRangeInfo PreLoopRRI; 1495 1496 if (NeedsPreLoop) { 1497 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, 1498 PreLoop.Structure.Header); 1499 1500 MainLoopPreheader = 1501 createPreheader(MainLoopStructure, Preheader, "mainloop"); 1502 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, 1503 ExitPreLoopAt, MainLoopPreheader); 1504 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, 1505 PreLoopRRI); 1506 } 1507 1508 BasicBlock *PostLoopPreheader = nullptr; 1509 RewrittenRangeInfo PostLoopRRI; 1510 1511 if (NeedsPostLoop) { 1512 PostLoopPreheader = 1513 createPreheader(PostLoop.Structure, Preheader, "postloop"); 1514 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, 1515 ExitMainLoopAt, PostLoopPreheader); 1516 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, 1517 PostLoopRRI); 1518 } 1519 1520 BasicBlock *NewMainLoopPreheader = 1521 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; 1522 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, 1523 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, 1524 PostLoopRRI.ExitSelector, NewMainLoopPreheader}; 1525 1526 // Some of the above may be nullptr, filter them out before passing to 1527 // addToParentLoopIfNeeded. 1528 auto NewBlocksEnd = 1529 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); 1530 1531 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); 1532 1533 DT.recalculate(F); 1534 1535 // We need to first add all the pre and post loop blocks into the loop 1536 // structures (as part of createClonedLoopStructure), and then update the 1537 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating 1538 // LI when LoopSimplifyForm is generated. 1539 Loop *PreL = nullptr, *PostL = nullptr; 1540 if (!PreLoop.Blocks.empty()) { 1541 PreL = createClonedLoopStructure(&OriginalLoop, 1542 OriginalLoop.getParentLoop(), PreLoop.Map, 1543 /* IsSubLoop */ false); 1544 } 1545 1546 if (!PostLoop.Blocks.empty()) { 1547 PostL = 1548 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(), 1549 PostLoop.Map, /* IsSubLoop */ false); 1550 } 1551 1552 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms. 1553 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) { 1554 formLCSSARecursively(*L, DT, &LI, &SE); 1555 simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, true); 1556 // Pre/post loops are slow paths, we do not need to perform any loop 1557 // optimizations on them. 1558 if (!IsOriginalLoop) 1559 DisableAllLoopOptsOnLoop(*L); 1560 }; 1561 if (PreL) 1562 CanonicalizeLoop(PreL, false); 1563 if (PostL) 1564 CanonicalizeLoop(PostL, false); 1565 CanonicalizeLoop(&OriginalLoop, true); 1566 1567 return true; 1568 } 1569 1570 /// Computes and returns a range of values for the induction variable (IndVar) 1571 /// in which the range check can be safely elided. If it cannot compute such a 1572 /// range, returns None. 1573 Optional<InductiveRangeCheck::Range> 1574 InductiveRangeCheck::computeSafeIterationSpace( 1575 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar, 1576 bool IsLatchSigned) const { 1577 // We can deal when types of latch check and range checks don't match in case 1578 // if latch check is more narrow. 1579 auto *IVType = cast<IntegerType>(IndVar->getType()); 1580 auto *RCType = cast<IntegerType>(getBegin()->getType()); 1581 if (IVType->getBitWidth() > RCType->getBitWidth()) 1582 return None; 1583 // IndVar is of the form "A + B * I" (where "I" is the canonical induction 1584 // variable, that may or may not exist as a real llvm::Value in the loop) and 1585 // this inductive range check is a range check on the "C + D * I" ("C" is 1586 // getBegin() and "D" is getStep()). We rewrite the value being range 1587 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". 1588 // 1589 // The actual inequalities we solve are of the form 1590 // 1591 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) 1592 // 1593 // Here L stands for upper limit of the safe iteration space. 1594 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid 1595 // overflows when calculating (0 - M) and (L - M) we, depending on type of 1596 // IV's iteration space, limit the calculations by borders of the iteration 1597 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0. 1598 // If we figured out that "anything greater than (-M) is safe", we strengthen 1599 // this to "everything greater than 0 is safe", assuming that values between 1600 // -M and 0 just do not exist in unsigned iteration space, and we don't want 1601 // to deal with overflown values. 1602 1603 if (!IndVar->isAffine()) 1604 return None; 1605 1606 const SCEV *A = NoopOrExtend(IndVar->getStart(), RCType, SE, IsLatchSigned); 1607 const SCEVConstant *B = dyn_cast<SCEVConstant>( 1608 NoopOrExtend(IndVar->getStepRecurrence(SE), RCType, SE, IsLatchSigned)); 1609 if (!B) 1610 return None; 1611 assert(!B->isZero() && "Recurrence with zero step?"); 1612 1613 const SCEV *C = getBegin(); 1614 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep()); 1615 if (D != B) 1616 return None; 1617 1618 assert(!D->getValue()->isZero() && "Recurrence with zero step?"); 1619 unsigned BitWidth = RCType->getBitWidth(); 1620 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); 1621 1622 // Subtract Y from X so that it does not go through border of the IV 1623 // iteration space. Mathematically, it is equivalent to: 1624 // 1625 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1] 1626 // 1627 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to 1628 // any width of bit grid). But after we take min/max, the result is 1629 // guaranteed to be within [INT_MIN, INT_MAX]. 1630 // 1631 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min 1632 // values, depending on type of latch condition that defines IV iteration 1633 // space. 1634 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) { 1635 // FIXME: The current implementation assumes that X is in [0, SINT_MAX]. 1636 // This is required to ensure that SINT_MAX - X does not overflow signed and 1637 // that X - Y does not overflow unsigned if Y is negative. Can we lift this 1638 // restriction and make it work for negative X either? 1639 if (IsLatchSigned) { 1640 // X is a number from signed range, Y is interpreted as signed. 1641 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only 1642 // thing we should care about is that we didn't cross SINT_MAX. 1643 // So, if Y is positive, we subtract Y safely. 1644 // Rule 1: Y > 0 ---> Y. 1645 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely. 1646 // Rule 2: Y >=s (X - SINT_MAX) ---> Y. 1647 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX). 1648 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX). 1649 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases. 1650 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax); 1651 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax), 1652 SCEV::FlagNSW); 1653 } else 1654 // X is a number from unsigned range, Y is interpreted as signed. 1655 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only 1656 // thing we should care about is that we didn't cross zero. 1657 // So, if Y is negative, we subtract Y safely. 1658 // Rule 1: Y <s 0 ---> Y. 1659 // If 0 <= Y <= X, we subtract Y safely. 1660 // Rule 2: Y <=s X ---> Y. 1661 // If 0 <= X < Y, we should stop at 0 and can only subtract X. 1662 // Rule 3: Y >s X ---> X. 1663 // It gives us smin(X, Y) to subtract in all cases. 1664 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW); 1665 }; 1666 const SCEV *M = SE.getMinusSCEV(C, A); 1667 const SCEV *Zero = SE.getZero(M->getType()); 1668 1669 // This function returns SCEV equal to 1 if X is non-negative 0 otherwise. 1670 auto SCEVCheckNonNegative = [&](const SCEV *X) { 1671 const Loop *L = IndVar->getLoop(); 1672 const SCEV *One = SE.getOne(X->getType()); 1673 // Can we trivially prove that X is a non-negative or negative value? 1674 if (isKnownNonNegativeInLoop(X, L, SE)) 1675 return One; 1676 else if (isKnownNegativeInLoop(X, L, SE)) 1677 return Zero; 1678 // If not, we will have to figure it out during the execution. 1679 // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0. 1680 const SCEV *NegOne = SE.getNegativeSCEV(One); 1681 return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One); 1682 }; 1683 // FIXME: Current implementation of ClampedSubtract implicitly assumes that 1684 // X is non-negative (in sense of a signed value). We need to re-implement 1685 // this function in a way that it will correctly handle negative X as well. 1686 // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can 1687 // end up with a negative X and produce wrong results. So currently we ensure 1688 // that if getEnd() is negative then both ends of the safe range are zero. 1689 // Note that this may pessimize elimination of unsigned range checks against 1690 // negative values. 1691 const SCEV *REnd = getEnd(); 1692 const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd); 1693 1694 const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative); 1695 const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative); 1696 return InductiveRangeCheck::Range(Begin, End); 1697 } 1698 1699 static Optional<InductiveRangeCheck::Range> 1700 IntersectSignedRange(ScalarEvolution &SE, 1701 const Optional<InductiveRangeCheck::Range> &R1, 1702 const InductiveRangeCheck::Range &R2) { 1703 if (R2.isEmpty(SE, /* IsSigned */ true)) 1704 return None; 1705 if (!R1.hasValue()) 1706 return R2; 1707 auto &R1Value = R1.getValue(); 1708 // We never return empty ranges from this function, and R1 is supposed to be 1709 // a result of intersection. Thus, R1 is never empty. 1710 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) && 1711 "We should never have empty R1!"); 1712 1713 // TODO: we could widen the smaller range and have this work; but for now we 1714 // bail out to keep things simple. 1715 if (R1Value.getType() != R2.getType()) 1716 return None; 1717 1718 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); 1719 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); 1720 1721 // If the resulting range is empty, just return None. 1722 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); 1723 if (Ret.isEmpty(SE, /* IsSigned */ true)) 1724 return None; 1725 return Ret; 1726 } 1727 1728 static Optional<InductiveRangeCheck::Range> 1729 IntersectUnsignedRange(ScalarEvolution &SE, 1730 const Optional<InductiveRangeCheck::Range> &R1, 1731 const InductiveRangeCheck::Range &R2) { 1732 if (R2.isEmpty(SE, /* IsSigned */ false)) 1733 return None; 1734 if (!R1.hasValue()) 1735 return R2; 1736 auto &R1Value = R1.getValue(); 1737 // We never return empty ranges from this function, and R1 is supposed to be 1738 // a result of intersection. Thus, R1 is never empty. 1739 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) && 1740 "We should never have empty R1!"); 1741 1742 // TODO: we could widen the smaller range and have this work; but for now we 1743 // bail out to keep things simple. 1744 if (R1Value.getType() != R2.getType()) 1745 return None; 1746 1747 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin()); 1748 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd()); 1749 1750 // If the resulting range is empty, just return None. 1751 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); 1752 if (Ret.isEmpty(SE, /* IsSigned */ false)) 1753 return None; 1754 return Ret; 1755 } 1756 1757 PreservedAnalyses IRCEPass::run(Function &F, FunctionAnalysisManager &AM) { 1758 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 1759 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1760 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 1761 1762 BranchProbabilityInfo BPI; 1763 BPI.calculate(F, LI); 1764 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI); 1765 1766 bool Changed = false; 1767 1768 for (const auto &L : LI) { 1769 Changed |= simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, 1770 /*PreserveLCSSA=*/false); 1771 Changed |= formLCSSARecursively(*L, DT, &LI, &SE); 1772 } 1773 1774 SmallPriorityWorklist<Loop *, 4> Worklist; 1775 appendLoopsToWorklist(LI, Worklist); 1776 auto LPMAddNewLoop = [&Worklist](Loop *NL, bool IsSubloop) { 1777 if (!IsSubloop) 1778 appendLoopsToWorklist(*NL, Worklist); 1779 }; 1780 1781 while (!Worklist.empty()) { 1782 Loop *L = Worklist.pop_back_val(); 1783 Changed |= IRCE.run(L, LPMAddNewLoop); 1784 } 1785 1786 if (!Changed) 1787 return PreservedAnalyses::all(); 1788 return getLoopPassPreservedAnalyses(); 1789 } 1790 1791 bool IRCELegacyPass::runOnFunction(Function &F) { 1792 if (skipFunction(F)) 1793 return false; 1794 1795 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1796 BranchProbabilityInfo &BPI = 1797 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 1798 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1799 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1800 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI); 1801 1802 bool Changed = false; 1803 1804 for (const auto &L : LI) { 1805 Changed |= simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, 1806 /*PreserveLCSSA=*/false); 1807 Changed |= formLCSSARecursively(*L, DT, &LI, &SE); 1808 } 1809 1810 SmallPriorityWorklist<Loop *, 4> Worklist; 1811 appendLoopsToWorklist(LI, Worklist); 1812 auto LPMAddNewLoop = [&](Loop *NL, bool IsSubloop) { 1813 if (!IsSubloop) 1814 appendLoopsToWorklist(*NL, Worklist); 1815 }; 1816 1817 while (!Worklist.empty()) { 1818 Loop *L = Worklist.pop_back_val(); 1819 Changed |= IRCE.run(L, LPMAddNewLoop); 1820 } 1821 return Changed; 1822 } 1823 1824 bool InductiveRangeCheckElimination::run( 1825 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) { 1826 if (L->getBlocks().size() >= LoopSizeCutoff) { 1827 LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n"); 1828 return false; 1829 } 1830 1831 BasicBlock *Preheader = L->getLoopPreheader(); 1832 if (!Preheader) { 1833 LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); 1834 return false; 1835 } 1836 1837 LLVMContext &Context = Preheader->getContext(); 1838 SmallVector<InductiveRangeCheck, 16> RangeChecks; 1839 1840 for (auto BBI : L->getBlocks()) 1841 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) 1842 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, 1843 RangeChecks); 1844 1845 if (RangeChecks.empty()) 1846 return false; 1847 1848 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { 1849 OS << "irce: looking at loop "; L->print(OS); 1850 OS << "irce: loop has " << RangeChecks.size() 1851 << " inductive range checks: \n"; 1852 for (InductiveRangeCheck &IRC : RangeChecks) 1853 IRC.print(OS); 1854 }; 1855 1856 LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs())); 1857 1858 if (PrintRangeChecks) 1859 PrintRecognizedRangeChecks(errs()); 1860 1861 const char *FailureReason = nullptr; 1862 Optional<LoopStructure> MaybeLoopStructure = 1863 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); 1864 if (!MaybeLoopStructure.hasValue()) { 1865 LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: " 1866 << FailureReason << "\n";); 1867 return false; 1868 } 1869 LoopStructure LS = MaybeLoopStructure.getValue(); 1870 const SCEVAddRecExpr *IndVar = 1871 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep))); 1872 1873 Optional<InductiveRangeCheck::Range> SafeIterRange; 1874 Instruction *ExprInsertPt = Preheader->getTerminator(); 1875 1876 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; 1877 // Basing on the type of latch predicate, we interpret the IV iteration range 1878 // as signed or unsigned range. We use different min/max functions (signed or 1879 // unsigned) when intersecting this range with safe iteration ranges implied 1880 // by range checks. 1881 auto IntersectRange = 1882 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange; 1883 1884 IRBuilder<> B(ExprInsertPt); 1885 for (InductiveRangeCheck &IRC : RangeChecks) { 1886 auto Result = IRC.computeSafeIterationSpace(SE, IndVar, 1887 LS.IsSignedPredicate); 1888 if (Result.hasValue()) { 1889 auto MaybeSafeIterRange = 1890 IntersectRange(SE, SafeIterRange, Result.getValue()); 1891 if (MaybeSafeIterRange.hasValue()) { 1892 assert( 1893 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) && 1894 "We should never return empty ranges!"); 1895 RangeChecksToEliminate.push_back(IRC); 1896 SafeIterRange = MaybeSafeIterRange.getValue(); 1897 } 1898 } 1899 } 1900 1901 if (!SafeIterRange.hasValue()) 1902 return false; 1903 1904 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, 1905 SafeIterRange.getValue()); 1906 bool Changed = LC.run(); 1907 1908 if (Changed) { 1909 auto PrintConstrainedLoopInfo = [L]() { 1910 dbgs() << "irce: in function "; 1911 dbgs() << L->getHeader()->getParent()->getName() << ": "; 1912 dbgs() << "constrained "; 1913 L->print(dbgs()); 1914 }; 1915 1916 LLVM_DEBUG(PrintConstrainedLoopInfo()); 1917 1918 if (PrintChangedLoops) 1919 PrintConstrainedLoopInfo(); 1920 1921 // Optimize away the now-redundant range checks. 1922 1923 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { 1924 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() 1925 ? ConstantInt::getTrue(Context) 1926 : ConstantInt::getFalse(Context); 1927 IRC.getCheckUse()->set(FoldedRangeCheck); 1928 } 1929 } 1930 1931 return Changed; 1932 } 1933 1934 Pass *llvm::createInductiveRangeCheckEliminationPass() { 1935 return new IRCELegacyPass(); 1936 } 1937