Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1 | //===-- InductiveRangeCheckElimination.cpp - ------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 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 | #include "llvm/ADT/Optional.h" |
| 45 | |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/InstructionSimplify.h" |
| 48 | #include "llvm/Analysis/LoopInfo.h" |
| 49 | #include "llvm/Analysis/LoopPass.h" |
| 50 | #include "llvm/Analysis/ScalarEvolution.h" |
| 51 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 52 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
| 53 | #include "llvm/Analysis/ValueTracking.h" |
| 54 | |
| 55 | #include "llvm/IR/Dominators.h" |
| 56 | #include "llvm/IR/Function.h" |
| 57 | #include "llvm/IR/Instructions.h" |
| 58 | #include "llvm/IR/IRBuilder.h" |
| 59 | #include "llvm/IR/Module.h" |
| 60 | #include "llvm/IR/PatternMatch.h" |
| 61 | #include "llvm/IR/ValueHandle.h" |
| 62 | #include "llvm/IR/Verifier.h" |
| 63 | |
| 64 | #include "llvm/Support/Debug.h" |
| 65 | |
| 66 | #include "llvm/Transforms/Scalar.h" |
| 67 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 68 | #include "llvm/Transforms/Utils/Cloning.h" |
| 69 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 70 | #include "llvm/Transforms/Utils/SimplifyIndVar.h" |
| 71 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
| 72 | |
| 73 | #include "llvm/Pass.h" |
| 74 | |
| 75 | #include <array> |
| 76 | |
| 77 | using namespace llvm; |
| 78 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 79 | static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, |
| 80 | cl::init(64)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 81 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 82 | static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, |
| 83 | cl::init(false)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 84 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 85 | static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", |
| 86 | cl::Hidden, cl::init(10)); |
| 87 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 88 | #define DEBUG_TYPE "irce" |
| 89 | |
| 90 | namespace { |
| 91 | |
| 92 | /// An inductive range check is conditional branch in a loop with |
| 93 | /// |
| 94 | /// 1. a very cold successor (i.e. the branch jumps to that successor very |
| 95 | /// rarely) |
| 96 | /// |
| 97 | /// and |
| 98 | /// |
| 99 | /// 2. a condition that is provably true for some range of values taken by the |
| 100 | /// containing loop's induction variable. |
| 101 | /// |
| 102 | /// Currently all inductive range checks are branches conditional on an |
| 103 | /// expression of the form |
| 104 | /// |
| 105 | /// 0 <= (Offset + Scale * I) < Length |
| 106 | /// |
| 107 | /// where `I' is the canonical induction variable of a loop to which Offset and |
| 108 | /// Scale are loop invariant, and Length is >= 0. Currently the 'false' branch |
| 109 | /// is considered cold, looking at profiling data to verify that is a TODO. |
| 110 | |
| 111 | class InductiveRangeCheck { |
| 112 | const SCEV *Offset; |
| 113 | const SCEV *Scale; |
| 114 | Value *Length; |
| 115 | BranchInst *Branch; |
| 116 | |
| 117 | InductiveRangeCheck() : |
| 118 | Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { } |
| 119 | |
| 120 | public: |
| 121 | const SCEV *getOffset() const { return Offset; } |
| 122 | const SCEV *getScale() const { return Scale; } |
| 123 | Value *getLength() const { return Length; } |
| 124 | |
| 125 | void print(raw_ostream &OS) const { |
| 126 | OS << "InductiveRangeCheck:\n"; |
| 127 | OS << " Offset: "; |
| 128 | Offset->print(OS); |
| 129 | OS << " Scale: "; |
| 130 | Scale->print(OS); |
| 131 | OS << " Length: "; |
| 132 | Length->print(OS); |
| 133 | OS << " Branch: "; |
| 134 | getBranch()->print(OS); |
Sanjoy Das | 48c7581 | 2015-02-26 04:03:31 +0000 | [diff] [blame] | 135 | OS << "\n"; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 139 | void dump() { |
| 140 | print(dbgs()); |
| 141 | } |
| 142 | #endif |
| 143 | |
| 144 | BranchInst *getBranch() const { return Branch; } |
| 145 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 146 | /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If |
| 147 | /// R.getEnd() sle R.getBegin(), then R denotes the empty range. |
| 148 | |
| 149 | class Range { |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 150 | const SCEV *Begin; |
| 151 | const SCEV *End; |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 152 | |
| 153 | public: |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 154 | Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 155 | assert(Begin->getType() == End->getType() && "ill-typed range!"); |
| 156 | } |
| 157 | |
| 158 | Type *getType() const { return Begin->getType(); } |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 159 | const SCEV *getBegin() const { return Begin; } |
| 160 | const SCEV *getEnd() const { return End; } |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 161 | }; |
| 162 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 163 | typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy; |
| 164 | |
| 165 | /// This is the value the condition of the branch needs to evaluate to for the |
| 166 | /// branch to take the hot successor (see (1) above). |
| 167 | bool getPassingDirection() { return true; } |
| 168 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 169 | /// Computes a range for the induction variable (IndVar) in which the range |
| 170 | /// check is redundant and can be constant-folded away. The induction |
| 171 | /// variable is not required to be the canonical {0,+,1} induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 172 | Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 173 | const SCEVAddRecExpr *IndVar, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 174 | IRBuilder<> &B) const; |
| 175 | |
| 176 | /// Create an inductive range check out of BI if possible, else return |
| 177 | /// nullptr. |
| 178 | static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI, |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 179 | Loop *L, ScalarEvolution &SE, |
| 180 | BranchProbabilityInfo &BPI); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 181 | }; |
| 182 | |
| 183 | class InductiveRangeCheckElimination : public LoopPass { |
| 184 | InductiveRangeCheck::AllocatorTy Allocator; |
| 185 | |
| 186 | public: |
| 187 | static char ID; |
| 188 | InductiveRangeCheckElimination() : LoopPass(ID) { |
| 189 | initializeInductiveRangeCheckEliminationPass( |
| 190 | *PassRegistry::getPassRegistry()); |
| 191 | } |
| 192 | |
| 193 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 194 | AU.addRequired<LoopInfoWrapperPass>(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 195 | AU.addRequiredID(LoopSimplifyID); |
| 196 | AU.addRequiredID(LCSSAID); |
| 197 | AU.addRequired<ScalarEvolution>(); |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 198 | AU.addRequired<BranchProbabilityInfo>(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 199 | } |
| 200 | |
| 201 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
| 202 | }; |
| 203 | |
| 204 | char InductiveRangeCheckElimination::ID = 0; |
| 205 | } |
| 206 | |
| 207 | INITIALIZE_PASS(InductiveRangeCheckElimination, "irce", |
| 208 | "Inductive range check elimination", false, false) |
| 209 | |
| 210 | static bool IsLowerBoundCheck(Value *Check, Value *&IndexV) { |
| 211 | using namespace llvm::PatternMatch; |
| 212 | |
| 213 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 214 | Value *LHS = nullptr, *RHS = nullptr; |
| 215 | |
| 216 | if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS)))) |
| 217 | return false; |
| 218 | |
| 219 | switch (Pred) { |
| 220 | default: |
| 221 | return false; |
| 222 | |
| 223 | case ICmpInst::ICMP_SLE: |
| 224 | std::swap(LHS, RHS); |
| 225 | // fallthrough |
| 226 | case ICmpInst::ICMP_SGE: |
| 227 | if (!match(RHS, m_ConstantInt<0>())) |
| 228 | return false; |
| 229 | IndexV = LHS; |
| 230 | return true; |
| 231 | |
| 232 | case ICmpInst::ICMP_SLT: |
| 233 | std::swap(LHS, RHS); |
| 234 | // fallthrough |
| 235 | case ICmpInst::ICMP_SGT: |
| 236 | if (!match(RHS, m_ConstantInt<-1>())) |
| 237 | return false; |
| 238 | IndexV = LHS; |
| 239 | return true; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | static bool IsUpperBoundCheck(Value *Check, Value *Index, Value *&UpperLimit) { |
| 244 | using namespace llvm::PatternMatch; |
| 245 | |
| 246 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 247 | Value *LHS = nullptr, *RHS = nullptr; |
| 248 | |
| 249 | if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS)))) |
| 250 | return false; |
| 251 | |
| 252 | switch (Pred) { |
| 253 | default: |
| 254 | return false; |
| 255 | |
| 256 | case ICmpInst::ICMP_SGT: |
| 257 | std::swap(LHS, RHS); |
| 258 | // fallthrough |
| 259 | case ICmpInst::ICMP_SLT: |
| 260 | if (LHS != Index) |
| 261 | return false; |
| 262 | UpperLimit = RHS; |
| 263 | return true; |
| 264 | |
| 265 | case ICmpInst::ICMP_UGT: |
| 266 | std::swap(LHS, RHS); |
| 267 | // fallthrough |
| 268 | case ICmpInst::ICMP_ULT: |
| 269 | if (LHS != Index) |
| 270 | return false; |
| 271 | UpperLimit = RHS; |
| 272 | return true; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// Split a condition into something semantically equivalent to (0 <= I < |
| 277 | /// Limit), both comparisons signed and Len loop invariant on L and positive. |
| 278 | /// On success, return true and set Index to I and UpperLimit to Limit. Return |
| 279 | /// false on failure (we may still write to UpperLimit and Index on failure). |
| 280 | /// It does not try to interpret I as a loop index. |
| 281 | /// |
| 282 | static bool SplitRangeCheckCondition(Loop *L, ScalarEvolution &SE, |
| 283 | Value *Condition, const SCEV *&Index, |
| 284 | Value *&UpperLimit) { |
| 285 | |
| 286 | // TODO: currently this catches some silly cases like comparing "%idx slt 1". |
| 287 | // Our transformations are still correct, but less likely to be profitable in |
| 288 | // those cases. We have to come up with some heuristics that pick out the |
| 289 | // range checks that are more profitable to clone a loop for. This function |
| 290 | // in general can be made more robust. |
| 291 | |
| 292 | using namespace llvm::PatternMatch; |
| 293 | |
| 294 | Value *A = nullptr; |
| 295 | Value *B = nullptr; |
| 296 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 297 | |
| 298 | // In these early checks we assume that the matched UpperLimit is positive. |
| 299 | // We'll verify that fact later, before returning true. |
| 300 | |
| 301 | if (match(Condition, m_And(m_Value(A), m_Value(B)))) { |
| 302 | Value *IndexV = nullptr; |
| 303 | Value *ExpectedUpperBoundCheck = nullptr; |
| 304 | |
| 305 | if (IsLowerBoundCheck(A, IndexV)) |
| 306 | ExpectedUpperBoundCheck = B; |
| 307 | else if (IsLowerBoundCheck(B, IndexV)) |
| 308 | ExpectedUpperBoundCheck = A; |
| 309 | else |
| 310 | return false; |
| 311 | |
| 312 | if (!IsUpperBoundCheck(ExpectedUpperBoundCheck, IndexV, UpperLimit)) |
| 313 | return false; |
| 314 | |
| 315 | Index = SE.getSCEV(IndexV); |
| 316 | |
| 317 | if (isa<SCEVCouldNotCompute>(Index)) |
| 318 | return false; |
| 319 | |
| 320 | } else if (match(Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) { |
| 321 | switch (Pred) { |
| 322 | default: |
| 323 | return false; |
| 324 | |
| 325 | case ICmpInst::ICMP_SGT: |
| 326 | std::swap(A, B); |
| 327 | // fall through |
| 328 | case ICmpInst::ICMP_SLT: |
| 329 | UpperLimit = B; |
| 330 | Index = SE.getSCEV(A); |
| 331 | if (isa<SCEVCouldNotCompute>(Index) || !SE.isKnownNonNegative(Index)) |
| 332 | return false; |
| 333 | break; |
| 334 | |
| 335 | case ICmpInst::ICMP_UGT: |
| 336 | std::swap(A, B); |
| 337 | // fall through |
| 338 | case ICmpInst::ICMP_ULT: |
| 339 | UpperLimit = B; |
| 340 | Index = SE.getSCEV(A); |
| 341 | if (isa<SCEVCouldNotCompute>(Index)) |
| 342 | return false; |
| 343 | break; |
| 344 | } |
| 345 | } else { |
| 346 | return false; |
| 347 | } |
| 348 | |
| 349 | const SCEV *UpperLimitSCEV = SE.getSCEV(UpperLimit); |
| 350 | if (isa<SCEVCouldNotCompute>(UpperLimitSCEV) || |
| 351 | !SE.isKnownNonNegative(UpperLimitSCEV)) |
| 352 | return false; |
| 353 | |
| 354 | if (SE.getLoopDisposition(UpperLimitSCEV, L) != |
| 355 | ScalarEvolution::LoopInvariant) { |
| 356 | DEBUG(dbgs() << " in function: " << L->getHeader()->getParent()->getName() |
| 357 | << " "; |
| 358 | dbgs() << " UpperLimit is not loop invariant: " |
| 359 | << UpperLimit->getName() << "\n";); |
| 360 | return false; |
| 361 | } |
| 362 | |
| 363 | return true; |
| 364 | } |
| 365 | |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 366 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 367 | InductiveRangeCheck * |
| 368 | InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI, |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 369 | Loop *L, ScalarEvolution &SE, |
| 370 | BranchProbabilityInfo &BPI) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 371 | |
| 372 | if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) |
| 373 | return nullptr; |
| 374 | |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 375 | BranchProbability LikelyTaken(15, 16); |
| 376 | |
| 377 | if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken) |
| 378 | return nullptr; |
| 379 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 380 | Value *Length = nullptr; |
| 381 | const SCEV *IndexSCEV = nullptr; |
| 382 | |
| 383 | if (!SplitRangeCheckCondition(L, SE, BI->getCondition(), IndexSCEV, Length)) |
| 384 | return nullptr; |
| 385 | |
| 386 | assert(IndexSCEV && Length && "contract with SplitRangeCheckCondition!"); |
| 387 | |
| 388 | const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV); |
| 389 | bool IsAffineIndex = |
| 390 | IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); |
| 391 | |
| 392 | if (!IsAffineIndex) |
| 393 | return nullptr; |
| 394 | |
| 395 | InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck; |
| 396 | IRC->Length = Length; |
| 397 | IRC->Offset = IndexAddRec->getStart(); |
| 398 | IRC->Scale = IndexAddRec->getStepRecurrence(SE); |
| 399 | IRC->Branch = BI; |
| 400 | return IRC; |
| 401 | } |
| 402 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 403 | namespace { |
| 404 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 405 | // Keeps track of the structure of a loop. This is similar to llvm::Loop, |
| 406 | // except that it is more lightweight and can track the state of a loop through |
| 407 | // changing and potentially invalid IR. This structure also formalizes the |
| 408 | // kinds of loops we can deal with -- ones that have a single latch that is also |
| 409 | // an exiting block *and* have a canonical induction variable. |
| 410 | struct LoopStructure { |
| 411 | const char *Tag; |
| 412 | |
| 413 | BasicBlock *Header; |
| 414 | BasicBlock *Latch; |
| 415 | |
| 416 | // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th |
| 417 | // successor is `LatchExit', the exit block of the loop. |
| 418 | BranchInst *LatchBr; |
| 419 | BasicBlock *LatchExit; |
| 420 | unsigned LatchBrExitIdx; |
| 421 | |
| 422 | Value *IndVarNext; |
| 423 | Value *IndVarStart; |
| 424 | Value *LoopExitAt; |
| 425 | bool IndVarIncreasing; |
| 426 | |
| 427 | LoopStructure() |
| 428 | : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr), |
| 429 | LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr), |
| 430 | IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {} |
| 431 | |
| 432 | template <typename M> LoopStructure map(M Map) const { |
| 433 | LoopStructure Result; |
| 434 | Result.Tag = Tag; |
| 435 | Result.Header = cast<BasicBlock>(Map(Header)); |
| 436 | Result.Latch = cast<BasicBlock>(Map(Latch)); |
| 437 | Result.LatchBr = cast<BranchInst>(Map(LatchBr)); |
| 438 | Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); |
| 439 | Result.LatchBrExitIdx = LatchBrExitIdx; |
| 440 | Result.IndVarNext = Map(IndVarNext); |
| 441 | Result.IndVarStart = Map(IndVarStart); |
| 442 | Result.LoopExitAt = Map(LoopExitAt); |
| 443 | Result.IndVarIncreasing = IndVarIncreasing; |
| 444 | return Result; |
| 445 | } |
| 446 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 447 | static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, |
| 448 | BranchProbabilityInfo &BPI, |
| 449 | Loop &, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 450 | const char *&); |
| 451 | }; |
| 452 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 453 | /// This class is used to constrain loops to run within a given iteration space. |
| 454 | /// The algorithm this class implements is given a Loop and a range [Begin, |
| 455 | /// End). The algorithm then tries to break out a "main loop" out of the loop |
| 456 | /// it is given in a way that the "main loop" runs with the induction variable |
| 457 | /// in a subset of [Begin, End). The algorithm emits appropriate pre and post |
| 458 | /// loops to run any remaining iterations. The pre loop runs any iterations in |
| 459 | /// which the induction variable is < Begin, and the post loop runs any |
| 460 | /// iterations in which the induction variable is >= End. |
| 461 | /// |
| 462 | class LoopConstrainer { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 463 | // The representation of a clone of the original loop we started out with. |
| 464 | struct ClonedLoop { |
| 465 | // The cloned blocks |
| 466 | std::vector<BasicBlock *> Blocks; |
| 467 | |
| 468 | // `Map` maps values in the clonee into values in the cloned version |
| 469 | ValueToValueMapTy Map; |
| 470 | |
| 471 | // An instance of `LoopStructure` for the cloned loop |
| 472 | LoopStructure Structure; |
| 473 | }; |
| 474 | |
| 475 | // Result of rewriting the range of a loop. See changeIterationSpaceEnd for |
| 476 | // more details on what these fields mean. |
| 477 | struct RewrittenRangeInfo { |
| 478 | BasicBlock *PseudoExit; |
| 479 | BasicBlock *ExitSelector; |
| 480 | std::vector<PHINode *> PHIValuesAtPseudoExit; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 481 | PHINode *IndVarEnd; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 482 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 483 | RewrittenRangeInfo() |
| 484 | : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 485 | }; |
| 486 | |
| 487 | // Calculated subranges we restrict the iteration space of the main loop to. |
| 488 | // See the implementation of `calculateSubRanges' for more details on how |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 489 | // these fields are computed. `LowLimit` is None if there is no restriction |
| 490 | // on low end of the restricted iteration space of the main loop. `HighLimit` |
| 491 | // is None if there is no restriction on high end of the restricted iteration |
| 492 | // space of the main loop. |
| 493 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 494 | struct SubRanges { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 495 | Optional<const SCEV *> LowLimit; |
| 496 | Optional<const SCEV *> HighLimit; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 497 | }; |
| 498 | |
| 499 | // A utility function that does a `replaceUsesOfWith' on the incoming block |
| 500 | // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's |
| 501 | // incoming block list with `ReplaceBy'. |
| 502 | static void replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 503 | BasicBlock *ReplaceBy); |
| 504 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 505 | // Compute a safe set of limits for the main loop to run in -- effectively the |
| 506 | // intersection of `Range' and the iteration space of the original loop. |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 507 | // Return None if unable to compute the set of subranges. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 508 | // |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 509 | Optional<SubRanges> calculateSubRanges() const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 510 | |
| 511 | // Clone `OriginalLoop' and return the result in CLResult. The IR after |
| 512 | // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- |
| 513 | // the PHI nodes say that there is an incoming edge from `OriginalPreheader` |
| 514 | // but there is no such edge. |
| 515 | // |
| 516 | void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; |
| 517 | |
| 518 | // Rewrite the iteration space of the loop denoted by (LS, Preheader). The |
| 519 | // iteration space of the rewritten loop ends at ExitLoopAt. The start of the |
| 520 | // iteration space is not changed. `ExitLoopAt' is assumed to be slt |
| 521 | // `OriginalHeaderCount'. |
| 522 | // |
| 523 | // If there are iterations left to execute, control is made to jump to |
| 524 | // `ContinuationBlock', otherwise they take the normal loop exit. The |
| 525 | // returned `RewrittenRangeInfo' object is populated as follows: |
| 526 | // |
| 527 | // .PseudoExit is a basic block that unconditionally branches to |
| 528 | // `ContinuationBlock'. |
| 529 | // |
| 530 | // .ExitSelector is a basic block that decides, on exit from the loop, |
| 531 | // whether to branch to the "true" exit or to `PseudoExit'. |
| 532 | // |
| 533 | // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value |
| 534 | // for each PHINode in the loop header on taking the pseudo exit. |
| 535 | // |
| 536 | // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate |
| 537 | // preheader because it is made to branch to the loop header only |
| 538 | // conditionally. |
| 539 | // |
| 540 | RewrittenRangeInfo |
| 541 | changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, |
| 542 | Value *ExitLoopAt, |
| 543 | BasicBlock *ContinuationBlock) const; |
| 544 | |
| 545 | // The loop denoted by `LS' has `OldPreheader' as its preheader. This |
| 546 | // function creates a new preheader for `LS' and returns it. |
| 547 | // |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 548 | BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, |
| 549 | const char *Tag) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 550 | |
| 551 | // `ContinuationBlockAndPreheader' was the continuation block for some call to |
| 552 | // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. |
| 553 | // This function rewrites the PHI nodes in `LS.Header' to start with the |
| 554 | // correct value. |
| 555 | void rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 556 | LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 557 | const LoopConstrainer::RewrittenRangeInfo &RRI) const; |
| 558 | |
| 559 | // Even though we do not preserve any passes at this time, we at least need to |
| 560 | // keep the parent loop structure consistent. The `LPPassManager' seems to |
| 561 | // verify this after running a loop pass. This function adds the list of |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 562 | // blocks denoted by BBs to this loops parent loop if required. |
| 563 | void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 564 | |
| 565 | // Some global state. |
| 566 | Function &F; |
| 567 | LLVMContext &Ctx; |
| 568 | ScalarEvolution &SE; |
| 569 | |
| 570 | // Information about the original loop we started out with. |
| 571 | Loop &OriginalLoop; |
| 572 | LoopInfo &OriginalLoopInfo; |
| 573 | const SCEV *LatchTakenCount; |
| 574 | BasicBlock *OriginalPreheader; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 575 | |
| 576 | // The preheader of the main loop. This may or may not be different from |
| 577 | // `OriginalPreheader'. |
| 578 | BasicBlock *MainLoopPreheader; |
| 579 | |
| 580 | // The range we need to run the main loop in. |
| 581 | InductiveRangeCheck::Range Range; |
| 582 | |
| 583 | // The structure of the main loop (see comment at the beginning of this class |
| 584 | // for a definition) |
| 585 | LoopStructure MainLoopStructure; |
| 586 | |
| 587 | public: |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 588 | LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS, |
| 589 | ScalarEvolution &SE, InductiveRangeCheck::Range R) |
| 590 | : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), |
| 591 | SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr), |
| 592 | OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R), |
| 593 | MainLoopStructure(LS) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 594 | |
| 595 | // Entry point for the algorithm. Returns true on success. |
| 596 | bool run(); |
| 597 | }; |
| 598 | |
| 599 | } |
| 600 | |
| 601 | void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 602 | BasicBlock *ReplaceBy) { |
| 603 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 604 | if (PN->getIncomingBlock(i) == Block) |
| 605 | PN->setIncomingBlock(i, ReplaceBy); |
| 606 | } |
| 607 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 608 | static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) { |
| 609 | APInt SMax = |
| 610 | APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()); |
| 611 | return SE.getSignedRange(S).contains(SMax) && |
| 612 | SE.getUnsignedRange(S).contains(SMax); |
| 613 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 614 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 615 | static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) { |
| 616 | APInt SMin = |
| 617 | APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()); |
| 618 | return SE.getSignedRange(S).contains(SMin) && |
| 619 | SE.getUnsignedRange(S).contains(SMin); |
| 620 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 621 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 622 | Optional<LoopStructure> |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 623 | LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI, |
| 624 | Loop &L, const char *&FailureReason) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 625 | assert(L.isLoopSimplifyForm() && "should follow from addRequired<>"); |
| 626 | |
| 627 | BasicBlock *Latch = L.getLoopLatch(); |
| 628 | if (!L.isLoopExiting(Latch)) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 629 | FailureReason = "no loop latch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 630 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 631 | } |
| 632 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 633 | BasicBlock *Header = L.getHeader(); |
| 634 | BasicBlock *Preheader = L.getLoopPreheader(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 635 | if (!Preheader) { |
| 636 | FailureReason = "no preheader"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 637 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 638 | } |
| 639 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 640 | BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 641 | if (!LatchBr || LatchBr->isUnconditional()) { |
| 642 | FailureReason = "latch terminator not conditional branch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 643 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 644 | } |
| 645 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 646 | unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 647 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 648 | BranchProbability ExitProbability = |
| 649 | BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx); |
| 650 | |
| 651 | if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { |
| 652 | FailureReason = "short running loop, not profitable"; |
| 653 | return None; |
| 654 | } |
| 655 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 656 | ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); |
| 657 | if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { |
| 658 | FailureReason = "latch terminator branch not conditional on integral icmp"; |
| 659 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 660 | } |
| 661 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 662 | const SCEV *LatchCount = SE.getExitCount(&L, Latch); |
| 663 | if (isa<SCEVCouldNotCompute>(LatchCount)) { |
| 664 | FailureReason = "could not compute latch count"; |
| 665 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 666 | } |
| 667 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 668 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 669 | Value *LeftValue = ICI->getOperand(0); |
| 670 | const SCEV *LeftSCEV = SE.getSCEV(LeftValue); |
| 671 | IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); |
| 672 | |
| 673 | Value *RightValue = ICI->getOperand(1); |
| 674 | const SCEV *RightSCEV = SE.getSCEV(RightValue); |
| 675 | |
| 676 | // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. |
| 677 | if (!isa<SCEVAddRecExpr>(LeftSCEV)) { |
| 678 | if (isa<SCEVAddRecExpr>(RightSCEV)) { |
| 679 | std::swap(LeftSCEV, RightSCEV); |
| 680 | std::swap(LeftValue, RightValue); |
| 681 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 682 | } else { |
| 683 | FailureReason = "no add recurrences in the icmp"; |
| 684 | return None; |
| 685 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 686 | } |
| 687 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 688 | auto IsInductionVar = [&SE](const SCEVAddRecExpr *AR, bool &IsIncreasing) { |
| 689 | if (!AR->isAffine()) |
| 690 | return false; |
| 691 | |
| 692 | IntegerType *Ty = cast<IntegerType>(AR->getType()); |
| 693 | IntegerType *WideTy = |
| 694 | IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); |
| 695 | |
| 696 | // Currently we only work with induction variables that have been proved to |
| 697 | // not wrap. This restriction can potentially be lifted in the future. |
| 698 | |
| 699 | const SCEVAddRecExpr *ExtendAfterOp = |
| 700 | dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); |
| 701 | if (!ExtendAfterOp) |
| 702 | return false; |
| 703 | |
| 704 | const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); |
| 705 | const SCEV *ExtendedStep = |
| 706 | SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); |
| 707 | |
| 708 | bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && |
| 709 | ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; |
| 710 | |
| 711 | if (!NoSignedWrap) |
| 712 | return false; |
| 713 | |
| 714 | if (const SCEVConstant *StepExpr = |
| 715 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) { |
| 716 | ConstantInt *StepCI = StepExpr->getValue(); |
| 717 | if (StepCI->isOne() || StepCI->isMinusOne()) { |
| 718 | IsIncreasing = StepCI->isOne(); |
| 719 | return true; |
| 720 | } |
| 721 | } |
| 722 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 723 | return false; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 724 | }; |
| 725 | |
| 726 | // `ICI` is interpreted as taking the backedge if the *next* value of the |
| 727 | // induction variable satisfies some constraint. |
| 728 | |
| 729 | const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV); |
| 730 | bool IsIncreasing = false; |
| 731 | if (!IsInductionVar(IndVarNext, IsIncreasing)) { |
| 732 | FailureReason = "LHS in icmp not induction variable"; |
| 733 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 734 | } |
| 735 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 736 | ConstantInt *One = ConstantInt::get(IndVarTy, 1); |
| 737 | // TODO: generalize the predicates here to also match their unsigned variants. |
| 738 | if (IsIncreasing) { |
| 739 | bool FoundExpectedPred = |
| 740 | (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) || |
| 741 | (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0); |
| 742 | |
| 743 | if (!FoundExpectedPred) { |
| 744 | FailureReason = "expected icmp slt semantically, found something else"; |
| 745 | return None; |
| 746 | } |
| 747 | |
| 748 | if (LatchBrExitIdx == 0) { |
| 749 | if (CanBeSMax(SE, RightSCEV)) { |
| 750 | // TODO: this restriction is easily removable -- we just have to |
| 751 | // remember that the icmp was an slt and not an sle. |
| 752 | FailureReason = "limit may overflow when coercing sle to slt"; |
| 753 | return None; |
| 754 | } |
| 755 | |
| 756 | IRBuilder<> B(&*Preheader->rbegin()); |
| 757 | RightValue = B.CreateAdd(RightValue, One); |
| 758 | } |
| 759 | |
| 760 | } else { |
| 761 | bool FoundExpectedPred = |
| 762 | (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) || |
| 763 | (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0); |
| 764 | |
| 765 | if (!FoundExpectedPred) { |
| 766 | FailureReason = "expected icmp sgt semantically, found something else"; |
| 767 | return None; |
| 768 | } |
| 769 | |
| 770 | if (LatchBrExitIdx == 0) { |
| 771 | if (CanBeSMin(SE, RightSCEV)) { |
| 772 | // TODO: this restriction is easily removable -- we just have to |
| 773 | // remember that the icmp was an sgt and not an sge. |
| 774 | FailureReason = "limit may overflow when coercing sge to sgt"; |
| 775 | return None; |
| 776 | } |
| 777 | |
| 778 | IRBuilder<> B(&*Preheader->rbegin()); |
| 779 | RightValue = B.CreateSub(RightValue, One); |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | const SCEV *StartNext = IndVarNext->getStart(); |
| 784 | const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE)); |
| 785 | const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); |
| 786 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 787 | BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); |
| 788 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 789 | assert(SE.getLoopDisposition(LatchCount, &L) == |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 790 | ScalarEvolution::LoopInvariant && |
| 791 | "loop variant exit count doesn't make sense!"); |
| 792 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 793 | assert(!L.contains(LatchExit) && "expected an exit block!"); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame^] | 794 | const DataLayout &DL = Preheader->getModule()->getDataLayout(); |
| 795 | Value *IndVarStartV = |
| 796 | SCEVExpander(SE, DL, "irce") |
| 797 | .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 798 | IndVarStartV->setName("indvar.start"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 799 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 800 | LoopStructure Result; |
| 801 | |
| 802 | Result.Tag = "main"; |
| 803 | Result.Header = Header; |
| 804 | Result.Latch = Latch; |
| 805 | Result.LatchBr = LatchBr; |
| 806 | Result.LatchExit = LatchExit; |
| 807 | Result.LatchBrExitIdx = LatchBrExitIdx; |
| 808 | Result.IndVarStart = IndVarStartV; |
| 809 | Result.IndVarNext = LeftValue; |
| 810 | Result.IndVarIncreasing = IsIncreasing; |
| 811 | Result.LoopExitAt = RightValue; |
| 812 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 813 | FailureReason = nullptr; |
| 814 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 815 | return Result; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 816 | } |
| 817 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 818 | Optional<LoopConstrainer::SubRanges> |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 819 | LoopConstrainer::calculateSubRanges() const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 820 | IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); |
| 821 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 822 | if (Range.getType() != Ty) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 823 | return None; |
| 824 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 825 | LoopConstrainer::SubRanges Result; |
| 826 | |
| 827 | // I think we can be more aggressive here and make this nuw / nsw if the |
| 828 | // addition that feeds into the icmp for the latch's terminating branch is nuw |
| 829 | // / nsw. In any case, a wrapping 2's complement addition is safe. |
| 830 | ConstantInt *One = ConstantInt::get(Ty, 1); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 831 | const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); |
| 832 | const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 833 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 834 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
| 835 | // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the |
| 836 | // range of values the induction variable takes. |
| 837 | const SCEV *Smallest = |
| 838 | Increasing ? Start : SE.getAddExpr(End, SE.getSCEV(One)); |
| 839 | const SCEV *Greatest = |
| 840 | Increasing ? End : SE.getAddExpr(Start, SE.getSCEV(One)); |
| 841 | |
| 842 | auto Clamp = [this, Smallest, Greatest](const SCEV *S) { |
| 843 | return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)); |
| 844 | }; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 845 | |
| 846 | // In some cases we can prove that we don't need a pre or post loop |
| 847 | |
| 848 | bool ProvablyNoPreloop = |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 849 | SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest); |
| 850 | if (!ProvablyNoPreloop) |
| 851 | Result.LowLimit = Clamp(Range.getBegin()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 852 | |
| 853 | bool ProvablyNoPostLoop = |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 854 | SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd()); |
| 855 | if (!ProvablyNoPostLoop) |
| 856 | Result.HighLimit = Clamp(Range.getEnd()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 857 | |
| 858 | return Result; |
| 859 | } |
| 860 | |
| 861 | void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, |
| 862 | const char *Tag) const { |
| 863 | for (BasicBlock *BB : OriginalLoop.getBlocks()) { |
| 864 | BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); |
| 865 | Result.Blocks.push_back(Clone); |
| 866 | Result.Map[BB] = Clone; |
| 867 | } |
| 868 | |
| 869 | auto GetClonedValue = [&Result](Value *V) { |
| 870 | assert(V && "null values not in domain!"); |
| 871 | auto It = Result.Map.find(V); |
| 872 | if (It == Result.Map.end()) |
| 873 | return V; |
| 874 | return static_cast<Value *>(It->second); |
| 875 | }; |
| 876 | |
| 877 | Result.Structure = MainLoopStructure.map(GetClonedValue); |
| 878 | Result.Structure.Tag = Tag; |
| 879 | |
| 880 | for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { |
| 881 | BasicBlock *ClonedBB = Result.Blocks[i]; |
| 882 | BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; |
| 883 | |
| 884 | assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); |
| 885 | |
| 886 | for (Instruction &I : *ClonedBB) |
| 887 | RemapInstruction(&I, Result.Map, |
| 888 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
| 889 | |
| 890 | // Exit blocks will now have one more predecessor and their PHI nodes need |
| 891 | // to be edited to reflect that. No phi nodes need to be introduced because |
| 892 | // the loop is in LCSSA. |
| 893 | |
| 894 | for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB); |
| 895 | SBBI != SBBE; ++SBBI) { |
| 896 | |
| 897 | if (OriginalLoop.contains(*SBBI)) |
| 898 | continue; // not an exit block |
| 899 | |
| 900 | for (Instruction &I : **SBBI) { |
| 901 | if (!isa<PHINode>(&I)) |
| 902 | break; |
| 903 | |
| 904 | PHINode *PN = cast<PHINode>(&I); |
| 905 | Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB); |
| 906 | PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB); |
| 907 | } |
| 908 | } |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 913 | const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 914 | BasicBlock *ContinuationBlock) const { |
| 915 | |
| 916 | // We start with a loop with a single latch: |
| 917 | // |
| 918 | // +--------------------+ |
| 919 | // | | |
| 920 | // | preheader | |
| 921 | // | | |
| 922 | // +--------+-----------+ |
| 923 | // | ----------------\ |
| 924 | // | / | |
| 925 | // +--------v----v------+ | |
| 926 | // | | | |
| 927 | // | header | | |
| 928 | // | | | |
| 929 | // +--------------------+ | |
| 930 | // | |
| 931 | // ..... | |
| 932 | // | |
| 933 | // +--------------------+ | |
| 934 | // | | | |
| 935 | // | latch >----------/ |
| 936 | // | | |
| 937 | // +-------v------------+ |
| 938 | // | |
| 939 | // | |
| 940 | // | +--------------------+ |
| 941 | // | | | |
| 942 | // +---> original exit | |
| 943 | // | | |
| 944 | // +--------------------+ |
| 945 | // |
| 946 | // We change the control flow to look like |
| 947 | // |
| 948 | // |
| 949 | // +--------------------+ |
| 950 | // | | |
| 951 | // | preheader >-------------------------+ |
| 952 | // | | | |
| 953 | // +--------v-----------+ | |
| 954 | // | /-------------+ | |
| 955 | // | / | | |
| 956 | // +--------v--v--------+ | | |
| 957 | // | | | | |
| 958 | // | header | | +--------+ | |
| 959 | // | | | | | | |
| 960 | // +--------------------+ | | +-----v-----v-----------+ |
| 961 | // | | | | |
| 962 | // | | | .pseudo.exit | |
| 963 | // | | | | |
| 964 | // | | +-----------v-----------+ |
| 965 | // | | | |
| 966 | // ..... | | | |
| 967 | // | | +--------v-------------+ |
| 968 | // +--------------------+ | | | | |
| 969 | // | | | | | ContinuationBlock | |
| 970 | // | latch >------+ | | | |
| 971 | // | | | +----------------------+ |
| 972 | // +---------v----------+ | |
| 973 | // | | |
| 974 | // | | |
| 975 | // | +---------------^-----+ |
| 976 | // | | | |
| 977 | // +-----> .exit.selector | |
| 978 | // | | |
| 979 | // +----------v----------+ |
| 980 | // | |
| 981 | // +--------------------+ | |
| 982 | // | | | |
| 983 | // | original exit <----+ |
| 984 | // | | |
| 985 | // +--------------------+ |
| 986 | // |
| 987 | |
| 988 | RewrittenRangeInfo RRI; |
| 989 | |
| 990 | auto BBInsertLocation = std::next(Function::iterator(LS.Latch)); |
| 991 | RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", |
| 992 | &F, BBInsertLocation); |
| 993 | RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, |
| 994 | BBInsertLocation); |
| 995 | |
| 996 | BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 997 | bool Increasing = LS.IndVarIncreasing; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 998 | |
| 999 | IRBuilder<> B(PreheaderJump); |
| 1000 | |
| 1001 | // EnterLoopCond - is it okay to start executing this `LS'? |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1002 | Value *EnterLoopCond = Increasing |
| 1003 | ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) |
| 1004 | : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt); |
| 1005 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1006 | B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); |
| 1007 | PreheaderJump->eraseFromParent(); |
| 1008 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1009 | LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1010 | B.SetInsertPoint(LS.LatchBr); |
| 1011 | Value *TakeBackedgeLoopCond = |
| 1012 | Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt) |
| 1013 | : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt); |
| 1014 | Value *CondForBranch = LS.LatchBrExitIdx == 1 |
| 1015 | ? TakeBackedgeLoopCond |
| 1016 | : B.CreateNot(TakeBackedgeLoopCond); |
| 1017 | |
| 1018 | LS.LatchBr->setCondition(CondForBranch); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1019 | |
| 1020 | B.SetInsertPoint(RRI.ExitSelector); |
| 1021 | |
| 1022 | // IterationsLeft - are there any more iterations left, given the original |
| 1023 | // upper bound on the induction variable? If not, we branch to the "real" |
| 1024 | // exit. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1025 | Value *IterationsLeft = Increasing |
| 1026 | ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt) |
| 1027 | : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1028 | B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); |
| 1029 | |
| 1030 | BranchInst *BranchToContinuation = |
| 1031 | BranchInst::Create(ContinuationBlock, RRI.PseudoExit); |
| 1032 | |
| 1033 | // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of |
| 1034 | // each of the PHI nodes in the loop header. This feeds into the initial |
| 1035 | // value of the same PHI nodes if/when we continue execution. |
| 1036 | for (Instruction &I : *LS.Header) { |
| 1037 | if (!isa<PHINode>(&I)) |
| 1038 | break; |
| 1039 | |
| 1040 | PHINode *PN = cast<PHINode>(&I); |
| 1041 | |
| 1042 | PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy", |
| 1043 | BranchToContinuation); |
| 1044 | |
| 1045 | NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader); |
| 1046 | NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch), |
| 1047 | RRI.ExitSelector); |
| 1048 | RRI.PHIValuesAtPseudoExit.push_back(NewPHI); |
| 1049 | } |
| 1050 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1051 | RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end", |
| 1052 | BranchToContinuation); |
| 1053 | RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); |
| 1054 | RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector); |
| 1055 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1056 | // The latch exit now has a branch from `RRI.ExitSelector' instead of |
| 1057 | // `LS.Latch'. The PHI nodes need to be updated to reflect that. |
| 1058 | for (Instruction &I : *LS.LatchExit) { |
| 1059 | if (PHINode *PN = dyn_cast<PHINode>(&I)) |
| 1060 | replacePHIBlock(PN, LS.Latch, RRI.ExitSelector); |
| 1061 | else |
| 1062 | break; |
| 1063 | } |
| 1064 | |
| 1065 | return RRI; |
| 1066 | } |
| 1067 | |
| 1068 | void LoopConstrainer::rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1069 | LoopStructure &LS, BasicBlock *ContinuationBlock, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1070 | const LoopConstrainer::RewrittenRangeInfo &RRI) const { |
| 1071 | |
| 1072 | unsigned PHIIndex = 0; |
| 1073 | for (Instruction &I : *LS.Header) { |
| 1074 | if (!isa<PHINode>(&I)) |
| 1075 | break; |
| 1076 | |
| 1077 | PHINode *PN = cast<PHINode>(&I); |
| 1078 | |
| 1079 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) |
| 1080 | if (PN->getIncomingBlock(i) == ContinuationBlock) |
| 1081 | PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); |
| 1082 | } |
| 1083 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1084 | LS.IndVarStart = RRI.IndVarEnd; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1085 | } |
| 1086 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1087 | BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, |
| 1088 | BasicBlock *OldPreheader, |
| 1089 | const char *Tag) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1090 | |
| 1091 | BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); |
| 1092 | BranchInst::Create(LS.Header, Preheader); |
| 1093 | |
| 1094 | for (Instruction &I : *LS.Header) { |
| 1095 | if (!isa<PHINode>(&I)) |
| 1096 | break; |
| 1097 | |
| 1098 | PHINode *PN = cast<PHINode>(&I); |
| 1099 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) |
| 1100 | replacePHIBlock(PN, OldPreheader, Preheader); |
| 1101 | } |
| 1102 | |
| 1103 | return Preheader; |
| 1104 | } |
| 1105 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1106 | void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1107 | Loop *ParentLoop = OriginalLoop.getParentLoop(); |
| 1108 | if (!ParentLoop) |
| 1109 | return; |
| 1110 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1111 | for (BasicBlock *BB : BBs) |
| 1112 | ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1113 | } |
| 1114 | |
| 1115 | bool LoopConstrainer::run() { |
| 1116 | BasicBlock *Preheader = nullptr; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1117 | LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); |
| 1118 | Preheader = OriginalLoop.getLoopPreheader(); |
| 1119 | assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && |
| 1120 | "preconditions!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1121 | |
| 1122 | OriginalPreheader = Preheader; |
| 1123 | MainLoopPreheader = Preheader; |
| 1124 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1125 | Optional<SubRanges> MaybeSR = calculateSubRanges(); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1126 | if (!MaybeSR.hasValue()) { |
| 1127 | DEBUG(dbgs() << "irce: could not compute subranges\n"); |
| 1128 | return false; |
| 1129 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1130 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1131 | SubRanges SR = MaybeSR.getValue(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1132 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
| 1133 | IntegerType *IVTy = |
| 1134 | cast<IntegerType>(MainLoopStructure.IndVarNext->getType()); |
| 1135 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame^] | 1136 | SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1137 | Instruction *InsertPt = OriginalPreheader->getTerminator(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1138 | |
| 1139 | // It would have been better to make `PreLoop' and `PostLoop' |
| 1140 | // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy |
| 1141 | // constructor. |
| 1142 | ClonedLoop PreLoop, PostLoop; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1143 | bool NeedsPreLoop = |
| 1144 | Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); |
| 1145 | bool NeedsPostLoop = |
| 1146 | Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); |
| 1147 | |
| 1148 | Value *ExitPreLoopAt = nullptr; |
| 1149 | Value *ExitMainLoopAt = nullptr; |
| 1150 | const SCEVConstant *MinusOneS = |
| 1151 | cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); |
| 1152 | |
| 1153 | if (NeedsPreLoop) { |
| 1154 | const SCEV *ExitPreLoopAtSCEV = nullptr; |
| 1155 | |
| 1156 | if (Increasing) |
| 1157 | ExitPreLoopAtSCEV = *SR.LowLimit; |
| 1158 | else { |
| 1159 | if (CanBeSMin(SE, *SR.HighLimit)) { |
| 1160 | DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1161 | << "preloop exit limit. HighLimit = " << *(*SR.HighLimit) |
| 1162 | << "\n"); |
| 1163 | return false; |
| 1164 | } |
| 1165 | ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); |
| 1166 | } |
| 1167 | |
| 1168 | ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); |
| 1169 | ExitPreLoopAt->setName("exit.preloop.at"); |
| 1170 | } |
| 1171 | |
| 1172 | if (NeedsPostLoop) { |
| 1173 | const SCEV *ExitMainLoopAtSCEV = nullptr; |
| 1174 | |
| 1175 | if (Increasing) |
| 1176 | ExitMainLoopAtSCEV = *SR.HighLimit; |
| 1177 | else { |
| 1178 | if (CanBeSMin(SE, *SR.LowLimit)) { |
| 1179 | DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1180 | << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit) |
| 1181 | << "\n"); |
| 1182 | return false; |
| 1183 | } |
| 1184 | ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); |
| 1185 | } |
| 1186 | |
| 1187 | ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); |
| 1188 | ExitMainLoopAt->setName("exit.mainloop.at"); |
| 1189 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1190 | |
| 1191 | // We clone these ahead of time so that we don't have to deal with changing |
| 1192 | // and temporarily invalid IR as we transform the loops. |
| 1193 | if (NeedsPreLoop) |
| 1194 | cloneLoop(PreLoop, "preloop"); |
| 1195 | if (NeedsPostLoop) |
| 1196 | cloneLoop(PostLoop, "postloop"); |
| 1197 | |
| 1198 | RewrittenRangeInfo PreLoopRRI; |
| 1199 | |
| 1200 | if (NeedsPreLoop) { |
| 1201 | Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, |
| 1202 | PreLoop.Structure.Header); |
| 1203 | |
| 1204 | MainLoopPreheader = |
| 1205 | createPreheader(MainLoopStructure, Preheader, "mainloop"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1206 | PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, |
| 1207 | ExitPreLoopAt, MainLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1208 | rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, |
| 1209 | PreLoopRRI); |
| 1210 | } |
| 1211 | |
| 1212 | BasicBlock *PostLoopPreheader = nullptr; |
| 1213 | RewrittenRangeInfo PostLoopRRI; |
| 1214 | |
| 1215 | if (NeedsPostLoop) { |
| 1216 | PostLoopPreheader = |
| 1217 | createPreheader(PostLoop.Structure, Preheader, "postloop"); |
| 1218 | PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1219 | ExitMainLoopAt, PostLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1220 | rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, |
| 1221 | PostLoopRRI); |
| 1222 | } |
| 1223 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1224 | BasicBlock *NewMainLoopPreheader = |
| 1225 | MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; |
| 1226 | BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, |
| 1227 | PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, |
| 1228 | PostLoopRRI.ExitSelector, NewMainLoopPreheader}; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1229 | |
| 1230 | // Some of the above may be nullptr, filter them out before passing to |
| 1231 | // addToParentLoopIfNeeded. |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1232 | auto NewBlocksEnd = |
| 1233 | std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1234 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1235 | addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); |
| 1236 | addToParentLoopIfNeeded(PreLoop.Blocks); |
| 1237 | addToParentLoopIfNeeded(PostLoop.Blocks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1238 | |
| 1239 | return true; |
| 1240 | } |
| 1241 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1242 | /// Computes and returns a range of values for the induction variable (IndVar) |
| 1243 | /// in which the range check can be safely elided. If it cannot compute such a |
| 1244 | /// range, returns None. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1245 | Optional<InductiveRangeCheck::Range> |
| 1246 | InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE, |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1247 | const SCEVAddRecExpr *IndVar, |
| 1248 | IRBuilder<> &) const { |
| 1249 | // IndVar is of the form "A + B * I" (where "I" is the canonical induction |
| 1250 | // variable, that may or may not exist as a real llvm::Value in the loop) and |
| 1251 | // this inductive range check is a range check on the "C + D * I" ("C" is |
| 1252 | // getOffset() and "D" is getScale()). We rewrite the value being range |
| 1253 | // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". |
| 1254 | // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code |
| 1255 | // can be generalized as needed. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1256 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1257 | // The actual inequalities we solve are of the form |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1258 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1259 | // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) |
| 1260 | // |
| 1261 | // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions |
| 1262 | // and subtractions are twos-complement wrapping and comparisons are signed. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1263 | // |
| 1264 | // Proof: |
| 1265 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1266 | // If there exists IndVar such that -M <= IndVar < (L - M) then it follows |
| 1267 | // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows |
| 1268 | // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have |
| 1269 | // overflown. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1270 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1271 | // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t. |
| 1272 | // Hence 0 <= (IndVar + M) < L |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1273 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1274 | // [^1]: Note that the solution does _not_ apply if L < 0; consider values M = |
| 1275 | // 127, IndVar = 126 and L = -2 in an i8 world. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1276 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1277 | if (!IndVar->isAffine()) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1278 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1279 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1280 | const SCEV *A = IndVar->getStart(); |
| 1281 | const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); |
| 1282 | if (!B) |
| 1283 | return None; |
| 1284 | |
| 1285 | const SCEV *C = getOffset(); |
| 1286 | const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale()); |
| 1287 | if (D != B) |
| 1288 | return None; |
| 1289 | |
| 1290 | ConstantInt *ConstD = D->getValue(); |
| 1291 | if (!(ConstD->isMinusOne() || ConstD->isOne())) |
| 1292 | return None; |
| 1293 | |
| 1294 | const SCEV *M = SE.getMinusSCEV(C, A); |
| 1295 | |
| 1296 | const SCEV *Begin = SE.getNegativeSCEV(M); |
| 1297 | const SCEV *End = SE.getMinusSCEV(SE.getSCEV(getLength()), M); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1298 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1299 | return InductiveRangeCheck::Range(Begin, End); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1300 | } |
| 1301 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1302 | static Optional<InductiveRangeCheck::Range> |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1303 | IntersectRange(ScalarEvolution &SE, |
| 1304 | const Optional<InductiveRangeCheck::Range> &R1, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1305 | const InductiveRangeCheck::Range &R2, IRBuilder<> &B) { |
| 1306 | if (!R1.hasValue()) |
| 1307 | return R2; |
| 1308 | auto &R1Value = R1.getValue(); |
| 1309 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1310 | // TODO: we could widen the smaller range and have this work; but for now we |
| 1311 | // bail out to keep things simple. |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1312 | if (R1Value.getType() != R2.getType()) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1313 | return None; |
| 1314 | |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1315 | const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); |
| 1316 | const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); |
| 1317 | |
| 1318 | return InductiveRangeCheck::Range(NewBegin, NewEnd); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1319 | } |
| 1320 | |
| 1321 | bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) { |
| 1322 | if (L->getBlocks().size() >= LoopSizeCutoff) { |
| 1323 | DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";); |
| 1324 | return false; |
| 1325 | } |
| 1326 | |
| 1327 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 1328 | if (!Preheader) { |
| 1329 | DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); |
| 1330 | return false; |
| 1331 | } |
| 1332 | |
| 1333 | LLVMContext &Context = Preheader->getContext(); |
| 1334 | InductiveRangeCheck::AllocatorTy IRCAlloc; |
| 1335 | SmallVector<InductiveRangeCheck *, 16> RangeChecks; |
| 1336 | ScalarEvolution &SE = getAnalysis<ScalarEvolution>(); |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 1337 | BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1338 | |
| 1339 | for (auto BBI : L->getBlocks()) |
| 1340 | if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) |
| 1341 | if (InductiveRangeCheck *IRC = |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 1342 | InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI)) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1343 | RangeChecks.push_back(IRC); |
| 1344 | |
| 1345 | if (RangeChecks.empty()) |
| 1346 | return false; |
| 1347 | |
| 1348 | DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs()); |
| 1349 | dbgs() << "irce: loop has " << RangeChecks.size() |
| 1350 | << " inductive range checks: \n"; |
| 1351 | for (InductiveRangeCheck *IRC : RangeChecks) |
| 1352 | IRC->print(dbgs()); |
| 1353 | ); |
| 1354 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1355 | const char *FailureReason = nullptr; |
| 1356 | Optional<LoopStructure> MaybeLoopStructure = |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 1357 | LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1358 | if (!MaybeLoopStructure.hasValue()) { |
| 1359 | DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason |
| 1360 | << "\n";); |
| 1361 | return false; |
| 1362 | } |
| 1363 | LoopStructure LS = MaybeLoopStructure.getValue(); |
| 1364 | bool Increasing = LS.IndVarIncreasing; |
| 1365 | const SCEV *MinusOne = |
| 1366 | SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true); |
| 1367 | const SCEVAddRecExpr *IndVar = |
| 1368 | cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne)); |
| 1369 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1370 | Optional<InductiveRangeCheck::Range> SafeIterRange; |
| 1371 | Instruction *ExprInsertPt = Preheader->getTerminator(); |
| 1372 | |
| 1373 | SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate; |
| 1374 | |
| 1375 | IRBuilder<> B(ExprInsertPt); |
| 1376 | for (InductiveRangeCheck *IRC : RangeChecks) { |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1377 | auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1378 | if (Result.hasValue()) { |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1379 | auto MaybeSafeIterRange = |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1380 | IntersectRange(SE, SafeIterRange, Result.getValue(), B); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1381 | if (MaybeSafeIterRange.hasValue()) { |
| 1382 | RangeChecksToEliminate.push_back(IRC); |
| 1383 | SafeIterRange = MaybeSafeIterRange.getValue(); |
| 1384 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | if (!SafeIterRange.hasValue()) |
| 1389 | return false; |
| 1390 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1391 | LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS, |
| 1392 | SE, SafeIterRange.getValue()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1393 | bool Changed = LC.run(); |
| 1394 | |
| 1395 | if (Changed) { |
| 1396 | auto PrintConstrainedLoopInfo = [L]() { |
| 1397 | dbgs() << "irce: in function "; |
| 1398 | dbgs() << L->getHeader()->getParent()->getName() << ": "; |
| 1399 | dbgs() << "constrained "; |
| 1400 | L->print(dbgs()); |
| 1401 | }; |
| 1402 | |
| 1403 | DEBUG(PrintConstrainedLoopInfo()); |
| 1404 | |
| 1405 | if (PrintChangedLoops) |
| 1406 | PrintConstrainedLoopInfo(); |
| 1407 | |
| 1408 | // Optimize away the now-redundant range checks. |
| 1409 | |
| 1410 | for (InductiveRangeCheck *IRC : RangeChecksToEliminate) { |
| 1411 | ConstantInt *FoldedRangeCheck = IRC->getPassingDirection() |
| 1412 | ? ConstantInt::getTrue(Context) |
| 1413 | : ConstantInt::getFalse(Context); |
| 1414 | IRC->getBranch()->setCondition(FoldedRangeCheck); |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | return Changed; |
| 1419 | } |
| 1420 | |
| 1421 | Pass *llvm::createInductiveRangeCheckEliminationPass() { |
| 1422 | return new InductiveRangeCheckElimination; |
| 1423 | } |