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