blob: 3226efb86d292b5e9d9636ed6cafabe9cb8c5712 [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 Dasbb969792016-07-22 00:40:56 +000085static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
86 cl::Hidden, cl::init(false));
87
Sanjoy Dasa1837a32015-01-16 01:03:22 +000088#define DEBUG_TYPE "irce"
89
90namespace {
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 Dase2cde6f2015-03-17 00:42:13 +000099/// 2. a condition that is provably true for some contiguous range of values
100/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000101///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000102class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000103 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000104 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000105 // 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
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000119 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000120
Sanjoy Dasee77a482016-05-26 01:50:18 +0000121 const SCEV *Offset = nullptr;
122 const SCEV *Scale = nullptr;
123 Value *Length = nullptr;
124 Use *CheckUse = nullptr;
125 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000126
Sanjoy Das337d46b2015-03-24 19:29:18 +0000127 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
128 ScalarEvolution &SE, Value *&Index,
129 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000130
Sanjoy Dasa0992682016-05-26 00:09:02 +0000131 static void
132 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
133 SmallVectorImpl<InductiveRangeCheck> &Checks,
134 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000135
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000136public:
137 const SCEV *getOffset() const { return Offset; }
138 const SCEV *getScale() const { return Scale; }
139 Value *getLength() const { return Length; }
140
141 void print(raw_ostream &OS) const {
142 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000143 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000144 OS << " Offset: ";
145 Offset->print(OS);
146 OS << " Scale: ";
147 Scale->print(OS);
148 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000149 if (Length)
150 Length->print(OS);
151 else
152 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000153 OS << "\n CheckUse: ";
154 getCheckUse()->getUser()->print(OS);
155 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000156 }
157
158#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
159 void dump() {
160 print(dbgs());
161 }
162#endif
163
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000164 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000165
Sanjoy Das351db052015-01-22 09:32:02 +0000166 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
167 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
168
169 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000170 const SCEV *Begin;
171 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000172
173 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000174 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000175 assert(Begin->getType() == End->getType() && "ill-typed range!");
176 }
177
178 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000179 const SCEV *getBegin() const { return Begin; }
180 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000181 };
182
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000183 /// This is the value the condition of the branch needs to evaluate to for the
184 /// branch to take the hot successor (see (1) above).
185 bool getPassingDirection() { return true; }
186
Sanjoy Das95c476d2015-02-21 22:20:22 +0000187 /// Computes a range for the induction variable (IndVar) in which the range
188 /// check is redundant and can be constant-folded away. The induction
189 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000190 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000191 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000192
Sanjoy Dasa0992682016-05-26 00:09:02 +0000193 /// Parse out a set of inductive range checks from \p BI and append them to \p
194 /// Checks.
195 ///
196 /// NB! There may be conditions feeding into \p BI that aren't inductive range
197 /// checks, and hence don't end up in \p Checks.
198 static void
199 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
200 BranchProbabilityInfo &BPI,
201 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000202};
203
204class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000205public:
206 static char ID;
207 InductiveRangeCheckElimination() : LoopPass(ID) {
208 initializeInductiveRangeCheckEliminationPass(
209 *PassRegistry::getPassRegistry());
210 }
211
212 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000213 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000214 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000215 }
216
217 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
218};
219
220char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000221}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000222
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000223INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
224 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000225INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000226INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000227INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
228 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000229
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000230StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000231 InductiveRangeCheck::RangeCheckKind RCK) {
232 switch (RCK) {
233 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
234 return "RANGE_CHECK_UNKNOWN";
235
236 case InductiveRangeCheck::RANGE_CHECK_UPPER:
237 return "RANGE_CHECK_UPPER";
238
239 case InductiveRangeCheck::RANGE_CHECK_LOWER:
240 return "RANGE_CHECK_LOWER";
241
242 case InductiveRangeCheck::RANGE_CHECK_BOTH:
243 return "RANGE_CHECK_BOTH";
244 }
245
246 llvm_unreachable("unknown range check type!");
247}
248
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000249/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000250/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000251/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000252/// range checked, and set `Length` to the upper limit `Index` is being range
253/// checked with if (and only if) the range check type is stronger or equal to
254/// RANGE_CHECK_UPPER.
255///
256InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000257InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
258 ScalarEvolution &SE, Value *&Index,
259 Value *&Length) {
260
261 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
262 const SCEV *S = SE.getSCEV(V);
263 if (isa<SCEVCouldNotCompute>(S))
264 return false;
265
266 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
267 SE.isKnownNonNegative(S);
268 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000269
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000270 using namespace llvm::PatternMatch;
271
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000272 ICmpInst::Predicate Pred = ICI->getPredicate();
273 Value *LHS = ICI->getOperand(0);
274 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000275
276 switch (Pred) {
277 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000278 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000279
280 case ICmpInst::ICMP_SLE:
281 std::swap(LHS, RHS);
282 // fallthrough
283 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000284 if (match(RHS, m_ConstantInt<0>())) {
285 Index = LHS;
286 return RANGE_CHECK_LOWER;
287 }
288 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000289
290 case ICmpInst::ICMP_SLT:
291 std::swap(LHS, RHS);
292 // fallthrough
293 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000294 if (match(RHS, m_ConstantInt<-1>())) {
295 Index = LHS;
296 return RANGE_CHECK_LOWER;
297 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000298
Sanjoy Das337d46b2015-03-24 19:29:18 +0000299 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000300 Index = RHS;
301 Length = LHS;
302 return RANGE_CHECK_UPPER;
303 }
304 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000305
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000306 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000307 std::swap(LHS, RHS);
308 // fallthrough
309 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000310 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000311 Index = RHS;
312 Length = LHS;
313 return RANGE_CHECK_BOTH;
314 }
315 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000316 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000317
318 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000319}
320
Sanjoy Dasa0992682016-05-26 00:09:02 +0000321void InductiveRangeCheck::extractRangeChecksFromCond(
322 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
323 SmallVectorImpl<InductiveRangeCheck> &Checks,
324 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000325 using namespace llvm::PatternMatch;
326
Sanjoy Das8fe88922016-05-26 00:08:24 +0000327 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000328 if (!Visited.insert(Condition).second)
329 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000330
Sanjoy Dasa0992682016-05-26 00:09:02 +0000331 if (match(Condition, m_And(m_Value(), m_Value()))) {
332 SmallVector<InductiveRangeCheck, 8> SubChecks;
333 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
334 SubChecks, Visited);
335 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
336 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000337
Sanjoy Dasa0992682016-05-26 00:09:02 +0000338 if (SubChecks.size() == 2) {
339 // Handle a special case where we know how to merge two checks separately
340 // checking the upper and lower bounds into a full range check.
341 const auto &RChkA = SubChecks[0];
342 const auto &RChkB = SubChecks[1];
343 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
344 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000345
Sanjoy Dasa0992682016-05-26 00:09:02 +0000346 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
347 // But if one of them is a RANGE_CHECK_LOWER and the other is a
348 // RANGE_CHECK_UPPER (only possibility if they're different) then
349 // together they form a RANGE_CHECK_BOTH.
350 SubChecks[0].Kind =
351 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
352 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
353 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354
Sanjoy Dasa0992682016-05-26 00:09:02 +0000355 // We updated one of the checks in place, now erase the other.
356 SubChecks.pop_back();
357 }
358 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000359
Sanjoy Dasa0992682016-05-26 00:09:02 +0000360 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
361 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000362 }
363
Sanjoy Dasa0992682016-05-26 00:09:02 +0000364 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
365 if (!ICI)
366 return;
367
368 Value *Length = nullptr, *Index;
369 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
370 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
371 return;
372
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000373 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374 bool IsAffineIndex =
375 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
376
377 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000378 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000379
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000380 InductiveRangeCheck IRC;
381 IRC.Length = Length;
382 IRC.Offset = IndexAddRec->getStart();
383 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000384 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000385 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000386 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000387}
388
Sanjoy Dasa0992682016-05-26 00:09:02 +0000389void InductiveRangeCheck::extractRangeChecksFromBranch(
390 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
391 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000392
393 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000394 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000395
396 BranchProbability LikelyTaken(15, 16);
397
Sanjoy Dasbb969792016-07-22 00:40:56 +0000398 if (!SkipProfitabilityChecks &&
399 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000400 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000401
Sanjoy Dasa0992682016-05-26 00:09:02 +0000402 SmallPtrSet<Value *, 8> Visited;
403 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
404 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000405}
406
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000407namespace {
408
Sanjoy Dase75ed922015-02-26 08:19:31 +0000409// Keeps track of the structure of a loop. This is similar to llvm::Loop,
410// except that it is more lightweight and can track the state of a loop through
411// changing and potentially invalid IR. This structure also formalizes the
412// kinds of loops we can deal with -- ones that have a single latch that is also
413// an exiting block *and* have a canonical induction variable.
414struct LoopStructure {
415 const char *Tag;
416
417 BasicBlock *Header;
418 BasicBlock *Latch;
419
420 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
421 // successor is `LatchExit', the exit block of the loop.
422 BranchInst *LatchBr;
423 BasicBlock *LatchExit;
424 unsigned LatchBrExitIdx;
425
426 Value *IndVarNext;
427 Value *IndVarStart;
428 Value *LoopExitAt;
429 bool IndVarIncreasing;
430
431 LoopStructure()
432 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
433 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
434 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
435
436 template <typename M> LoopStructure map(M Map) const {
437 LoopStructure Result;
438 Result.Tag = Tag;
439 Result.Header = cast<BasicBlock>(Map(Header));
440 Result.Latch = cast<BasicBlock>(Map(Latch));
441 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
442 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
443 Result.LatchBrExitIdx = LatchBrExitIdx;
444 Result.IndVarNext = Map(IndVarNext);
445 Result.IndVarStart = Map(IndVarStart);
446 Result.LoopExitAt = Map(LoopExitAt);
447 Result.IndVarIncreasing = IndVarIncreasing;
448 return Result;
449 }
450
Sanjoy Dase91665d2015-02-26 08:56:04 +0000451 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
452 BranchProbabilityInfo &BPI,
453 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000454 const char *&);
455};
456
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000457/// This class is used to constrain loops to run within a given iteration space.
458/// The algorithm this class implements is given a Loop and a range [Begin,
459/// End). The algorithm then tries to break out a "main loop" out of the loop
460/// it is given in a way that the "main loop" runs with the induction variable
461/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
462/// loops to run any remaining iterations. The pre loop runs any iterations in
463/// which the induction variable is < Begin, and the post loop runs any
464/// iterations in which the induction variable is >= End.
465///
466class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000467 // The representation of a clone of the original loop we started out with.
468 struct ClonedLoop {
469 // The cloned blocks
470 std::vector<BasicBlock *> Blocks;
471
472 // `Map` maps values in the clonee into values in the cloned version
473 ValueToValueMapTy Map;
474
475 // An instance of `LoopStructure` for the cloned loop
476 LoopStructure Structure;
477 };
478
479 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
480 // more details on what these fields mean.
481 struct RewrittenRangeInfo {
482 BasicBlock *PseudoExit;
483 BasicBlock *ExitSelector;
484 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000485 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000486
Sanjoy Dase75ed922015-02-26 08:19:31 +0000487 RewrittenRangeInfo()
488 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000489 };
490
491 // Calculated subranges we restrict the iteration space of the main loop to.
492 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000493 // these fields are computed. `LowLimit` is None if there is no restriction
494 // on low end of the restricted iteration space of the main loop. `HighLimit`
495 // is None if there is no restriction on high end of the restricted iteration
496 // space of the main loop.
497
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000498 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000499 Optional<const SCEV *> LowLimit;
500 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000501 };
502
503 // A utility function that does a `replaceUsesOfWith' on the incoming block
504 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
505 // incoming block list with `ReplaceBy'.
506 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
507 BasicBlock *ReplaceBy);
508
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000509 // Compute a safe set of limits for the main loop to run in -- effectively the
510 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000511 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000512 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000513 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000514
515 // Clone `OriginalLoop' and return the result in CLResult. The IR after
516 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
517 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
518 // but there is no such edge.
519 //
520 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
521
522 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
523 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
524 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
525 // `OriginalHeaderCount'.
526 //
527 // If there are iterations left to execute, control is made to jump to
528 // `ContinuationBlock', otherwise they take the normal loop exit. The
529 // returned `RewrittenRangeInfo' object is populated as follows:
530 //
531 // .PseudoExit is a basic block that unconditionally branches to
532 // `ContinuationBlock'.
533 //
534 // .ExitSelector is a basic block that decides, on exit from the loop,
535 // whether to branch to the "true" exit or to `PseudoExit'.
536 //
537 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
538 // for each PHINode in the loop header on taking the pseudo exit.
539 //
540 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
541 // preheader because it is made to branch to the loop header only
542 // conditionally.
543 //
544 RewrittenRangeInfo
545 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
546 Value *ExitLoopAt,
547 BasicBlock *ContinuationBlock) const;
548
549 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
550 // function creates a new preheader for `LS' and returns it.
551 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000552 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
553 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000554
555 // `ContinuationBlockAndPreheader' was the continuation block for some call to
556 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
557 // This function rewrites the PHI nodes in `LS.Header' to start with the
558 // correct value.
559 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000560 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000561 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
562
563 // Even though we do not preserve any passes at this time, we at least need to
564 // keep the parent loop structure consistent. The `LPPassManager' seems to
565 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000566 // blocks denoted by BBs to this loops parent loop if required.
567 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000568
569 // Some global state.
570 Function &F;
571 LLVMContext &Ctx;
572 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000573 DominatorTree &DT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000574
575 // Information about the original loop we started out with.
576 Loop &OriginalLoop;
Sanjoy Das83a72852016-08-02 19:32:01 +0000577 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000578 const SCEV *LatchTakenCount;
579 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000580
581 // The preheader of the main loop. This may or may not be different from
582 // `OriginalPreheader'.
583 BasicBlock *MainLoopPreheader;
584
585 // The range we need to run the main loop in.
586 InductiveRangeCheck::Range Range;
587
588 // The structure of the main loop (see comment at the beginning of this class
589 // for a definition)
590 LoopStructure MainLoopStructure;
591
592public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000593 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000594 ScalarEvolution &SE, DominatorTree &DT,
595 InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000596 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das83a72852016-08-02 19:32:01 +0000597 SE(SE), DT(DT), OriginalLoop(L), LI(LI), LatchTakenCount(nullptr),
598 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
599 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000600
601 // Entry point for the algorithm. Returns true on success.
602 bool run();
603};
604
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000605}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000606
607void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
608 BasicBlock *ReplaceBy) {
609 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
610 if (PN->getIncomingBlock(i) == Block)
611 PN->setIncomingBlock(i, ReplaceBy);
612}
613
Sanjoy Dase75ed922015-02-26 08:19:31 +0000614static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
615 APInt SMax =
616 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
617 return SE.getSignedRange(S).contains(SMax) &&
618 SE.getUnsignedRange(S).contains(SMax);
619}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000620
Sanjoy Dase75ed922015-02-26 08:19:31 +0000621static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
622 APInt SMin =
623 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
624 return SE.getSignedRange(S).contains(SMin) &&
625 SE.getUnsignedRange(S).contains(SMin);
626}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000627
Sanjoy Dase75ed922015-02-26 08:19:31 +0000628Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000629LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
630 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000631 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
632
633 BasicBlock *Latch = L.getLoopLatch();
634 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000635 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000636 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000637 }
638
Sanjoy Dase75ed922015-02-26 08:19:31 +0000639 BasicBlock *Header = L.getHeader();
640 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641 if (!Preheader) {
642 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000643 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000644 }
645
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000646 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647 if (!LatchBr || LatchBr->isUnconditional()) {
648 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000649 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000650 }
651
Sanjoy Dase75ed922015-02-26 08:19:31 +0000652 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000653
Sanjoy Dase91665d2015-02-26 08:56:04 +0000654 BranchProbability ExitProbability =
655 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
656
Sanjoy Dasbb969792016-07-22 00:40:56 +0000657 if (!SkipProfitabilityChecks &&
658 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000659 FailureReason = "short running loop, not profitable";
660 return None;
661 }
662
Sanjoy Dase75ed922015-02-26 08:19:31 +0000663 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
664 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
665 FailureReason = "latch terminator branch not conditional on integral icmp";
666 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000667 }
668
Sanjoy Dase75ed922015-02-26 08:19:31 +0000669 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
670 if (isa<SCEVCouldNotCompute>(LatchCount)) {
671 FailureReason = "could not compute latch count";
672 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000673 }
674
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 ICmpInst::Predicate Pred = ICI->getPredicate();
676 Value *LeftValue = ICI->getOperand(0);
677 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
678 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
679
680 Value *RightValue = ICI->getOperand(1);
681 const SCEV *RightSCEV = SE.getSCEV(RightValue);
682
683 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
684 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
685 if (isa<SCEVAddRecExpr>(RightSCEV)) {
686 std::swap(LeftSCEV, RightSCEV);
687 std::swap(LeftValue, RightValue);
688 Pred = ICmpInst::getSwappedPredicate(Pred);
689 } else {
690 FailureReason = "no add recurrences in the icmp";
691 return None;
692 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000693 }
694
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000695 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
696 if (AR->getNoWrapFlags(SCEV::FlagNSW))
697 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000698
699 IntegerType *Ty = cast<IntegerType>(AR->getType());
700 IntegerType *WideTy =
701 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
702
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000703 const SCEVAddRecExpr *ExtendAfterOp =
704 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
705 if (ExtendAfterOp) {
706 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
707 const SCEV *ExtendedStep =
708 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
709
710 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
711 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
712
713 if (NoSignedWrap)
714 return true;
715 }
716
717 // We may have proved this when computing the sign extension above.
718 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
719 };
720
721 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
722 if (!AR->isAffine())
723 return false;
724
Sanjoy Dase75ed922015-02-26 08:19:31 +0000725 // Currently we only work with induction variables that have been proved to
726 // not wrap. This restriction can potentially be lifted in the future.
727
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000728 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000729 return false;
730
731 if (const SCEVConstant *StepExpr =
732 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
733 ConstantInt *StepCI = StepExpr->getValue();
734 if (StepCI->isOne() || StepCI->isMinusOne()) {
735 IsIncreasing = StepCI->isOne();
736 return true;
737 }
738 }
739
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000740 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000741 };
742
743 // `ICI` is interpreted as taking the backedge if the *next* value of the
744 // induction variable satisfies some constraint.
745
746 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
747 bool IsIncreasing = false;
748 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
749 FailureReason = "LHS in icmp not induction variable";
750 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000751 }
752
Sanjoy Dase75ed922015-02-26 08:19:31 +0000753 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
754 // TODO: generalize the predicates here to also match their unsigned variants.
755 if (IsIncreasing) {
756 bool FoundExpectedPred =
757 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
758 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
759
760 if (!FoundExpectedPred) {
761 FailureReason = "expected icmp slt semantically, found something else";
762 return None;
763 }
764
765 if (LatchBrExitIdx == 0) {
766 if (CanBeSMax(SE, RightSCEV)) {
767 // TODO: this restriction is easily removable -- we just have to
768 // remember that the icmp was an slt and not an sle.
769 FailureReason = "limit may overflow when coercing sle to slt";
770 return None;
771 }
772
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000773 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000774 RightValue = B.CreateAdd(RightValue, One);
775 }
776
777 } else {
778 bool FoundExpectedPred =
779 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
780 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
781
782 if (!FoundExpectedPred) {
783 FailureReason = "expected icmp sgt semantically, found something else";
784 return None;
785 }
786
787 if (LatchBrExitIdx == 0) {
788 if (CanBeSMin(SE, RightSCEV)) {
789 // TODO: this restriction is easily removable -- we just have to
790 // remember that the icmp was an sgt and not an sge.
791 FailureReason = "limit may overflow when coercing sge to sgt";
792 return None;
793 }
794
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000795 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000796 RightValue = B.CreateSub(RightValue, One);
797 }
798 }
799
800 const SCEV *StartNext = IndVarNext->getStart();
801 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
802 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
803
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000804 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
805
Sanjoy Dase75ed922015-02-26 08:19:31 +0000806 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000807 ScalarEvolution::LoopInvariant &&
808 "loop variant exit count doesn't make sense!");
809
Sanjoy Dase75ed922015-02-26 08:19:31 +0000810 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000811 const DataLayout &DL = Preheader->getModule()->getDataLayout();
812 Value *IndVarStartV =
813 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000814 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000815 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000816
Sanjoy Dase75ed922015-02-26 08:19:31 +0000817 LoopStructure Result;
818
819 Result.Tag = "main";
820 Result.Header = Header;
821 Result.Latch = Latch;
822 Result.LatchBr = LatchBr;
823 Result.LatchExit = LatchExit;
824 Result.LatchBrExitIdx = LatchBrExitIdx;
825 Result.IndVarStart = IndVarStartV;
826 Result.IndVarNext = LeftValue;
827 Result.IndVarIncreasing = IsIncreasing;
828 Result.LoopExitAt = RightValue;
829
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000830 FailureReason = nullptr;
831
Sanjoy Dase75ed922015-02-26 08:19:31 +0000832 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000833}
834
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000835Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000836LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000837 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
838
Sanjoy Das351db052015-01-22 09:32:02 +0000839 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000840 return None;
841
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000842 LoopConstrainer::SubRanges Result;
843
844 // I think we can be more aggressive here and make this nuw / nsw if the
845 // addition that feeds into the icmp for the latch's terminating branch is nuw
846 // / nsw. In any case, a wrapping 2's complement addition is safe.
847 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000848 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
849 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000850
Sanjoy Dase75ed922015-02-26 08:19:31 +0000851 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000852
Sanjoy Dase75ed922015-02-26 08:19:31 +0000853 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
854 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000855
856 const SCEV *Smallest = nullptr, *Greatest = nullptr;
857
858 if (Increasing) {
859 Smallest = Start;
860 Greatest = End;
861 } else {
862 // These two computations may sign-overflow. Here is why that is okay:
863 //
864 // We know that the induction variable does not sign-overflow on any
865 // iteration except the last one, and it starts at `Start` and ends at
866 // `End`, decrementing by one every time.
867 //
868 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
869 // induction variable is decreasing we know that that the smallest value
870 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
871 //
872 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
873 // that case, `Clamp` will always return `Smallest` and
874 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
875 // will be an empty range. Returning an empty range is always safe.
876 //
877
878 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
879 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
880 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000881
882 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
883 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
884 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000885
886 // In some cases we can prove that we don't need a pre or post loop
887
888 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000889 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
890 if (!ProvablyNoPreloop)
891 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000892
893 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000894 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
895 if (!ProvablyNoPostLoop)
896 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000897
898 return Result;
899}
900
901void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
902 const char *Tag) const {
903 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
904 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
905 Result.Blocks.push_back(Clone);
906 Result.Map[BB] = Clone;
907 }
908
909 auto GetClonedValue = [&Result](Value *V) {
910 assert(V && "null values not in domain!");
911 auto It = Result.Map.find(V);
912 if (It == Result.Map.end())
913 return V;
914 return static_cast<Value *>(It->second);
915 };
916
917 Result.Structure = MainLoopStructure.map(GetClonedValue);
918 Result.Structure.Tag = Tag;
919
920 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
921 BasicBlock *ClonedBB = Result.Blocks[i];
922 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
923
924 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
925
926 for (Instruction &I : *ClonedBB)
927 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000928 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000929
930 // Exit blocks will now have one more predecessor and their PHI nodes need
931 // to be edited to reflect that. No phi nodes need to be introduced because
932 // the loop is in LCSSA.
933
934 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
935 SBBI != SBBE; ++SBBI) {
936
937 if (OriginalLoop.contains(*SBBI))
938 continue; // not an exit block
939
940 for (Instruction &I : **SBBI) {
941 if (!isa<PHINode>(&I))
942 break;
943
944 PHINode *PN = cast<PHINode>(&I);
945 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
946 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
947 }
948 }
949 }
950}
951
952LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000953 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000954 BasicBlock *ContinuationBlock) const {
955
956 // We start with a loop with a single latch:
957 //
958 // +--------------------+
959 // | |
960 // | preheader |
961 // | |
962 // +--------+-----------+
963 // | ----------------\
964 // | / |
965 // +--------v----v------+ |
966 // | | |
967 // | header | |
968 // | | |
969 // +--------------------+ |
970 // |
971 // ..... |
972 // |
973 // +--------------------+ |
974 // | | |
975 // | latch >----------/
976 // | |
977 // +-------v------------+
978 // |
979 // |
980 // | +--------------------+
981 // | | |
982 // +---> original exit |
983 // | |
984 // +--------------------+
985 //
986 // We change the control flow to look like
987 //
988 //
989 // +--------------------+
990 // | |
991 // | preheader >-------------------------+
992 // | | |
993 // +--------v-----------+ |
994 // | /-------------+ |
995 // | / | |
996 // +--------v--v--------+ | |
997 // | | | |
998 // | header | | +--------+ |
999 // | | | | | |
1000 // +--------------------+ | | +-----v-----v-----------+
1001 // | | | |
1002 // | | | .pseudo.exit |
1003 // | | | |
1004 // | | +-----------v-----------+
1005 // | | |
1006 // ..... | | |
1007 // | | +--------v-------------+
1008 // +--------------------+ | | | |
1009 // | | | | | ContinuationBlock |
1010 // | latch >------+ | | |
1011 // | | | +----------------------+
1012 // +---------v----------+ |
1013 // | |
1014 // | |
1015 // | +---------------^-----+
1016 // | | |
1017 // +-----> .exit.selector |
1018 // | |
1019 // +----------v----------+
1020 // |
1021 // +--------------------+ |
1022 // | | |
1023 // | original exit <----+
1024 // | |
1025 // +--------------------+
1026 //
1027
1028 RewrittenRangeInfo RRI;
1029
1030 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1031 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001032 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001033 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001034 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001035
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001036 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001037 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001038
1039 IRBuilder<> B(PreheaderJump);
1040
1041 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001042 Value *EnterLoopCond = Increasing
1043 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1044 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1045
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001046 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1047 PreheaderJump->eraseFromParent();
1048
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001049 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001050 B.SetInsertPoint(LS.LatchBr);
1051 Value *TakeBackedgeLoopCond =
1052 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1053 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1054 Value *CondForBranch = LS.LatchBrExitIdx == 1
1055 ? TakeBackedgeLoopCond
1056 : B.CreateNot(TakeBackedgeLoopCond);
1057
1058 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001059
1060 B.SetInsertPoint(RRI.ExitSelector);
1061
1062 // IterationsLeft - are there any more iterations left, given the original
1063 // upper bound on the induction variable? If not, we branch to the "real"
1064 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001065 Value *IterationsLeft = Increasing
1066 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1067 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001068 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1069
1070 BranchInst *BranchToContinuation =
1071 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1072
1073 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1074 // each of the PHI nodes in the loop header. This feeds into the initial
1075 // value of the same PHI nodes if/when we continue execution.
1076 for (Instruction &I : *LS.Header) {
1077 if (!isa<PHINode>(&I))
1078 break;
1079
1080 PHINode *PN = cast<PHINode>(&I);
1081
1082 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1083 BranchToContinuation);
1084
1085 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1086 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1087 RRI.ExitSelector);
1088 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1089 }
1090
Sanjoy Dase75ed922015-02-26 08:19:31 +00001091 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1092 BranchToContinuation);
1093 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1094 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1095
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001096 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1097 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1098 for (Instruction &I : *LS.LatchExit) {
1099 if (PHINode *PN = dyn_cast<PHINode>(&I))
1100 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1101 else
1102 break;
1103 }
1104
1105 return RRI;
1106}
1107
1108void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001109 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001110 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1111
1112 unsigned PHIIndex = 0;
1113 for (Instruction &I : *LS.Header) {
1114 if (!isa<PHINode>(&I))
1115 break;
1116
1117 PHINode *PN = cast<PHINode>(&I);
1118
1119 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1120 if (PN->getIncomingBlock(i) == ContinuationBlock)
1121 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1122 }
1123
Sanjoy Dase75ed922015-02-26 08:19:31 +00001124 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001125}
1126
Sanjoy Dase75ed922015-02-26 08:19:31 +00001127BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1128 BasicBlock *OldPreheader,
1129 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001130
1131 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1132 BranchInst::Create(LS.Header, Preheader);
1133
1134 for (Instruction &I : *LS.Header) {
1135 if (!isa<PHINode>(&I))
1136 break;
1137
1138 PHINode *PN = cast<PHINode>(&I);
1139 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1140 replacePHIBlock(PN, OldPreheader, Preheader);
1141 }
1142
1143 return Preheader;
1144}
1145
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001146void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001147 Loop *ParentLoop = OriginalLoop.getParentLoop();
1148 if (!ParentLoop)
1149 return;
1150
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001151 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001152 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001153}
1154
1155bool LoopConstrainer::run() {
1156 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001157 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1158 Preheader = OriginalLoop.getLoopPreheader();
1159 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1160 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001161
1162 OriginalPreheader = Preheader;
1163 MainLoopPreheader = Preheader;
1164
Sanjoy Dase75ed922015-02-26 08:19:31 +00001165 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001166 if (!MaybeSR.hasValue()) {
1167 DEBUG(dbgs() << "irce: could not compute subranges\n");
1168 return false;
1169 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001170
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001171 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001172 bool Increasing = MainLoopStructure.IndVarIncreasing;
1173 IntegerType *IVTy =
1174 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1175
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001176 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001177 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001178
1179 // It would have been better to make `PreLoop' and `PostLoop'
1180 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1181 // constructor.
1182 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001183 bool NeedsPreLoop =
1184 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1185 bool NeedsPostLoop =
1186 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1187
1188 Value *ExitPreLoopAt = nullptr;
1189 Value *ExitMainLoopAt = nullptr;
1190 const SCEVConstant *MinusOneS =
1191 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1192
1193 if (NeedsPreLoop) {
1194 const SCEV *ExitPreLoopAtSCEV = nullptr;
1195
1196 if (Increasing)
1197 ExitPreLoopAtSCEV = *SR.LowLimit;
1198 else {
1199 if (CanBeSMin(SE, *SR.HighLimit)) {
1200 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1201 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1202 << "\n");
1203 return false;
1204 }
1205 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1206 }
1207
1208 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1209 ExitPreLoopAt->setName("exit.preloop.at");
1210 }
1211
1212 if (NeedsPostLoop) {
1213 const SCEV *ExitMainLoopAtSCEV = nullptr;
1214
1215 if (Increasing)
1216 ExitMainLoopAtSCEV = *SR.HighLimit;
1217 else {
1218 if (CanBeSMin(SE, *SR.LowLimit)) {
1219 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1220 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1221 << "\n");
1222 return false;
1223 }
1224 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1225 }
1226
1227 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1228 ExitMainLoopAt->setName("exit.mainloop.at");
1229 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001230
1231 // We clone these ahead of time so that we don't have to deal with changing
1232 // and temporarily invalid IR as we transform the loops.
1233 if (NeedsPreLoop)
1234 cloneLoop(PreLoop, "preloop");
1235 if (NeedsPostLoop)
1236 cloneLoop(PostLoop, "postloop");
1237
1238 RewrittenRangeInfo PreLoopRRI;
1239
1240 if (NeedsPreLoop) {
1241 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1242 PreLoop.Structure.Header);
1243
1244 MainLoopPreheader =
1245 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001246 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1247 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001248 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1249 PreLoopRRI);
1250 }
1251
1252 BasicBlock *PostLoopPreheader = nullptr;
1253 RewrittenRangeInfo PostLoopRRI;
1254
1255 if (NeedsPostLoop) {
1256 PostLoopPreheader =
1257 createPreheader(PostLoop.Structure, Preheader, "postloop");
1258 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001259 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001260 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1261 PostLoopRRI);
1262 }
1263
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001264 BasicBlock *NewMainLoopPreheader =
1265 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1266 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1267 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1268 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001269
1270 // Some of the above may be nullptr, filter them out before passing to
1271 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001272 auto NewBlocksEnd =
1273 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001274
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001275 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1276 addToParentLoopIfNeeded(PreLoop.Blocks);
1277 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001278
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001279 DT.recalculate(F);
Sanjoy Das83a72852016-08-02 19:32:01 +00001280 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001281
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001282 return true;
1283}
1284
Sanjoy Das95c476d2015-02-21 22:20:22 +00001285/// Computes and returns a range of values for the induction variable (IndVar)
1286/// in which the range check can be safely elided. If it cannot compute such a
1287/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001288Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001289InductiveRangeCheck::computeSafeIterationSpace(
1290 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001291 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1292 // variable, that may or may not exist as a real llvm::Value in the loop) and
1293 // this inductive range check is a range check on the "C + D * I" ("C" is
1294 // getOffset() and "D" is getScale()). We rewrite the value being range
1295 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1296 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1297 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001298 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001299 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001300 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001301 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1302 //
1303 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1304 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001305 //
1306 // Proof:
1307 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001308 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1309 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1310 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1311 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001312 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001313 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1314 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001315
Sanjoy Das95c476d2015-02-21 22:20:22 +00001316 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1317 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001318
Sanjoy Das95c476d2015-02-21 22:20:22 +00001319 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001320 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001321
Sanjoy Das95c476d2015-02-21 22:20:22 +00001322 const SCEV *A = IndVar->getStart();
1323 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1324 if (!B)
1325 return None;
1326
1327 const SCEV *C = getOffset();
1328 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1329 if (D != B)
1330 return None;
1331
1332 ConstantInt *ConstD = D->getValue();
1333 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1334 return None;
1335
1336 const SCEV *M = SE.getMinusSCEV(C, A);
1337
1338 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001339 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001341 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1342 // We can potentially do much better here.
1343 if (Value *V = getLength()) {
1344 UpperLimit = SE.getSCEV(V);
1345 } else {
1346 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1347 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1348 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1349 }
1350
1351 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001352 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001353}
1354
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001355static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001356IntersectRange(ScalarEvolution &SE,
1357 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001358 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001359 if (!R1.hasValue())
1360 return R2;
1361 auto &R1Value = R1.getValue();
1362
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001363 // TODO: we could widen the smaller range and have this work; but for now we
1364 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001365 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001366 return None;
1367
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001368 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1369 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1370
1371 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001372}
1373
1374bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001375 if (skipLoop(L))
1376 return false;
1377
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001378 if (L->getBlocks().size() >= LoopSizeCutoff) {
1379 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1380 return false;
1381 }
1382
1383 BasicBlock *Preheader = L->getLoopPreheader();
1384 if (!Preheader) {
1385 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1386 return false;
1387 }
1388
1389 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001390 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001391 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001392 BranchProbabilityInfo &BPI =
1393 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001394
1395 for (auto BBI : L->getBlocks())
1396 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001397 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1398 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001399
1400 if (RangeChecks.empty())
1401 return false;
1402
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001403 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1404 OS << "irce: looking at loop "; L->print(OS);
1405 OS << "irce: loop has " << RangeChecks.size()
1406 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001407 for (InductiveRangeCheck &IRC : RangeChecks)
1408 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001409 };
1410
1411 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1412
1413 if (PrintRangeChecks)
1414 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001415
Sanjoy Dase75ed922015-02-26 08:19:31 +00001416 const char *FailureReason = nullptr;
1417 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001418 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001419 if (!MaybeLoopStructure.hasValue()) {
1420 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1421 << "\n";);
1422 return false;
1423 }
1424 LoopStructure LS = MaybeLoopStructure.getValue();
1425 bool Increasing = LS.IndVarIncreasing;
1426 const SCEV *MinusOne =
1427 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1428 const SCEVAddRecExpr *IndVar =
1429 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1430
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001431 Optional<InductiveRangeCheck::Range> SafeIterRange;
1432 Instruction *ExprInsertPt = Preheader->getTerminator();
1433
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001434 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001435
1436 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001437 for (InductiveRangeCheck &IRC : RangeChecks) {
1438 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001439 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001440 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001441 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001442 if (MaybeSafeIterRange.hasValue()) {
1443 RangeChecksToEliminate.push_back(IRC);
1444 SafeIterRange = MaybeSafeIterRange.getValue();
1445 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001446 }
1447 }
1448
1449 if (!SafeIterRange.hasValue())
1450 return false;
1451
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001452 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001453 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001454 SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001455 bool Changed = LC.run();
1456
1457 if (Changed) {
1458 auto PrintConstrainedLoopInfo = [L]() {
1459 dbgs() << "irce: in function ";
1460 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1461 dbgs() << "constrained ";
1462 L->print(dbgs());
1463 };
1464
1465 DEBUG(PrintConstrainedLoopInfo());
1466
1467 if (PrintChangedLoops)
1468 PrintConstrainedLoopInfo();
1469
1470 // Optimize away the now-redundant range checks.
1471
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001472 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1473 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001474 ? ConstantInt::getTrue(Context)
1475 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001476 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001477 }
1478 }
1479
1480 return Changed;
1481}
1482
1483Pass *llvm::createInductiveRangeCheckEliminationPass() {
1484 return new InductiveRangeCheckElimination;
1485}