blob: 5501800196337dc6478177c8bb90d0658cdb8e4f [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/Optional.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000045#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000046#include "llvm/Analysis/InstructionSimplify.h"
47#include "llvm/Analysis/LoopInfo.h"
48#include "llvm/Analysis/LoopPass.h"
49#include "llvm/Analysis/ScalarEvolution.h"
50#include "llvm/Analysis/ScalarEvolutionExpander.h"
51#include "llvm/Analysis/ScalarEvolutionExpressions.h"
52#include "llvm/Analysis/ValueTracking.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/IR/Module.h"
58#include "llvm/IR/PatternMatch.h"
59#include "llvm/IR/ValueHandle.h"
60#include "llvm/IR/Verifier.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000061#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000062#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000063#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064#include "llvm/Transforms/Scalar.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Cloning.h"
67#include "llvm/Transforms/Utils/LoopUtils.h"
68#include "llvm/Transforms/Utils/SimplifyIndVar.h"
69#include "llvm/Transforms/Utils/UnrollLoop.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000070
71using namespace llvm;
72
Benjamin Kramer970eac42015-02-06 17:51:54 +000073static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
74 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000075
Benjamin Kramer970eac42015-02-06 17:51:54 +000076static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
77 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000078
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000079static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
80 cl::init(false));
81
Sanjoy Dase91665d2015-02-26 08:56:04 +000082static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
83 cl::Hidden, cl::init(10));
84
Sanjoy Dasa1837a32015-01-16 01:03:22 +000085#define DEBUG_TYPE "irce"
86
87namespace {
88
89/// An inductive range check is conditional branch in a loop with
90///
91/// 1. a very cold successor (i.e. the branch jumps to that successor very
92/// rarely)
93///
94/// and
95///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000096/// 2. a condition that is provably true for some contiguous range of values
97/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000099class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000100 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000101 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000102 // Range check of the form "0 <= I".
103 RANGE_CHECK_LOWER = 1,
104
105 // Range check of the form "I < L" where L is known positive.
106 RANGE_CHECK_UPPER = 2,
107
108 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
109 // conditions.
110 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
111
112 // Unrecognized range check condition.
113 RANGE_CHECK_UNKNOWN = (unsigned)-1
114 };
115
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000116 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000117
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000118 const SCEV *Offset;
119 const SCEV *Scale;
120 Value *Length;
121 BranchInst *Branch;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122 RangeCheckKind Kind;
123
Sanjoy Das337d46b2015-03-24 19:29:18 +0000124 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
125 ScalarEvolution &SE, Value *&Index,
126 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000127
128 static InductiveRangeCheck::RangeCheckKind
129 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
130 const SCEV *&Index, Value *&UpperLimit);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
132 InductiveRangeCheck() :
133 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
134
135public:
136 const SCEV *getOffset() const { return Offset; }
137 const SCEV *getScale() const { return Scale; }
138 Value *getLength() const { return Length; }
139
140 void print(raw_ostream &OS) const {
141 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000142 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000143 OS << " Offset: ";
144 Offset->print(OS);
145 OS << " Scale: ";
146 Scale->print(OS);
147 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000148 if (Length)
149 Length->print(OS);
150 else
151 OS << "(null)";
152 OS << "\n Branch: ";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000153 getBranch()->print(OS);
Sanjoy Das48c75812015-02-26 04:03:31 +0000154 OS << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 }
156
157#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
158 void dump() {
159 print(dbgs());
160 }
161#endif
162
163 BranchInst *getBranch() const { return Branch; }
164
Sanjoy Das351db052015-01-22 09:32:02 +0000165 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
166 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
167
168 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000169 const SCEV *Begin;
170 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000171
172 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000173 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000174 assert(Begin->getType() == End->getType() && "ill-typed range!");
175 }
176
177 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000178 const SCEV *getBegin() const { return Begin; }
179 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000180 };
181
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000182 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
183
184 /// This is the value the condition of the branch needs to evaluate to for the
185 /// branch to take the hot successor (see (1) above).
186 bool getPassingDirection() { return true; }
187
Sanjoy Das95c476d2015-02-21 22:20:22 +0000188 /// Computes a range for the induction variable (IndVar) in which the range
189 /// check is redundant and can be constant-folded away. The induction
190 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das95c476d2015-02-21 22:20:22 +0000192 const SCEVAddRecExpr *IndVar,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000193 IRBuilder<> &B) const;
194
195 /// Create an inductive range check out of BI if possible, else return
196 /// nullptr.
197 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000198 Loop *L, ScalarEvolution &SE,
199 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000200};
201
202class InductiveRangeCheckElimination : public LoopPass {
203 InductiveRangeCheck::AllocatorTy Allocator;
204
205public:
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 Dase2cde6f2015-03-17 00:42:13 +0000321/// Parses an arbitrary condition into a range check. `Length` is set only if
322/// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
323InductiveRangeCheck::RangeCheckKind
324InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000325 Value *Condition, const SCEV *&Index,
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000326 Value *&Length) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000327 using namespace llvm::PatternMatch;
328
329 Value *A = nullptr;
330 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000331
332 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000333 Value *IndexA = nullptr, *IndexB = nullptr;
334 Value *LengthA = nullptr, *LengthB = nullptr;
335 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000336
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000337 if (!ICmpA || !ICmpB)
338 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000339
Sanjoy Das337d46b2015-03-24 19:29:18 +0000340 auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
341 auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000342
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000343 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
344 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
345 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000346
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000347 if (IndexA != IndexB)
348 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
349
350 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
351 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
352
353 Index = SE.getSCEV(IndexA);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354 if (isa<SCEVCouldNotCompute>(Index))
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000355 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000356
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000357 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000359 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000360 }
361
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000362 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
363 Value *IndexVal = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000364
Sanjoy Das337d46b2015-03-24 19:29:18 +0000365 auto RCKind = parseRangeCheckICmp(L, ICI, SE, IndexVal, Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000366
367 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
368 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
369
370 Index = SE.getSCEV(IndexVal);
371 if (isa<SCEVCouldNotCompute>(Index))
372 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
373
374 return RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000375 }
376
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000377 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000378}
379
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000380
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000381InductiveRangeCheck *
382InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000383 Loop *L, ScalarEvolution &SE,
384 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000385
386 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
387 return nullptr;
388
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000389 BranchProbability LikelyTaken(15, 16);
390
391 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
392 return nullptr;
393
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000394 Value *Length = nullptr;
395 const SCEV *IndexSCEV = nullptr;
396
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000397 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
398 IndexSCEV, Length);
399
400 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000401 return nullptr;
402
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000403 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
David Blaikiec4dfa632015-03-17 17:48:24 +0000404 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
405 "contract with SplitRangeCheckCondition!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000406
407 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
408 bool IsAffineIndex =
409 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
410
411 if (!IsAffineIndex)
412 return nullptr;
413
414 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
415 IRC->Length = Length;
416 IRC->Offset = IndexAddRec->getStart();
417 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
418 IRC->Branch = BI;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000419 IRC->Kind = RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000420 return IRC;
421}
422
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000423namespace {
424
Sanjoy Dase75ed922015-02-26 08:19:31 +0000425// Keeps track of the structure of a loop. This is similar to llvm::Loop,
426// except that it is more lightweight and can track the state of a loop through
427// changing and potentially invalid IR. This structure also formalizes the
428// kinds of loops we can deal with -- ones that have a single latch that is also
429// an exiting block *and* have a canonical induction variable.
430struct LoopStructure {
431 const char *Tag;
432
433 BasicBlock *Header;
434 BasicBlock *Latch;
435
436 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
437 // successor is `LatchExit', the exit block of the loop.
438 BranchInst *LatchBr;
439 BasicBlock *LatchExit;
440 unsigned LatchBrExitIdx;
441
442 Value *IndVarNext;
443 Value *IndVarStart;
444 Value *LoopExitAt;
445 bool IndVarIncreasing;
446
447 LoopStructure()
448 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
449 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
450 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
451
452 template <typename M> LoopStructure map(M Map) const {
453 LoopStructure Result;
454 Result.Tag = Tag;
455 Result.Header = cast<BasicBlock>(Map(Header));
456 Result.Latch = cast<BasicBlock>(Map(Latch));
457 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
458 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
459 Result.LatchBrExitIdx = LatchBrExitIdx;
460 Result.IndVarNext = Map(IndVarNext);
461 Result.IndVarStart = Map(IndVarStart);
462 Result.LoopExitAt = Map(LoopExitAt);
463 Result.IndVarIncreasing = IndVarIncreasing;
464 return Result;
465 }
466
Sanjoy Dase91665d2015-02-26 08:56:04 +0000467 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
468 BranchProbabilityInfo &BPI,
469 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000470 const char *&);
471};
472
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000473/// This class is used to constrain loops to run within a given iteration space.
474/// The algorithm this class implements is given a Loop and a range [Begin,
475/// End). The algorithm then tries to break out a "main loop" out of the loop
476/// it is given in a way that the "main loop" runs with the induction variable
477/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
478/// loops to run any remaining iterations. The pre loop runs any iterations in
479/// which the induction variable is < Begin, and the post loop runs any
480/// iterations in which the induction variable is >= End.
481///
482class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000483 // The representation of a clone of the original loop we started out with.
484 struct ClonedLoop {
485 // The cloned blocks
486 std::vector<BasicBlock *> Blocks;
487
488 // `Map` maps values in the clonee into values in the cloned version
489 ValueToValueMapTy Map;
490
491 // An instance of `LoopStructure` for the cloned loop
492 LoopStructure Structure;
493 };
494
495 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
496 // more details on what these fields mean.
497 struct RewrittenRangeInfo {
498 BasicBlock *PseudoExit;
499 BasicBlock *ExitSelector;
500 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000501 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000502
Sanjoy Dase75ed922015-02-26 08:19:31 +0000503 RewrittenRangeInfo()
504 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000505 };
506
507 // Calculated subranges we restrict the iteration space of the main loop to.
508 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000509 // these fields are computed. `LowLimit` is None if there is no restriction
510 // on low end of the restricted iteration space of the main loop. `HighLimit`
511 // is None if there is no restriction on high end of the restricted iteration
512 // space of the main loop.
513
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000514 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000515 Optional<const SCEV *> LowLimit;
516 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000517 };
518
519 // A utility function that does a `replaceUsesOfWith' on the incoming block
520 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
521 // incoming block list with `ReplaceBy'.
522 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
523 BasicBlock *ReplaceBy);
524
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000525 // Compute a safe set of limits for the main loop to run in -- effectively the
526 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000527 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000528 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000529 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000530
531 // Clone `OriginalLoop' and return the result in CLResult. The IR after
532 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
533 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
534 // but there is no such edge.
535 //
536 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
537
538 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
539 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
540 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
541 // `OriginalHeaderCount'.
542 //
543 // If there are iterations left to execute, control is made to jump to
544 // `ContinuationBlock', otherwise they take the normal loop exit. The
545 // returned `RewrittenRangeInfo' object is populated as follows:
546 //
547 // .PseudoExit is a basic block that unconditionally branches to
548 // `ContinuationBlock'.
549 //
550 // .ExitSelector is a basic block that decides, on exit from the loop,
551 // whether to branch to the "true" exit or to `PseudoExit'.
552 //
553 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
554 // for each PHINode in the loop header on taking the pseudo exit.
555 //
556 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
557 // preheader because it is made to branch to the loop header only
558 // conditionally.
559 //
560 RewrittenRangeInfo
561 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
562 Value *ExitLoopAt,
563 BasicBlock *ContinuationBlock) const;
564
565 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
566 // function creates a new preheader for `LS' and returns it.
567 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000568 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
569 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000570
571 // `ContinuationBlockAndPreheader' was the continuation block for some call to
572 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
573 // This function rewrites the PHI nodes in `LS.Header' to start with the
574 // correct value.
575 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000576 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000577 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
578
579 // Even though we do not preserve any passes at this time, we at least need to
580 // keep the parent loop structure consistent. The `LPPassManager' seems to
581 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000582 // blocks denoted by BBs to this loops parent loop if required.
583 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000584
585 // Some global state.
586 Function &F;
587 LLVMContext &Ctx;
588 ScalarEvolution &SE;
589
590 // Information about the original loop we started out with.
591 Loop &OriginalLoop;
592 LoopInfo &OriginalLoopInfo;
593 const SCEV *LatchTakenCount;
594 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000595
596 // The preheader of the main loop. This may or may not be different from
597 // `OriginalPreheader'.
598 BasicBlock *MainLoopPreheader;
599
600 // The range we need to run the main loop in.
601 InductiveRangeCheck::Range Range;
602
603 // The structure of the main loop (see comment at the beginning of this class
604 // for a definition)
605 LoopStructure MainLoopStructure;
606
607public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000608 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
609 ScalarEvolution &SE, InductiveRangeCheck::Range R)
610 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
611 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
612 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
613 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000614
615 // Entry point for the algorithm. Returns true on success.
616 bool run();
617};
618
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000619}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000620
621void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
622 BasicBlock *ReplaceBy) {
623 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
624 if (PN->getIncomingBlock(i) == Block)
625 PN->setIncomingBlock(i, ReplaceBy);
626}
627
Sanjoy Dase75ed922015-02-26 08:19:31 +0000628static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
629 APInt SMax =
630 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
631 return SE.getSignedRange(S).contains(SMax) &&
632 SE.getUnsignedRange(S).contains(SMax);
633}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000634
Sanjoy Dase75ed922015-02-26 08:19:31 +0000635static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
636 APInt SMin =
637 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
638 return SE.getSignedRange(S).contains(SMin) &&
639 SE.getUnsignedRange(S).contains(SMin);
640}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641
Sanjoy Dase75ed922015-02-26 08:19:31 +0000642Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000643LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
644 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000645 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
646
647 BasicBlock *Latch = L.getLoopLatch();
648 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000649 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000650 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000651 }
652
Sanjoy Dase75ed922015-02-26 08:19:31 +0000653 BasicBlock *Header = L.getHeader();
654 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000655 if (!Preheader) {
656 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000657 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000658 }
659
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000660 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000661 if (!LatchBr || LatchBr->isUnconditional()) {
662 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000663 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000664 }
665
Sanjoy Dase75ed922015-02-26 08:19:31 +0000666 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000667
Sanjoy Dase91665d2015-02-26 08:56:04 +0000668 BranchProbability ExitProbability =
669 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
670
671 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
672 FailureReason = "short running loop, not profitable";
673 return None;
674 }
675
Sanjoy Dase75ed922015-02-26 08:19:31 +0000676 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
677 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
678 FailureReason = "latch terminator branch not conditional on integral icmp";
679 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000680 }
681
Sanjoy Dase75ed922015-02-26 08:19:31 +0000682 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
683 if (isa<SCEVCouldNotCompute>(LatchCount)) {
684 FailureReason = "could not compute latch count";
685 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000686 }
687
Sanjoy Dase75ed922015-02-26 08:19:31 +0000688 ICmpInst::Predicate Pred = ICI->getPredicate();
689 Value *LeftValue = ICI->getOperand(0);
690 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
691 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
692
693 Value *RightValue = ICI->getOperand(1);
694 const SCEV *RightSCEV = SE.getSCEV(RightValue);
695
696 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
697 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
698 if (isa<SCEVAddRecExpr>(RightSCEV)) {
699 std::swap(LeftSCEV, RightSCEV);
700 std::swap(LeftValue, RightValue);
701 Pred = ICmpInst::getSwappedPredicate(Pred);
702 } else {
703 FailureReason = "no add recurrences in the icmp";
704 return None;
705 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000706 }
707
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000708 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
709 if (AR->getNoWrapFlags(SCEV::FlagNSW))
710 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000711
712 IntegerType *Ty = cast<IntegerType>(AR->getType());
713 IntegerType *WideTy =
714 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
715
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000716 const SCEVAddRecExpr *ExtendAfterOp =
717 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
718 if (ExtendAfterOp) {
719 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
720 const SCEV *ExtendedStep =
721 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
722
723 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
724 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
725
726 if (NoSignedWrap)
727 return true;
728 }
729
730 // We may have proved this when computing the sign extension above.
731 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
732 };
733
734 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
735 if (!AR->isAffine())
736 return false;
737
Sanjoy Dase75ed922015-02-26 08:19:31 +0000738 // Currently we only work with induction variables that have been proved to
739 // not wrap. This restriction can potentially be lifted in the future.
740
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000741 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000742 return false;
743
744 if (const SCEVConstant *StepExpr =
745 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
746 ConstantInt *StepCI = StepExpr->getValue();
747 if (StepCI->isOne() || StepCI->isMinusOne()) {
748 IsIncreasing = StepCI->isOne();
749 return true;
750 }
751 }
752
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000753 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000754 };
755
756 // `ICI` is interpreted as taking the backedge if the *next* value of the
757 // induction variable satisfies some constraint.
758
759 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
760 bool IsIncreasing = false;
761 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
762 FailureReason = "LHS in icmp not induction variable";
763 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000764 }
765
Sanjoy Dase75ed922015-02-26 08:19:31 +0000766 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
767 // TODO: generalize the predicates here to also match their unsigned variants.
768 if (IsIncreasing) {
769 bool FoundExpectedPred =
770 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
771 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
772
773 if (!FoundExpectedPred) {
774 FailureReason = "expected icmp slt semantically, found something else";
775 return None;
776 }
777
778 if (LatchBrExitIdx == 0) {
779 if (CanBeSMax(SE, RightSCEV)) {
780 // TODO: this restriction is easily removable -- we just have to
781 // remember that the icmp was an slt and not an sle.
782 FailureReason = "limit may overflow when coercing sle to slt";
783 return None;
784 }
785
786 IRBuilder<> B(&*Preheader->rbegin());
787 RightValue = B.CreateAdd(RightValue, One);
788 }
789
790 } else {
791 bool FoundExpectedPred =
792 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
793 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
794
795 if (!FoundExpectedPred) {
796 FailureReason = "expected icmp sgt semantically, found something else";
797 return None;
798 }
799
800 if (LatchBrExitIdx == 0) {
801 if (CanBeSMin(SE, RightSCEV)) {
802 // TODO: this restriction is easily removable -- we just have to
803 // remember that the icmp was an sgt and not an sge.
804 FailureReason = "limit may overflow when coercing sge to sgt";
805 return None;
806 }
807
808 IRBuilder<> B(&*Preheader->rbegin());
809 RightValue = B.CreateSub(RightValue, One);
810 }
811 }
812
813 const SCEV *StartNext = IndVarNext->getStart();
814 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
815 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
816
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000817 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
818
Sanjoy Dase75ed922015-02-26 08:19:31 +0000819 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000820 ScalarEvolution::LoopInvariant &&
821 "loop variant exit count doesn't make sense!");
822
Sanjoy Dase75ed922015-02-26 08:19:31 +0000823 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000824 const DataLayout &DL = Preheader->getModule()->getDataLayout();
825 Value *IndVarStartV =
826 SCEVExpander(SE, DL, "irce")
827 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000828 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000829
Sanjoy Dase75ed922015-02-26 08:19:31 +0000830 LoopStructure Result;
831
832 Result.Tag = "main";
833 Result.Header = Header;
834 Result.Latch = Latch;
835 Result.LatchBr = LatchBr;
836 Result.LatchExit = LatchExit;
837 Result.LatchBrExitIdx = LatchBrExitIdx;
838 Result.IndVarStart = IndVarStartV;
839 Result.IndVarNext = LeftValue;
840 Result.IndVarIncreasing = IsIncreasing;
841 Result.LoopExitAt = RightValue;
842
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000843 FailureReason = nullptr;
844
Sanjoy Dase75ed922015-02-26 08:19:31 +0000845 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000846}
847
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000848Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000849LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000850 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
851
Sanjoy Das351db052015-01-22 09:32:02 +0000852 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000853 return None;
854
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000855 LoopConstrainer::SubRanges Result;
856
857 // I think we can be more aggressive here and make this nuw / nsw if the
858 // addition that feeds into the icmp for the latch's terminating branch is nuw
859 // / nsw. In any case, a wrapping 2's complement addition is safe.
860 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000861 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
862 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000863
Sanjoy Dase75ed922015-02-26 08:19:31 +0000864 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000865
Sanjoy Dase75ed922015-02-26 08:19:31 +0000866 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
867 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000868
869 const SCEV *Smallest = nullptr, *Greatest = nullptr;
870
871 if (Increasing) {
872 Smallest = Start;
873 Greatest = End;
874 } else {
875 // These two computations may sign-overflow. Here is why that is okay:
876 //
877 // We know that the induction variable does not sign-overflow on any
878 // iteration except the last one, and it starts at `Start` and ends at
879 // `End`, decrementing by one every time.
880 //
881 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
882 // induction variable is decreasing we know that that the smallest value
883 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
884 //
885 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
886 // that case, `Clamp` will always return `Smallest` and
887 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
888 // will be an empty range. Returning an empty range is always safe.
889 //
890
891 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
892 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
893 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000894
895 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
896 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
897 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000898
899 // In some cases we can prove that we don't need a pre or post loop
900
901 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000902 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
903 if (!ProvablyNoPreloop)
904 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000905
906 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000907 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
908 if (!ProvablyNoPostLoop)
909 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000910
911 return Result;
912}
913
914void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
915 const char *Tag) const {
916 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
917 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
918 Result.Blocks.push_back(Clone);
919 Result.Map[BB] = Clone;
920 }
921
922 auto GetClonedValue = [&Result](Value *V) {
923 assert(V && "null values not in domain!");
924 auto It = Result.Map.find(V);
925 if (It == Result.Map.end())
926 return V;
927 return static_cast<Value *>(It->second);
928 };
929
930 Result.Structure = MainLoopStructure.map(GetClonedValue);
931 Result.Structure.Tag = Tag;
932
933 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
934 BasicBlock *ClonedBB = Result.Blocks[i];
935 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
936
937 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
938
939 for (Instruction &I : *ClonedBB)
940 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000941 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000942
943 // Exit blocks will now have one more predecessor and their PHI nodes need
944 // to be edited to reflect that. No phi nodes need to be introduced because
945 // the loop is in LCSSA.
946
947 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
948 SBBI != SBBE; ++SBBI) {
949
950 if (OriginalLoop.contains(*SBBI))
951 continue; // not an exit block
952
953 for (Instruction &I : **SBBI) {
954 if (!isa<PHINode>(&I))
955 break;
956
957 PHINode *PN = cast<PHINode>(&I);
958 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
959 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
960 }
961 }
962 }
963}
964
965LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000966 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000967 BasicBlock *ContinuationBlock) const {
968
969 // We start with a loop with a single latch:
970 //
971 // +--------------------+
972 // | |
973 // | preheader |
974 // | |
975 // +--------+-----------+
976 // | ----------------\
977 // | / |
978 // +--------v----v------+ |
979 // | | |
980 // | header | |
981 // | | |
982 // +--------------------+ |
983 // |
984 // ..... |
985 // |
986 // +--------------------+ |
987 // | | |
988 // | latch >----------/
989 // | |
990 // +-------v------------+
991 // |
992 // |
993 // | +--------------------+
994 // | | |
995 // +---> original exit |
996 // | |
997 // +--------------------+
998 //
999 // We change the control flow to look like
1000 //
1001 //
1002 // +--------------------+
1003 // | |
1004 // | preheader >-------------------------+
1005 // | | |
1006 // +--------v-----------+ |
1007 // | /-------------+ |
1008 // | / | |
1009 // +--------v--v--------+ | |
1010 // | | | |
1011 // | header | | +--------+ |
1012 // | | | | | |
1013 // +--------------------+ | | +-----v-----v-----------+
1014 // | | | |
1015 // | | | .pseudo.exit |
1016 // | | | |
1017 // | | +-----------v-----------+
1018 // | | |
1019 // ..... | | |
1020 // | | +--------v-------------+
1021 // +--------------------+ | | | |
1022 // | | | | | ContinuationBlock |
1023 // | latch >------+ | | |
1024 // | | | +----------------------+
1025 // +---------v----------+ |
1026 // | |
1027 // | |
1028 // | +---------------^-----+
1029 // | | |
1030 // +-----> .exit.selector |
1031 // | |
1032 // +----------v----------+
1033 // |
1034 // +--------------------+ |
1035 // | | |
1036 // | original exit <----+
1037 // | |
1038 // +--------------------+
1039 //
1040
1041 RewrittenRangeInfo RRI;
1042
1043 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1044 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001045 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001046 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001047 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001048
1049 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001050 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001051
1052 IRBuilder<> B(PreheaderJump);
1053
1054 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001055 Value *EnterLoopCond = Increasing
1056 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1057 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1058
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001059 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1060 PreheaderJump->eraseFromParent();
1061
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001062 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001063 B.SetInsertPoint(LS.LatchBr);
1064 Value *TakeBackedgeLoopCond =
1065 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1066 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1067 Value *CondForBranch = LS.LatchBrExitIdx == 1
1068 ? TakeBackedgeLoopCond
1069 : B.CreateNot(TakeBackedgeLoopCond);
1070
1071 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001072
1073 B.SetInsertPoint(RRI.ExitSelector);
1074
1075 // IterationsLeft - are there any more iterations left, given the original
1076 // upper bound on the induction variable? If not, we branch to the "real"
1077 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001078 Value *IterationsLeft = Increasing
1079 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1080 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001081 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1082
1083 BranchInst *BranchToContinuation =
1084 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1085
1086 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1087 // each of the PHI nodes in the loop header. This feeds into the initial
1088 // value of the same PHI nodes if/when we continue execution.
1089 for (Instruction &I : *LS.Header) {
1090 if (!isa<PHINode>(&I))
1091 break;
1092
1093 PHINode *PN = cast<PHINode>(&I);
1094
1095 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1096 BranchToContinuation);
1097
1098 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1099 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1100 RRI.ExitSelector);
1101 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1102 }
1103
Sanjoy Dase75ed922015-02-26 08:19:31 +00001104 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1105 BranchToContinuation);
1106 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1107 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1108
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001109 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1110 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1111 for (Instruction &I : *LS.LatchExit) {
1112 if (PHINode *PN = dyn_cast<PHINode>(&I))
1113 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1114 else
1115 break;
1116 }
1117
1118 return RRI;
1119}
1120
1121void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001122 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001123 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1124
1125 unsigned PHIIndex = 0;
1126 for (Instruction &I : *LS.Header) {
1127 if (!isa<PHINode>(&I))
1128 break;
1129
1130 PHINode *PN = cast<PHINode>(&I);
1131
1132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1133 if (PN->getIncomingBlock(i) == ContinuationBlock)
1134 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1135 }
1136
Sanjoy Dase75ed922015-02-26 08:19:31 +00001137 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001138}
1139
Sanjoy Dase75ed922015-02-26 08:19:31 +00001140BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1141 BasicBlock *OldPreheader,
1142 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001143
1144 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1145 BranchInst::Create(LS.Header, Preheader);
1146
1147 for (Instruction &I : *LS.Header) {
1148 if (!isa<PHINode>(&I))
1149 break;
1150
1151 PHINode *PN = cast<PHINode>(&I);
1152 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1153 replacePHIBlock(PN, OldPreheader, Preheader);
1154 }
1155
1156 return Preheader;
1157}
1158
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001159void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001160 Loop *ParentLoop = OriginalLoop.getParentLoop();
1161 if (!ParentLoop)
1162 return;
1163
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001164 for (BasicBlock *BB : BBs)
1165 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001166}
1167
1168bool LoopConstrainer::run() {
1169 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001170 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1171 Preheader = OriginalLoop.getLoopPreheader();
1172 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1173 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001174
1175 OriginalPreheader = Preheader;
1176 MainLoopPreheader = Preheader;
1177
Sanjoy Dase75ed922015-02-26 08:19:31 +00001178 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001179 if (!MaybeSR.hasValue()) {
1180 DEBUG(dbgs() << "irce: could not compute subranges\n");
1181 return false;
1182 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001183
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001184 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001185 bool Increasing = MainLoopStructure.IndVarIncreasing;
1186 IntegerType *IVTy =
1187 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1188
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001189 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001190 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001191
1192 // It would have been better to make `PreLoop' and `PostLoop'
1193 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1194 // constructor.
1195 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001196 bool NeedsPreLoop =
1197 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1198 bool NeedsPostLoop =
1199 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1200
1201 Value *ExitPreLoopAt = nullptr;
1202 Value *ExitMainLoopAt = nullptr;
1203 const SCEVConstant *MinusOneS =
1204 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1205
1206 if (NeedsPreLoop) {
1207 const SCEV *ExitPreLoopAtSCEV = nullptr;
1208
1209 if (Increasing)
1210 ExitPreLoopAtSCEV = *SR.LowLimit;
1211 else {
1212 if (CanBeSMin(SE, *SR.HighLimit)) {
1213 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1214 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1215 << "\n");
1216 return false;
1217 }
1218 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1219 }
1220
1221 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1222 ExitPreLoopAt->setName("exit.preloop.at");
1223 }
1224
1225 if (NeedsPostLoop) {
1226 const SCEV *ExitMainLoopAtSCEV = nullptr;
1227
1228 if (Increasing)
1229 ExitMainLoopAtSCEV = *SR.HighLimit;
1230 else {
1231 if (CanBeSMin(SE, *SR.LowLimit)) {
1232 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1233 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1234 << "\n");
1235 return false;
1236 }
1237 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1238 }
1239
1240 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1241 ExitMainLoopAt->setName("exit.mainloop.at");
1242 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001243
1244 // We clone these ahead of time so that we don't have to deal with changing
1245 // and temporarily invalid IR as we transform the loops.
1246 if (NeedsPreLoop)
1247 cloneLoop(PreLoop, "preloop");
1248 if (NeedsPostLoop)
1249 cloneLoop(PostLoop, "postloop");
1250
1251 RewrittenRangeInfo PreLoopRRI;
1252
1253 if (NeedsPreLoop) {
1254 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1255 PreLoop.Structure.Header);
1256
1257 MainLoopPreheader =
1258 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001259 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1260 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001261 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1262 PreLoopRRI);
1263 }
1264
1265 BasicBlock *PostLoopPreheader = nullptr;
1266 RewrittenRangeInfo PostLoopRRI;
1267
1268 if (NeedsPostLoop) {
1269 PostLoopPreheader =
1270 createPreheader(PostLoop.Structure, Preheader, "postloop");
1271 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001272 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001273 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1274 PostLoopRRI);
1275 }
1276
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001277 BasicBlock *NewMainLoopPreheader =
1278 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1279 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1280 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1281 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001282
1283 // Some of the above may be nullptr, filter them out before passing to
1284 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001285 auto NewBlocksEnd =
1286 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001287
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001288 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1289 addToParentLoopIfNeeded(PreLoop.Blocks);
1290 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001291
1292 return true;
1293}
1294
Sanjoy Das95c476d2015-02-21 22:20:22 +00001295/// Computes and returns a range of values for the induction variable (IndVar)
1296/// in which the range check can be safely elided. If it cannot compute such a
1297/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001298Optional<InductiveRangeCheck::Range>
1299InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das95c476d2015-02-21 22:20:22 +00001300 const SCEVAddRecExpr *IndVar,
1301 IRBuilder<> &) const {
1302 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1303 // variable, that may or may not exist as a real llvm::Value in the loop) and
1304 // this inductive range check is a range check on the "C + D * I" ("C" is
1305 // getOffset() and "D" is getScale()). We rewrite the value being range
1306 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1307 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1308 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001309 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001310 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001311 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001312 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1313 //
1314 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1315 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001316 //
1317 // Proof:
1318 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001319 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1320 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1321 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1322 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001323 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001324 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1325 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001326
Sanjoy Das95c476d2015-02-21 22:20:22 +00001327 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1328 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329
Sanjoy Das95c476d2015-02-21 22:20:22 +00001330 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001331 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001332
Sanjoy Das95c476d2015-02-21 22:20:22 +00001333 const SCEV *A = IndVar->getStart();
1334 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1335 if (!B)
1336 return None;
1337
1338 const SCEV *C = getOffset();
1339 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1340 if (D != B)
1341 return None;
1342
1343 ConstantInt *ConstD = D->getValue();
1344 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1345 return None;
1346
1347 const SCEV *M = SE.getMinusSCEV(C, A);
1348
1349 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001350 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001351
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001352 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1353 // We can potentially do much better here.
1354 if (Value *V = getLength()) {
1355 UpperLimit = SE.getSCEV(V);
1356 } else {
1357 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1358 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1359 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1360 }
1361
1362 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001363 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001364}
1365
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001366static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001367IntersectRange(ScalarEvolution &SE,
1368 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001369 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1370 if (!R1.hasValue())
1371 return R2;
1372 auto &R1Value = R1.getValue();
1373
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001374 // TODO: we could widen the smaller range and have this work; but for now we
1375 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001376 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001377 return None;
1378
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001379 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1380 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1381
1382 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001383}
1384
1385bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001386 if (skipLoop(L))
1387 return false;
1388
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001389 if (L->getBlocks().size() >= LoopSizeCutoff) {
1390 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1391 return false;
1392 }
1393
1394 BasicBlock *Preheader = L->getLoopPreheader();
1395 if (!Preheader) {
1396 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1397 return false;
1398 }
1399
1400 LLVMContext &Context = Preheader->getContext();
1401 InductiveRangeCheck::AllocatorTy IRCAlloc;
1402 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001403 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001404 BranchProbabilityInfo &BPI =
1405 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001406
1407 for (auto BBI : L->getBlocks())
1408 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1409 if (InductiveRangeCheck *IRC =
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001410 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001411 RangeChecks.push_back(IRC);
1412
1413 if (RangeChecks.empty())
1414 return false;
1415
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001416 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1417 OS << "irce: looking at loop "; L->print(OS);
1418 OS << "irce: loop has " << RangeChecks.size()
1419 << " inductive range checks: \n";
1420 for (InductiveRangeCheck *IRC : RangeChecks)
1421 IRC->print(OS);
1422 };
1423
1424 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1425
1426 if (PrintRangeChecks)
1427 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001428
Sanjoy Dase75ed922015-02-26 08:19:31 +00001429 const char *FailureReason = nullptr;
1430 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001431 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001432 if (!MaybeLoopStructure.hasValue()) {
1433 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1434 << "\n";);
1435 return false;
1436 }
1437 LoopStructure LS = MaybeLoopStructure.getValue();
1438 bool Increasing = LS.IndVarIncreasing;
1439 const SCEV *MinusOne =
1440 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1441 const SCEVAddRecExpr *IndVar =
1442 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1443
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001444 Optional<InductiveRangeCheck::Range> SafeIterRange;
1445 Instruction *ExprInsertPt = Preheader->getTerminator();
1446
1447 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1448
1449 IRBuilder<> B(ExprInsertPt);
1450 for (InductiveRangeCheck *IRC : RangeChecks) {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001451 auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001452 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001453 auto MaybeSafeIterRange =
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001454 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001455 if (MaybeSafeIterRange.hasValue()) {
1456 RangeChecksToEliminate.push_back(IRC);
1457 SafeIterRange = MaybeSafeIterRange.getValue();
1458 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001459 }
1460 }
1461
1462 if (!SafeIterRange.hasValue())
1463 return false;
1464
Sanjoy Dase75ed922015-02-26 08:19:31 +00001465 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1466 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001467 bool Changed = LC.run();
1468
1469 if (Changed) {
1470 auto PrintConstrainedLoopInfo = [L]() {
1471 dbgs() << "irce: in function ";
1472 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1473 dbgs() << "constrained ";
1474 L->print(dbgs());
1475 };
1476
1477 DEBUG(PrintConstrainedLoopInfo());
1478
1479 if (PrintChangedLoops)
1480 PrintConstrainedLoopInfo();
1481
1482 // Optimize away the now-redundant range checks.
1483
1484 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1485 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1486 ? ConstantInt::getTrue(Context)
1487 : ConstantInt::getFalse(Context);
1488 IRC->getBranch()->setCondition(FoldedRangeCheck);
1489 }
1490 }
1491
1492 return Changed;
1493}
1494
1495Pass *llvm::createInductiveRangeCheckEliminationPass() {
1496 return new InductiveRangeCheckElimination;
1497}