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