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