blob: 48ec2de5e56a246f18ba6a350a0b3ec586aca460 [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#include <array>
71
72using namespace llvm;
73
Benjamin Kramer970eac42015-02-06 17:51:54 +000074static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
75 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000076
Benjamin Kramer970eac42015-02-06 17:51:54 +000077static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
78 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000079
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000080static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
81 cl::init(false));
82
Sanjoy Dase91665d2015-02-26 08:56:04 +000083static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
84 cl::Hidden, cl::init(10));
85
Sanjoy Dasa1837a32015-01-16 01:03:22 +000086#define DEBUG_TYPE "irce"
87
88namespace {
89
90/// An inductive range check is conditional branch in a loop with
91///
92/// 1. a very cold successor (i.e. the branch jumps to that successor very
93/// rarely)
94///
95/// and
96///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000097/// 2. a condition that is provably true for some contiguous range of values
98/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000099///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000100class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000101 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000102 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000103 // Range check of the form "0 <= I".
104 RANGE_CHECK_LOWER = 1,
105
106 // Range check of the form "I < L" where L is known positive.
107 RANGE_CHECK_UPPER = 2,
108
109 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
110 // conditions.
111 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
112
113 // Unrecognized range check condition.
114 RANGE_CHECK_UNKNOWN = (unsigned)-1
115 };
116
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000117 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000118
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000119 const SCEV *Offset;
120 const SCEV *Scale;
121 Value *Length;
122 BranchInst *Branch;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000123 RangeCheckKind Kind;
124
Sanjoy Das337d46b2015-03-24 19:29:18 +0000125 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
126 ScalarEvolution &SE, Value *&Index,
127 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000128
129 static InductiveRangeCheck::RangeCheckKind
130 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
131 const SCEV *&Index, Value *&UpperLimit);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132
133 InductiveRangeCheck() :
134 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
135
136public:
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)";
153 OS << "\n Branch: ";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000154 getBranch()->print(OS);
Sanjoy Das48c75812015-02-26 04:03:31 +0000155 OS << "\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
164 BranchInst *getBranch() const { return Branch; }
165
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 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
184
185 /// This is the value the condition of the branch needs to evaluate to for the
186 /// branch to take the hot successor (see (1) above).
187 bool getPassingDirection() { return true; }
188
Sanjoy Das95c476d2015-02-21 22:20:22 +0000189 /// Computes a range for the induction variable (IndVar) in which the range
190 /// check is redundant and can be constant-folded away. The induction
191 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000192 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das95c476d2015-02-21 22:20:22 +0000193 const SCEVAddRecExpr *IndVar,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000194 IRBuilder<> &B) const;
195
196 /// Create an inductive range check out of BI if possible, else return
197 /// nullptr.
198 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000199 Loop *L, ScalarEvolution &SE,
200 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000201};
202
203class InductiveRangeCheckElimination : public LoopPass {
204 InductiveRangeCheck::AllocatorTy Allocator;
205
206public:
207 static char ID;
208 InductiveRangeCheckElimination() : LoopPass(ID) {
209 initializeInductiveRangeCheckEliminationPass(
210 *PassRegistry::getPassRegistry());
211 }
212
213 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000214 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000215 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000216 }
217
218 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
219};
220
221char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000224INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
225 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000226INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000227INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000228INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
229 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000230
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000231StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000232 InductiveRangeCheck::RangeCheckKind RCK) {
233 switch (RCK) {
234 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
235 return "RANGE_CHECK_UNKNOWN";
236
237 case InductiveRangeCheck::RANGE_CHECK_UPPER:
238 return "RANGE_CHECK_UPPER";
239
240 case InductiveRangeCheck::RANGE_CHECK_LOWER:
241 return "RANGE_CHECK_LOWER";
242
243 case InductiveRangeCheck::RANGE_CHECK_BOTH:
244 return "RANGE_CHECK_BOTH";
245 }
246
247 llvm_unreachable("unknown range check type!");
248}
249
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000250/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000251/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000252/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000253/// range checked, and set `Length` to the upper limit `Index` is being range
254/// checked with if (and only if) the range check type is stronger or equal to
255/// RANGE_CHECK_UPPER.
256///
257InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000258InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
259 ScalarEvolution &SE, Value *&Index,
260 Value *&Length) {
261
262 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
263 const SCEV *S = SE.getSCEV(V);
264 if (isa<SCEVCouldNotCompute>(S))
265 return false;
266
267 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
268 SE.isKnownNonNegative(S);
269 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000270
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000271 using namespace llvm::PatternMatch;
272
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000273 ICmpInst::Predicate Pred = ICI->getPredicate();
274 Value *LHS = ICI->getOperand(0);
275 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000276
277 switch (Pred) {
278 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000279 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000280
281 case ICmpInst::ICMP_SLE:
282 std::swap(LHS, RHS);
283 // fallthrough
284 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000285 if (match(RHS, m_ConstantInt<0>())) {
286 Index = LHS;
287 return RANGE_CHECK_LOWER;
288 }
289 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000290
291 case ICmpInst::ICMP_SLT:
292 std::swap(LHS, RHS);
293 // fallthrough
294 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295 if (match(RHS, m_ConstantInt<-1>())) {
296 Index = LHS;
297 return RANGE_CHECK_LOWER;
298 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000299
Sanjoy Das337d46b2015-03-24 19:29:18 +0000300 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000301 Index = RHS;
302 Length = LHS;
303 return RANGE_CHECK_UPPER;
304 }
305 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000306
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000307 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000308 std::swap(LHS, RHS);
309 // fallthrough
310 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000311 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000312 Index = RHS;
313 Length = LHS;
314 return RANGE_CHECK_BOTH;
315 }
316 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000317 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000318
319 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320}
321
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000322/// Parses an arbitrary condition into a range check. `Length` is set only if
323/// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
324InductiveRangeCheck::RangeCheckKind
325InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326 Value *Condition, const SCEV *&Index,
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000327 Value *&Length) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000328 using namespace llvm::PatternMatch;
329
330 Value *A = nullptr;
331 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000332
333 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000334 Value *IndexA = nullptr, *IndexB = nullptr;
335 Value *LengthA = nullptr, *LengthB = nullptr;
336 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000337
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000338 if (!ICmpA || !ICmpB)
339 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000340
Sanjoy Das337d46b2015-03-24 19:29:18 +0000341 auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
342 auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000343
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000344 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
345 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
346 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000347
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000348 if (IndexA != IndexB)
349 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
350
351 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
352 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
353
354 Index = SE.getSCEV(IndexA);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355 if (isa<SCEVCouldNotCompute>(Index))
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000356 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000358 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000359
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000360 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000361 }
362
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000363 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
364 Value *IndexVal = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000365
Sanjoy Das337d46b2015-03-24 19:29:18 +0000366 auto RCKind = parseRangeCheckICmp(L, ICI, SE, IndexVal, Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000367
368 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
369 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
370
371 Index = SE.getSCEV(IndexVal);
372 if (isa<SCEVCouldNotCompute>(Index))
373 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
374
375 return RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000376 }
377
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000378 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000379}
380
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000381
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000382InductiveRangeCheck *
383InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000384 Loop *L, ScalarEvolution &SE,
385 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000386
387 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
388 return nullptr;
389
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000390 BranchProbability LikelyTaken(15, 16);
391
392 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
393 return nullptr;
394
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000395 Value *Length = nullptr;
396 const SCEV *IndexSCEV = nullptr;
397
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000398 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
399 IndexSCEV, Length);
400
401 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000402 return nullptr;
403
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000404 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
David Blaikiec4dfa632015-03-17 17:48:24 +0000405 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
406 "contract with SplitRangeCheckCondition!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000407
408 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
409 bool IsAffineIndex =
410 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
411
412 if (!IsAffineIndex)
413 return nullptr;
414
415 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
416 IRC->Length = Length;
417 IRC->Offset = IndexAddRec->getStart();
418 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
419 IRC->Branch = BI;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000420 IRC->Kind = RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000421 return IRC;
422}
423
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000424namespace {
425
Sanjoy Dase75ed922015-02-26 08:19:31 +0000426// Keeps track of the structure of a loop. This is similar to llvm::Loop,
427// except that it is more lightweight and can track the state of a loop through
428// changing and potentially invalid IR. This structure also formalizes the
429// kinds of loops we can deal with -- ones that have a single latch that is also
430// an exiting block *and* have a canonical induction variable.
431struct LoopStructure {
432 const char *Tag;
433
434 BasicBlock *Header;
435 BasicBlock *Latch;
436
437 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
438 // successor is `LatchExit', the exit block of the loop.
439 BranchInst *LatchBr;
440 BasicBlock *LatchExit;
441 unsigned LatchBrExitIdx;
442
443 Value *IndVarNext;
444 Value *IndVarStart;
445 Value *LoopExitAt;
446 bool IndVarIncreasing;
447
448 LoopStructure()
449 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
450 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
451 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
452
453 template <typename M> LoopStructure map(M Map) const {
454 LoopStructure Result;
455 Result.Tag = Tag;
456 Result.Header = cast<BasicBlock>(Map(Header));
457 Result.Latch = cast<BasicBlock>(Map(Latch));
458 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
459 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
460 Result.LatchBrExitIdx = LatchBrExitIdx;
461 Result.IndVarNext = Map(IndVarNext);
462 Result.IndVarStart = Map(IndVarStart);
463 Result.LoopExitAt = Map(LoopExitAt);
464 Result.IndVarIncreasing = IndVarIncreasing;
465 return Result;
466 }
467
Sanjoy Dase91665d2015-02-26 08:56:04 +0000468 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
469 BranchProbabilityInfo &BPI,
470 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000471 const char *&);
472};
473
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000474/// This class is used to constrain loops to run within a given iteration space.
475/// The algorithm this class implements is given a Loop and a range [Begin,
476/// End). The algorithm then tries to break out a "main loop" out of the loop
477/// it is given in a way that the "main loop" runs with the induction variable
478/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
479/// loops to run any remaining iterations. The pre loop runs any iterations in
480/// which the induction variable is < Begin, and the post loop runs any
481/// iterations in which the induction variable is >= End.
482///
483class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000484 // The representation of a clone of the original loop we started out with.
485 struct ClonedLoop {
486 // The cloned blocks
487 std::vector<BasicBlock *> Blocks;
488
489 // `Map` maps values in the clonee into values in the cloned version
490 ValueToValueMapTy Map;
491
492 // An instance of `LoopStructure` for the cloned loop
493 LoopStructure Structure;
494 };
495
496 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
497 // more details on what these fields mean.
498 struct RewrittenRangeInfo {
499 BasicBlock *PseudoExit;
500 BasicBlock *ExitSelector;
501 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000502 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000503
Sanjoy Dase75ed922015-02-26 08:19:31 +0000504 RewrittenRangeInfo()
505 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000506 };
507
508 // Calculated subranges we restrict the iteration space of the main loop to.
509 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000510 // these fields are computed. `LowLimit` is None if there is no restriction
511 // on low end of the restricted iteration space of the main loop. `HighLimit`
512 // is None if there is no restriction on high end of the restricted iteration
513 // space of the main loop.
514
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000515 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000516 Optional<const SCEV *> LowLimit;
517 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000518 };
519
520 // A utility function that does a `replaceUsesOfWith' on the incoming block
521 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
522 // incoming block list with `ReplaceBy'.
523 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
524 BasicBlock *ReplaceBy);
525
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000526 // Compute a safe set of limits for the main loop to run in -- effectively the
527 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000528 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000529 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000530 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000531
532 // Clone `OriginalLoop' and return the result in CLResult. The IR after
533 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
534 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
535 // but there is no such edge.
536 //
537 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
538
539 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
540 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
541 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
542 // `OriginalHeaderCount'.
543 //
544 // If there are iterations left to execute, control is made to jump to
545 // `ContinuationBlock', otherwise they take the normal loop exit. The
546 // returned `RewrittenRangeInfo' object is populated as follows:
547 //
548 // .PseudoExit is a basic block that unconditionally branches to
549 // `ContinuationBlock'.
550 //
551 // .ExitSelector is a basic block that decides, on exit from the loop,
552 // whether to branch to the "true" exit or to `PseudoExit'.
553 //
554 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
555 // for each PHINode in the loop header on taking the pseudo exit.
556 //
557 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
558 // preheader because it is made to branch to the loop header only
559 // conditionally.
560 //
561 RewrittenRangeInfo
562 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
563 Value *ExitLoopAt,
564 BasicBlock *ContinuationBlock) const;
565
566 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
567 // function creates a new preheader for `LS' and returns it.
568 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000569 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
570 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000571
572 // `ContinuationBlockAndPreheader' was the continuation block for some call to
573 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
574 // This function rewrites the PHI nodes in `LS.Header' to start with the
575 // correct value.
576 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000577 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000578 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
579
580 // Even though we do not preserve any passes at this time, we at least need to
581 // keep the parent loop structure consistent. The `LPPassManager' seems to
582 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000583 // blocks denoted by BBs to this loops parent loop if required.
584 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000585
586 // Some global state.
587 Function &F;
588 LLVMContext &Ctx;
589 ScalarEvolution &SE;
590
591 // Information about the original loop we started out with.
592 Loop &OriginalLoop;
593 LoopInfo &OriginalLoopInfo;
594 const SCEV *LatchTakenCount;
595 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000596
597 // The preheader of the main loop. This may or may not be different from
598 // `OriginalPreheader'.
599 BasicBlock *MainLoopPreheader;
600
601 // The range we need to run the main loop in.
602 InductiveRangeCheck::Range Range;
603
604 // The structure of the main loop (see comment at the beginning of this class
605 // for a definition)
606 LoopStructure MainLoopStructure;
607
608public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000609 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
610 ScalarEvolution &SE, InductiveRangeCheck::Range R)
611 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
612 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
613 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
614 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000615
616 // Entry point for the algorithm. Returns true on success.
617 bool run();
618};
619
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000620}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621
622void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
623 BasicBlock *ReplaceBy) {
624 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
625 if (PN->getIncomingBlock(i) == Block)
626 PN->setIncomingBlock(i, ReplaceBy);
627}
628
Sanjoy Dase75ed922015-02-26 08:19:31 +0000629static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
630 APInt SMax =
631 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
632 return SE.getSignedRange(S).contains(SMax) &&
633 SE.getUnsignedRange(S).contains(SMax);
634}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000635
Sanjoy Dase75ed922015-02-26 08:19:31 +0000636static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
637 APInt SMin =
638 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
639 return SE.getSignedRange(S).contains(SMin) &&
640 SE.getUnsignedRange(S).contains(SMin);
641}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000642
Sanjoy Dase75ed922015-02-26 08:19:31 +0000643Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000644LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
645 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000646 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
647
648 BasicBlock *Latch = L.getLoopLatch();
649 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000650 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000651 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652 }
653
Sanjoy Dase75ed922015-02-26 08:19:31 +0000654 BasicBlock *Header = L.getHeader();
655 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000656 if (!Preheader) {
657 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000658 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000659 }
660
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000661 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000662 if (!LatchBr || LatchBr->isUnconditional()) {
663 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000664 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000665 }
666
Sanjoy Dase75ed922015-02-26 08:19:31 +0000667 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000668
Sanjoy Dase91665d2015-02-26 08:56:04 +0000669 BranchProbability ExitProbability =
670 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
671
672 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
673 FailureReason = "short running loop, not profitable";
674 return None;
675 }
676
Sanjoy Dase75ed922015-02-26 08:19:31 +0000677 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
678 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
679 FailureReason = "latch terminator branch not conditional on integral icmp";
680 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000681 }
682
Sanjoy Dase75ed922015-02-26 08:19:31 +0000683 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
684 if (isa<SCEVCouldNotCompute>(LatchCount)) {
685 FailureReason = "could not compute latch count";
686 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000687 }
688
Sanjoy Dase75ed922015-02-26 08:19:31 +0000689 ICmpInst::Predicate Pred = ICI->getPredicate();
690 Value *LeftValue = ICI->getOperand(0);
691 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
692 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
693
694 Value *RightValue = ICI->getOperand(1);
695 const SCEV *RightSCEV = SE.getSCEV(RightValue);
696
697 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
698 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
699 if (isa<SCEVAddRecExpr>(RightSCEV)) {
700 std::swap(LeftSCEV, RightSCEV);
701 std::swap(LeftValue, RightValue);
702 Pred = ICmpInst::getSwappedPredicate(Pred);
703 } else {
704 FailureReason = "no add recurrences in the icmp";
705 return None;
706 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000707 }
708
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000709 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
710 if (AR->getNoWrapFlags(SCEV::FlagNSW))
711 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000712
713 IntegerType *Ty = cast<IntegerType>(AR->getType());
714 IntegerType *WideTy =
715 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
716
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000717 const SCEVAddRecExpr *ExtendAfterOp =
718 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
719 if (ExtendAfterOp) {
720 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
721 const SCEV *ExtendedStep =
722 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
723
724 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
725 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
726
727 if (NoSignedWrap)
728 return true;
729 }
730
731 // We may have proved this when computing the sign extension above.
732 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
733 };
734
735 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
736 if (!AR->isAffine())
737 return false;
738
Sanjoy Dase75ed922015-02-26 08:19:31 +0000739 // Currently we only work with induction variables that have been proved to
740 // not wrap. This restriction can potentially be lifted in the future.
741
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000742 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000743 return false;
744
745 if (const SCEVConstant *StepExpr =
746 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
747 ConstantInt *StepCI = StepExpr->getValue();
748 if (StepCI->isOne() || StepCI->isMinusOne()) {
749 IsIncreasing = StepCI->isOne();
750 return true;
751 }
752 }
753
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000754 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000755 };
756
757 // `ICI` is interpreted as taking the backedge if the *next* value of the
758 // induction variable satisfies some constraint.
759
760 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
761 bool IsIncreasing = false;
762 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
763 FailureReason = "LHS in icmp not induction variable";
764 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000765 }
766
Sanjoy Dase75ed922015-02-26 08:19:31 +0000767 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
768 // TODO: generalize the predicates here to also match their unsigned variants.
769 if (IsIncreasing) {
770 bool FoundExpectedPred =
771 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
772 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
773
774 if (!FoundExpectedPred) {
775 FailureReason = "expected icmp slt semantically, found something else";
776 return None;
777 }
778
779 if (LatchBrExitIdx == 0) {
780 if (CanBeSMax(SE, RightSCEV)) {
781 // TODO: this restriction is easily removable -- we just have to
782 // remember that the icmp was an slt and not an sle.
783 FailureReason = "limit may overflow when coercing sle to slt";
784 return None;
785 }
786
787 IRBuilder<> B(&*Preheader->rbegin());
788 RightValue = B.CreateAdd(RightValue, One);
789 }
790
791 } else {
792 bool FoundExpectedPred =
793 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
794 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
795
796 if (!FoundExpectedPred) {
797 FailureReason = "expected icmp sgt semantically, found something else";
798 return None;
799 }
800
801 if (LatchBrExitIdx == 0) {
802 if (CanBeSMin(SE, RightSCEV)) {
803 // TODO: this restriction is easily removable -- we just have to
804 // remember that the icmp was an sgt and not an sge.
805 FailureReason = "limit may overflow when coercing sge to sgt";
806 return None;
807 }
808
809 IRBuilder<> B(&*Preheader->rbegin());
810 RightValue = B.CreateSub(RightValue, One);
811 }
812 }
813
814 const SCEV *StartNext = IndVarNext->getStart();
815 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
816 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
817
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000818 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
819
Sanjoy Dase75ed922015-02-26 08:19:31 +0000820 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000821 ScalarEvolution::LoopInvariant &&
822 "loop variant exit count doesn't make sense!");
823
Sanjoy Dase75ed922015-02-26 08:19:31 +0000824 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 const DataLayout &DL = Preheader->getModule()->getDataLayout();
826 Value *IndVarStartV =
827 SCEVExpander(SE, DL, "irce")
828 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000829 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000830
Sanjoy Dase75ed922015-02-26 08:19:31 +0000831 LoopStructure Result;
832
833 Result.Tag = "main";
834 Result.Header = Header;
835 Result.Latch = Latch;
836 Result.LatchBr = LatchBr;
837 Result.LatchExit = LatchExit;
838 Result.LatchBrExitIdx = LatchBrExitIdx;
839 Result.IndVarStart = IndVarStartV;
840 Result.IndVarNext = LeftValue;
841 Result.IndVarIncreasing = IsIncreasing;
842 Result.LoopExitAt = RightValue;
843
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000844 FailureReason = nullptr;
845
Sanjoy Dase75ed922015-02-26 08:19:31 +0000846 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000847}
848
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000849Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000850LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000851 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
852
Sanjoy Das351db052015-01-22 09:32:02 +0000853 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000854 return None;
855
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000856 LoopConstrainer::SubRanges Result;
857
858 // I think we can be more aggressive here and make this nuw / nsw if the
859 // addition that feeds into the icmp for the latch's terminating branch is nuw
860 // / nsw. In any case, a wrapping 2's complement addition is safe.
861 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000862 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
863 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000864
Sanjoy Dase75ed922015-02-26 08:19:31 +0000865 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000866
Sanjoy Dase75ed922015-02-26 08:19:31 +0000867 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
868 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000869
870 const SCEV *Smallest = nullptr, *Greatest = nullptr;
871
872 if (Increasing) {
873 Smallest = Start;
874 Greatest = End;
875 } else {
876 // These two computations may sign-overflow. Here is why that is okay:
877 //
878 // We know that the induction variable does not sign-overflow on any
879 // iteration except the last one, and it starts at `Start` and ends at
880 // `End`, decrementing by one every time.
881 //
882 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
883 // induction variable is decreasing we know that that the smallest value
884 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
885 //
886 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
887 // that case, `Clamp` will always return `Smallest` and
888 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
889 // will be an empty range. Returning an empty range is always safe.
890 //
891
892 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
893 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
894 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000895
896 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
897 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
898 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000899
900 // In some cases we can prove that we don't need a pre or post loop
901
902 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000903 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
904 if (!ProvablyNoPreloop)
905 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000906
907 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000908 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
909 if (!ProvablyNoPostLoop)
910 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000911
912 return Result;
913}
914
915void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
916 const char *Tag) const {
917 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
918 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
919 Result.Blocks.push_back(Clone);
920 Result.Map[BB] = Clone;
921 }
922
923 auto GetClonedValue = [&Result](Value *V) {
924 assert(V && "null values not in domain!");
925 auto It = Result.Map.find(V);
926 if (It == Result.Map.end())
927 return V;
928 return static_cast<Value *>(It->second);
929 };
930
931 Result.Structure = MainLoopStructure.map(GetClonedValue);
932 Result.Structure.Tag = Tag;
933
934 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
935 BasicBlock *ClonedBB = Result.Blocks[i];
936 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
937
938 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
939
940 for (Instruction &I : *ClonedBB)
941 RemapInstruction(&I, Result.Map,
942 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
943
944 // Exit blocks will now have one more predecessor and their PHI nodes need
945 // to be edited to reflect that. No phi nodes need to be introduced because
946 // the loop is in LCSSA.
947
948 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
949 SBBI != SBBE; ++SBBI) {
950
951 if (OriginalLoop.contains(*SBBI))
952 continue; // not an exit block
953
954 for (Instruction &I : **SBBI) {
955 if (!isa<PHINode>(&I))
956 break;
957
958 PHINode *PN = cast<PHINode>(&I);
959 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
960 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
961 }
962 }
963 }
964}
965
966LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000967 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000968 BasicBlock *ContinuationBlock) const {
969
970 // We start with a loop with a single latch:
971 //
972 // +--------------------+
973 // | |
974 // | preheader |
975 // | |
976 // +--------+-----------+
977 // | ----------------\
978 // | / |
979 // +--------v----v------+ |
980 // | | |
981 // | header | |
982 // | | |
983 // +--------------------+ |
984 // |
985 // ..... |
986 // |
987 // +--------------------+ |
988 // | | |
989 // | latch >----------/
990 // | |
991 // +-------v------------+
992 // |
993 // |
994 // | +--------------------+
995 // | | |
996 // +---> original exit |
997 // | |
998 // +--------------------+
999 //
1000 // We change the control flow to look like
1001 //
1002 //
1003 // +--------------------+
1004 // | |
1005 // | preheader >-------------------------+
1006 // | | |
1007 // +--------v-----------+ |
1008 // | /-------------+ |
1009 // | / | |
1010 // +--------v--v--------+ | |
1011 // | | | |
1012 // | header | | +--------+ |
1013 // | | | | | |
1014 // +--------------------+ | | +-----v-----v-----------+
1015 // | | | |
1016 // | | | .pseudo.exit |
1017 // | | | |
1018 // | | +-----------v-----------+
1019 // | | |
1020 // ..... | | |
1021 // | | +--------v-------------+
1022 // +--------------------+ | | | |
1023 // | | | | | ContinuationBlock |
1024 // | latch >------+ | | |
1025 // | | | +----------------------+
1026 // +---------v----------+ |
1027 // | |
1028 // | |
1029 // | +---------------^-----+
1030 // | | |
1031 // +-----> .exit.selector |
1032 // | |
1033 // +----------v----------+
1034 // |
1035 // +--------------------+ |
1036 // | | |
1037 // | original exit <----+
1038 // | |
1039 // +--------------------+
1040 //
1041
1042 RewrittenRangeInfo RRI;
1043
1044 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1045 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001046 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001047 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001048 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001049
1050 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001051 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001052
1053 IRBuilder<> B(PreheaderJump);
1054
1055 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001056 Value *EnterLoopCond = Increasing
1057 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1058 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1059
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001060 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1061 PreheaderJump->eraseFromParent();
1062
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001063 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001064 B.SetInsertPoint(LS.LatchBr);
1065 Value *TakeBackedgeLoopCond =
1066 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1067 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1068 Value *CondForBranch = LS.LatchBrExitIdx == 1
1069 ? TakeBackedgeLoopCond
1070 : B.CreateNot(TakeBackedgeLoopCond);
1071
1072 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001073
1074 B.SetInsertPoint(RRI.ExitSelector);
1075
1076 // IterationsLeft - are there any more iterations left, given the original
1077 // upper bound on the induction variable? If not, we branch to the "real"
1078 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001079 Value *IterationsLeft = Increasing
1080 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1081 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001082 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1083
1084 BranchInst *BranchToContinuation =
1085 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1086
1087 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1088 // each of the PHI nodes in the loop header. This feeds into the initial
1089 // value of the same PHI nodes if/when we continue execution.
1090 for (Instruction &I : *LS.Header) {
1091 if (!isa<PHINode>(&I))
1092 break;
1093
1094 PHINode *PN = cast<PHINode>(&I);
1095
1096 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1097 BranchToContinuation);
1098
1099 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1100 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1101 RRI.ExitSelector);
1102 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1103 }
1104
Sanjoy Dase75ed922015-02-26 08:19:31 +00001105 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1106 BranchToContinuation);
1107 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1108 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1109
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001110 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1111 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1112 for (Instruction &I : *LS.LatchExit) {
1113 if (PHINode *PN = dyn_cast<PHINode>(&I))
1114 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1115 else
1116 break;
1117 }
1118
1119 return RRI;
1120}
1121
1122void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001123 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001124 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1125
1126 unsigned PHIIndex = 0;
1127 for (Instruction &I : *LS.Header) {
1128 if (!isa<PHINode>(&I))
1129 break;
1130
1131 PHINode *PN = cast<PHINode>(&I);
1132
1133 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1134 if (PN->getIncomingBlock(i) == ContinuationBlock)
1135 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1136 }
1137
Sanjoy Dase75ed922015-02-26 08:19:31 +00001138 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001139}
1140
Sanjoy Dase75ed922015-02-26 08:19:31 +00001141BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1142 BasicBlock *OldPreheader,
1143 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001144
1145 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1146 BranchInst::Create(LS.Header, Preheader);
1147
1148 for (Instruction &I : *LS.Header) {
1149 if (!isa<PHINode>(&I))
1150 break;
1151
1152 PHINode *PN = cast<PHINode>(&I);
1153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1154 replacePHIBlock(PN, OldPreheader, Preheader);
1155 }
1156
1157 return Preheader;
1158}
1159
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001160void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001161 Loop *ParentLoop = OriginalLoop.getParentLoop();
1162 if (!ParentLoop)
1163 return;
1164
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001165 for (BasicBlock *BB : BBs)
1166 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001167}
1168
1169bool LoopConstrainer::run() {
1170 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001171 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1172 Preheader = OriginalLoop.getLoopPreheader();
1173 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1174 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001175
1176 OriginalPreheader = Preheader;
1177 MainLoopPreheader = Preheader;
1178
Sanjoy Dase75ed922015-02-26 08:19:31 +00001179 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001180 if (!MaybeSR.hasValue()) {
1181 DEBUG(dbgs() << "irce: could not compute subranges\n");
1182 return false;
1183 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001184
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001185 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001186 bool Increasing = MainLoopStructure.IndVarIncreasing;
1187 IntegerType *IVTy =
1188 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1189
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001190 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001191 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001192
1193 // It would have been better to make `PreLoop' and `PostLoop'
1194 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1195 // constructor.
1196 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001197 bool NeedsPreLoop =
1198 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1199 bool NeedsPostLoop =
1200 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1201
1202 Value *ExitPreLoopAt = nullptr;
1203 Value *ExitMainLoopAt = nullptr;
1204 const SCEVConstant *MinusOneS =
1205 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1206
1207 if (NeedsPreLoop) {
1208 const SCEV *ExitPreLoopAtSCEV = nullptr;
1209
1210 if (Increasing)
1211 ExitPreLoopAtSCEV = *SR.LowLimit;
1212 else {
1213 if (CanBeSMin(SE, *SR.HighLimit)) {
1214 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1215 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1216 << "\n");
1217 return false;
1218 }
1219 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1220 }
1221
1222 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1223 ExitPreLoopAt->setName("exit.preloop.at");
1224 }
1225
1226 if (NeedsPostLoop) {
1227 const SCEV *ExitMainLoopAtSCEV = nullptr;
1228
1229 if (Increasing)
1230 ExitMainLoopAtSCEV = *SR.HighLimit;
1231 else {
1232 if (CanBeSMin(SE, *SR.LowLimit)) {
1233 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1234 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1235 << "\n");
1236 return false;
1237 }
1238 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1239 }
1240
1241 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1242 ExitMainLoopAt->setName("exit.mainloop.at");
1243 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001244
1245 // We clone these ahead of time so that we don't have to deal with changing
1246 // and temporarily invalid IR as we transform the loops.
1247 if (NeedsPreLoop)
1248 cloneLoop(PreLoop, "preloop");
1249 if (NeedsPostLoop)
1250 cloneLoop(PostLoop, "postloop");
1251
1252 RewrittenRangeInfo PreLoopRRI;
1253
1254 if (NeedsPreLoop) {
1255 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1256 PreLoop.Structure.Header);
1257
1258 MainLoopPreheader =
1259 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001260 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1261 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001262 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1263 PreLoopRRI);
1264 }
1265
1266 BasicBlock *PostLoopPreheader = nullptr;
1267 RewrittenRangeInfo PostLoopRRI;
1268
1269 if (NeedsPostLoop) {
1270 PostLoopPreheader =
1271 createPreheader(PostLoop.Structure, Preheader, "postloop");
1272 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001273 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001274 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1275 PostLoopRRI);
1276 }
1277
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001278 BasicBlock *NewMainLoopPreheader =
1279 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1280 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1281 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1282 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001283
1284 // Some of the above may be nullptr, filter them out before passing to
1285 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001286 auto NewBlocksEnd =
1287 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001288
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001289 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1290 addToParentLoopIfNeeded(PreLoop.Blocks);
1291 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001292
1293 return true;
1294}
1295
Sanjoy Das95c476d2015-02-21 22:20:22 +00001296/// Computes and returns a range of values for the induction variable (IndVar)
1297/// in which the range check can be safely elided. If it cannot compute such a
1298/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001299Optional<InductiveRangeCheck::Range>
1300InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das95c476d2015-02-21 22:20:22 +00001301 const SCEVAddRecExpr *IndVar,
1302 IRBuilder<> &) const {
1303 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1304 // variable, that may or may not exist as a real llvm::Value in the loop) and
1305 // this inductive range check is a range check on the "C + D * I" ("C" is
1306 // getOffset() and "D" is getScale()). We rewrite the value being range
1307 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1308 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1309 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001310 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001311 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001312 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001313 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1314 //
1315 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1316 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001317 //
1318 // Proof:
1319 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001320 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1321 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1322 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1323 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001325 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1326 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001327
Sanjoy Das95c476d2015-02-21 22:20:22 +00001328 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1329 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001330
Sanjoy Das95c476d2015-02-21 22:20:22 +00001331 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001332 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001333
Sanjoy Das95c476d2015-02-21 22:20:22 +00001334 const SCEV *A = IndVar->getStart();
1335 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1336 if (!B)
1337 return None;
1338
1339 const SCEV *C = getOffset();
1340 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1341 if (D != B)
1342 return None;
1343
1344 ConstantInt *ConstD = D->getValue();
1345 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1346 return None;
1347
1348 const SCEV *M = SE.getMinusSCEV(C, A);
1349
1350 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001351 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001352
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001353 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1354 // We can potentially do much better here.
1355 if (Value *V = getLength()) {
1356 UpperLimit = SE.getSCEV(V);
1357 } else {
1358 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1359 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1360 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1361 }
1362
1363 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001364 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001365}
1366
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001367static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001368IntersectRange(ScalarEvolution &SE,
1369 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001370 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1371 if (!R1.hasValue())
1372 return R2;
1373 auto &R1Value = R1.getValue();
1374
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001375 // TODO: we could widen the smaller range and have this work; but for now we
1376 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001377 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001378 return None;
1379
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001380 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1381 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1382
1383 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001384}
1385
1386bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1387 if (L->getBlocks().size() >= LoopSizeCutoff) {
1388 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1389 return false;
1390 }
1391
1392 BasicBlock *Preheader = L->getLoopPreheader();
1393 if (!Preheader) {
1394 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1395 return false;
1396 }
1397
1398 LLVMContext &Context = Preheader->getContext();
1399 InductiveRangeCheck::AllocatorTy IRCAlloc;
1400 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001401 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001402 BranchProbabilityInfo &BPI =
1403 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001404
1405 for (auto BBI : L->getBlocks())
1406 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1407 if (InductiveRangeCheck *IRC =
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001408 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001409 RangeChecks.push_back(IRC);
1410
1411 if (RangeChecks.empty())
1412 return false;
1413
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001414 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1415 OS << "irce: looking at loop "; L->print(OS);
1416 OS << "irce: loop has " << RangeChecks.size()
1417 << " inductive range checks: \n";
1418 for (InductiveRangeCheck *IRC : RangeChecks)
1419 IRC->print(OS);
1420 };
1421
1422 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1423
1424 if (PrintRangeChecks)
1425 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001426
Sanjoy Dase75ed922015-02-26 08:19:31 +00001427 const char *FailureReason = nullptr;
1428 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001429 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001430 if (!MaybeLoopStructure.hasValue()) {
1431 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1432 << "\n";);
1433 return false;
1434 }
1435 LoopStructure LS = MaybeLoopStructure.getValue();
1436 bool Increasing = LS.IndVarIncreasing;
1437 const SCEV *MinusOne =
1438 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1439 const SCEVAddRecExpr *IndVar =
1440 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1441
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001442 Optional<InductiveRangeCheck::Range> SafeIterRange;
1443 Instruction *ExprInsertPt = Preheader->getTerminator();
1444
1445 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1446
1447 IRBuilder<> B(ExprInsertPt);
1448 for (InductiveRangeCheck *IRC : RangeChecks) {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001449 auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001450 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001451 auto MaybeSafeIterRange =
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001452 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001453 if (MaybeSafeIterRange.hasValue()) {
1454 RangeChecksToEliminate.push_back(IRC);
1455 SafeIterRange = MaybeSafeIterRange.getValue();
1456 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001457 }
1458 }
1459
1460 if (!SafeIterRange.hasValue())
1461 return false;
1462
Sanjoy Dase75ed922015-02-26 08:19:31 +00001463 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1464 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001465 bool Changed = LC.run();
1466
1467 if (Changed) {
1468 auto PrintConstrainedLoopInfo = [L]() {
1469 dbgs() << "irce: in function ";
1470 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1471 dbgs() << "constrained ";
1472 L->print(dbgs());
1473 };
1474
1475 DEBUG(PrintConstrainedLoopInfo());
1476
1477 if (PrintChangedLoops)
1478 PrintConstrainedLoopInfo();
1479
1480 // Optimize away the now-redundant range checks.
1481
1482 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1483 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1484 ? ConstantInt::getTrue(Context)
1485 : ConstantInt::getFalse(Context);
1486 IRC->getBranch()->setCondition(FoldedRangeCheck);
1487 }
1488 }
1489
1490 return Changed;
1491}
1492
1493Pass *llvm::createInductiveRangeCheckEliminationPass() {
1494 return new InductiveRangeCheckElimination;
1495}