blob: 5b4b6c14693ed4e036369424b51a6fd380ef92dc [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- 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 Dasdcf26512015-01-27 21:38:12 +000045#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000046#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 Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/IR/Module.h"
58#include "llvm/IR/PatternMatch.h"
59#include "llvm/IR/ValueHandle.h"
60#include "llvm/IR/Verifier.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000061#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000062#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000063#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064#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 Dasa1837a32015-01-16 01:03:22 +000070
71using namespace llvm;
72
Benjamin Kramer970eac42015-02-06 17:51:54 +000073static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
74 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000075
Benjamin Kramer970eac42015-02-06 17:51:54 +000076static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
77 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000078
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000079static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
80 cl::init(false));
81
Sanjoy Dase91665d2015-02-26 08:56:04 +000082static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
83 cl::Hidden, cl::init(10));
84
Sanjoy Dasa1837a32015-01-16 01:03:22 +000085#define DEBUG_TYPE "irce"
86
87namespace {
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 Dase2cde6f2015-03-17 00:42:13 +000096/// 2. a condition that is provably true for some contiguous range of values
97/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000099class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000100 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000101 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000102 // 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 Das2eac48d2016-03-09 02:34:19 +0000116 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000117
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000118 const SCEV *Offset;
119 const SCEV *Scale;
120 Value *Length;
121 BranchInst *Branch;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122 RangeCheckKind Kind;
123
Sanjoy Das337d46b2015-03-24 19:29:18 +0000124 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
125 ScalarEvolution &SE, Value *&Index,
126 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000127
128 static InductiveRangeCheck::RangeCheckKind
129 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
130 const SCEV *&Index, Value *&UpperLimit);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
132 InductiveRangeCheck() :
133 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
134
135public:
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 Dase2cde6f2015-03-17 00:42:13 +0000142 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000143 OS << " Offset: ";
144 Offset->print(OS);
145 OS << " Scale: ";
146 Scale->print(OS);
147 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000148 if (Length)
149 Length->print(OS);
150 else
151 OS << "(null)";
152 OS << "\n Branch: ";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000153 getBranch()->print(OS);
Sanjoy Das48c75812015-02-26 04:03:31 +0000154 OS << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 }
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 Das351db052015-01-22 09:32:02 +0000165 /// 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 Das7fc60da2015-02-21 22:07:32 +0000169 const SCEV *Begin;
170 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000171
172 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000173 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000174 assert(Begin->getType() == End->getType() && "ill-typed range!");
175 }
176
177 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000178 const SCEV *getBegin() const { return Begin; }
179 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000180 };
181
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000182 /// 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 Das95c476d2015-02-21 22:20:22 +0000186 /// 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 Dasa1837a32015-01-16 01:03:22 +0000189 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000190 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000192 /// 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 Dasa1837a32015-01-16 01:03:22 +0000196};
197
198class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000199public:
200 static char ID;
201 InductiveRangeCheckElimination() : LoopPass(ID) {
202 initializeInductiveRangeCheckEliminationPass(
203 *PassRegistry::getPassRegistry());
204 }
205
206 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000207 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000208 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000209 }
210
211 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
212};
213
214char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000215}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000216
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000217INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
218 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000219INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000220INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000221INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
222 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000224StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000225 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 Dasf13900f2016-03-09 02:34:15 +0000243/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000244/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000245/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000246/// 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///
250InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000251InductiveRangeCheck::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 Dase2cde6f2015-03-17 00:42:13 +0000263
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000264 using namespace llvm::PatternMatch;
265
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000266 ICmpInst::Predicate Pred = ICI->getPredicate();
267 Value *LHS = ICI->getOperand(0);
268 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000269
270 switch (Pred) {
271 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000272 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000273
274 case ICmpInst::ICMP_SLE:
275 std::swap(LHS, RHS);
276 // fallthrough
277 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000278 if (match(RHS, m_ConstantInt<0>())) {
279 Index = LHS;
280 return RANGE_CHECK_LOWER;
281 }
282 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000283
284 case ICmpInst::ICMP_SLT:
285 std::swap(LHS, RHS);
286 // fallthrough
287 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000288 if (match(RHS, m_ConstantInt<-1>())) {
289 Index = LHS;
290 return RANGE_CHECK_LOWER;
291 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000292
Sanjoy Das337d46b2015-03-24 19:29:18 +0000293 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000294 Index = RHS;
295 Length = LHS;
296 return RANGE_CHECK_UPPER;
297 }
298 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000299
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000300 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000301 std::swap(LHS, RHS);
302 // fallthrough
303 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000304 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000305 Index = RHS;
306 Length = LHS;
307 return RANGE_CHECK_BOTH;
308 }
309 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000310 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000311
312 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000313}
314
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000315/// 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.
317InductiveRangeCheck::RangeCheckKind
318InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000319 Value *Condition, const SCEV *&Index,
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000320 Value *&Length) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000321 using namespace llvm::PatternMatch;
322
323 Value *A = nullptr;
324 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000325
326 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000327 Value *IndexA = nullptr, *IndexB = nullptr;
328 Value *LengthA = nullptr, *LengthB = nullptr;
329 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000330
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000331 if (!ICmpA || !ICmpB)
332 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000333
Sanjoy Das337d46b2015-03-24 19:29:18 +0000334 auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
335 auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000336
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000337 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
338 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
339 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000340
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000341 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 Dasa1837a32015-01-16 01:03:22 +0000348 if (isa<SCEVCouldNotCompute>(Index))
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000349 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000350
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000351 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000352
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000353 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354 }
355
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000356 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
357 Value *IndexVal = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358
Sanjoy Das337d46b2015-03-24 19:29:18 +0000359 auto RCKind = parseRangeCheckICmp(L, ICI, SE, IndexVal, Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000360
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 Dasa1837a32015-01-16 01:03:22 +0000369 }
370
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000371 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000372}
373
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000374Optional<InductiveRangeCheck>
375InductiveRangeCheck::create(BranchInst *BI, Loop *L, ScalarEvolution &SE,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000376 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000377
378 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000379 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000380
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000381 BranchProbability LikelyTaken(15, 16);
382
383 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000384 return None;
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000385
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000386 Value *Length = nullptr;
387 const SCEV *IndexSCEV = nullptr;
388
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000389 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
390 IndexSCEV, Length);
391
392 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000393 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000394
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000395 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
David Blaikiec4dfa632015-03-17 17:48:24 +0000396 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
397 "contract with SplitRangeCheckCondition!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000398
399 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
400 bool IsAffineIndex =
401 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
402
403 if (!IsAffineIndex)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000404 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000405
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000406 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 Dasa1837a32015-01-16 01:03:22 +0000412 return IRC;
413}
414
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000415namespace {
416
Sanjoy Dase75ed922015-02-26 08:19:31 +0000417// 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.
422struct 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 Dase91665d2015-02-26 08:56:04 +0000459 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
460 BranchProbabilityInfo &BPI,
461 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000462 const char *&);
463};
464
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000465/// 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///
474class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000475 // 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 Dase75ed922015-02-26 08:19:31 +0000493 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000494
Sanjoy Dase75ed922015-02-26 08:19:31 +0000495 RewrittenRangeInfo()
496 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000497 };
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 Dase75ed922015-02-26 08:19:31 +0000501 // 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 Dasa1837a32015-01-16 01:03:22 +0000506 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000507 Optional<const SCEV *> LowLimit;
508 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000509 };
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 Dasa1837a32015-01-16 01:03:22 +0000517 // 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 Dasd1fb13c2015-01-22 08:29:18 +0000519 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000520 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000521 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000522
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 Dase75ed922015-02-26 08:19:31 +0000560 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
561 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562
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 Dase75ed922015-02-26 08:19:31 +0000568 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000569 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 Kramer39f76ac2015-02-06 14:43:49 +0000574 // blocks denoted by BBs to this loops parent loop if required.
575 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000576
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 Dasa1837a32015-01-16 01:03:22 +0000587
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
599public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000600 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 Dasa1837a32015-01-16 01:03:22 +0000606
607 // Entry point for the algorithm. Returns true on success.
608 bool run();
609};
610
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000611}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000612
613void 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 Dase75ed922015-02-26 08:19:31 +0000620static 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 Dasa1837a32015-01-16 01:03:22 +0000626
Sanjoy Dase75ed922015-02-26 08:19:31 +0000627static 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 Dasa1837a32015-01-16 01:03:22 +0000633
Sanjoy Dase75ed922015-02-26 08:19:31 +0000634Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000635LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
636 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000637 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
638
639 BasicBlock *Latch = L.getLoopLatch();
640 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000642 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000643 }
644
Sanjoy Dase75ed922015-02-26 08:19:31 +0000645 BasicBlock *Header = L.getHeader();
646 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647 if (!Preheader) {
648 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000649 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000650 }
651
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000653 if (!LatchBr || LatchBr->isUnconditional()) {
654 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000655 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000656 }
657
Sanjoy Dase75ed922015-02-26 08:19:31 +0000658 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000659
Sanjoy Dase91665d2015-02-26 08:56:04 +0000660 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 Dase75ed922015-02-26 08:19:31 +0000668 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 Dasa1837a32015-01-16 01:03:22 +0000672 }
673
Sanjoy Dase75ed922015-02-26 08:19:31 +0000674 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
675 if (isa<SCEVCouldNotCompute>(LatchCount)) {
676 FailureReason = "could not compute latch count";
677 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000678 }
679
Sanjoy Dase75ed922015-02-26 08:19:31 +0000680 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 Dasa1837a32015-01-16 01:03:22 +0000698 }
699
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000700 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
701 if (AR->getNoWrapFlags(SCEV::FlagNSW))
702 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000703
704 IntegerType *Ty = cast<IntegerType>(AR->getType());
705 IntegerType *WideTy =
706 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
707
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000708 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 Dase75ed922015-02-26 08:19:31 +0000730 // 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 Das45dc94a2015-03-24 19:29:22 +0000733 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000734 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 Dasa1837a32015-01-16 01:03:22 +0000745 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000746 };
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 Dasa1837a32015-01-16 01:03:22 +0000756 }
757
Sanjoy Dase75ed922015-02-26 08:19:31 +0000758 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 Dasa1837a32015-01-16 01:03:22 +0000809 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
810
Sanjoy Dase75ed922015-02-26 08:19:31 +0000811 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000812 ScalarEvolution::LoopInvariant &&
813 "loop variant exit count doesn't make sense!");
814
Sanjoy Dase75ed922015-02-26 08:19:31 +0000815 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000816 const DataLayout &DL = Preheader->getModule()->getDataLayout();
817 Value *IndVarStartV =
818 SCEVExpander(SE, DL, "irce")
819 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000820 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000821
Sanjoy Dase75ed922015-02-26 08:19:31 +0000822 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 Dasa1837a32015-01-16 01:03:22 +0000835 FailureReason = nullptr;
836
Sanjoy Dase75ed922015-02-26 08:19:31 +0000837 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000838}
839
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000840Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000841LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000842 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
843
Sanjoy Das351db052015-01-22 09:32:02 +0000844 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000845 return None;
846
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000847 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 Dase75ed922015-02-26 08:19:31 +0000853 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
854 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000855
Sanjoy Dase75ed922015-02-26 08:19:31 +0000856 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000857
Sanjoy Dase75ed922015-02-26 08:19:31 +0000858 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
859 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000860
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 Dase75ed922015-02-26 08:19:31 +0000886
887 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
888 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
889 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000890
891 // In some cases we can prove that we don't need a pre or post loop
892
893 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000894 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
895 if (!ProvablyNoPreloop)
896 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000897
898 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000899 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
900 if (!ProvablyNoPostLoop)
901 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000902
903 return Result;
904}
905
906void 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 Smithda68cbc2016-04-07 00:26:43 +0000933 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000934
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
957LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000958 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000959 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 Smith3a9c9e32015-10-13 18:26:00 +00001037 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001038 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001039 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001040
1041 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001042 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001043
1044 IRBuilder<> B(PreheaderJump);
1045
1046 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001047 Value *EnterLoopCond = Increasing
1048 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1049 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1050
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001051 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1052 PreheaderJump->eraseFromParent();
1053
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001054 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001055 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 Dasa1837a32015-01-16 01:03:22 +00001064
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 Dase75ed922015-02-26 08:19:31 +00001070 Value *IterationsLeft = Increasing
1071 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1072 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001073 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 Dase75ed922015-02-26 08:19:31 +00001096 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 Dasa1837a32015-01-16 01:03:22 +00001101 // 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
1113void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001114 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001115 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 Dase75ed922015-02-26 08:19:31 +00001129 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001130}
1131
Sanjoy Dase75ed922015-02-26 08:19:31 +00001132BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1133 BasicBlock *OldPreheader,
1134 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001135
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 Kramer39f76ac2015-02-06 14:43:49 +00001151void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001152 Loop *ParentLoop = OriginalLoop.getParentLoop();
1153 if (!ParentLoop)
1154 return;
1155
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001156 for (BasicBlock *BB : BBs)
1157 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001158}
1159
1160bool LoopConstrainer::run() {
1161 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001162 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1163 Preheader = OriginalLoop.getLoopPreheader();
1164 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1165 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001166
1167 OriginalPreheader = Preheader;
1168 MainLoopPreheader = Preheader;
1169
Sanjoy Dase75ed922015-02-26 08:19:31 +00001170 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001171 if (!MaybeSR.hasValue()) {
1172 DEBUG(dbgs() << "irce: could not compute subranges\n");
1173 return false;
1174 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001175
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001176 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001177 bool Increasing = MainLoopStructure.IndVarIncreasing;
1178 IntegerType *IVTy =
1179 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1180
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001181 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001182 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001183
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 Dase75ed922015-02-26 08:19:31 +00001188 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 Dasa1837a32015-01-16 01:03:22 +00001235
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 Dase75ed922015-02-26 08:19:31 +00001251 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1252 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001253 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 Dase75ed922015-02-26 08:19:31 +00001264 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001265 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1266 PostLoopRRI);
1267 }
1268
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001269 BasicBlock *NewMainLoopPreheader =
1270 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1271 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1272 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1273 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001274
1275 // Some of the above may be nullptr, filter them out before passing to
1276 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001277 auto NewBlocksEnd =
1278 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001279
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001280 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1281 addToParentLoopIfNeeded(PreLoop.Blocks);
1282 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001283
1284 return true;
1285}
1286
Sanjoy Das95c476d2015-02-21 22:20:22 +00001287/// 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 Dasa1837a32015-01-16 01:03:22 +00001290Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001291InductiveRangeCheck::computeSafeIterationSpace(
1292 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001293 // 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 Dasa1837a32015-01-16 01:03:22 +00001300 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001301 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001302 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001303 // 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 Dasa1837a32015-01-16 01:03:22 +00001307 //
1308 // Proof:
1309 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001310 // 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 Dasa1837a32015-01-16 01:03:22 +00001314 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001315 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1316 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001317
Sanjoy Das95c476d2015-02-21 22:20:22 +00001318 // [^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 Dasa1837a32015-01-16 01:03:22 +00001320
Sanjoy Das95c476d2015-02-21 22:20:22 +00001321 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001322 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001323
Sanjoy Das95c476d2015-02-21 22:20:22 +00001324 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 Dase2cde6f2015-03-17 00:42:13 +00001341 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001342
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001343 // 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 Das351db052015-01-22 09:32:02 +00001354 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001355}
1356
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001357static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001358IntersectRange(ScalarEvolution &SE,
1359 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001360 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001361 if (!R1.hasValue())
1362 return R2;
1363 auto &R1Value = R1.getValue();
1364
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001365 // TODO: we could widen the smaller range and have this work; but for now we
1366 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001367 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001368 return None;
1369
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001370 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 Dasa1837a32015-01-16 01:03:22 +00001374}
1375
1376bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001377 if (skipLoop(L))
1378 return false;
1379
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001380 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 Dasc5b11692016-05-21 02:52:13 +00001392 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001393 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001394 BranchProbabilityInfo &BPI =
1395 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001396
1397 for (auto BBI : L->getBlocks())
1398 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001399 if (auto MaybeIRC = InductiveRangeCheck::create(TBI, L, SE, BPI))
1400 RangeChecks.push_back(*MaybeIRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001401
1402 if (RangeChecks.empty())
1403 return false;
1404
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001405 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 Dasc5b11692016-05-21 02:52:13 +00001409 for (InductiveRangeCheck &IRC : RangeChecks)
1410 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001411 };
1412
1413 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1414
1415 if (PrintRangeChecks)
1416 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001417
Sanjoy Dase75ed922015-02-26 08:19:31 +00001418 const char *FailureReason = nullptr;
1419 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001420 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001421 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 Dasa1837a32015-01-16 01:03:22 +00001433 Optional<InductiveRangeCheck::Range> SafeIterRange;
1434 Instruction *ExprInsertPt = Preheader->getTerminator();
1435
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001436 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001437
1438 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001439 for (InductiveRangeCheck &IRC : RangeChecks) {
1440 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001441 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001442 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001443 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001444 if (MaybeSafeIterRange.hasValue()) {
1445 RangeChecksToEliminate.push_back(IRC);
1446 SafeIterRange = MaybeSafeIterRange.getValue();
1447 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001448 }
1449 }
1450
1451 if (!SafeIterRange.hasValue())
1452 return false;
1453
Sanjoy Dase75ed922015-02-26 08:19:31 +00001454 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1455 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001456 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 Dasc5b11692016-05-21 02:52:13 +00001473 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1474 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001475 ? ConstantInt::getTrue(Context)
1476 : ConstantInt::getFalse(Context);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001477 IRC.getBranch()->setCondition(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001478 }
1479 }
1480
1481 return Changed;
1482}
1483
1484Pass *llvm::createInductiveRangeCheckEliminationPass() {
1485 return new InductiveRangeCheckElimination;
1486}