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